'use client';

import { forwardRef, type ButtonHTMLAttributes, type ReactNode } from 'react';
import {
  Tooltip,
  TooltipContent,
  TooltipTrigger,
} from '@djangocfg/ui-core/components';

type Props = {
  label: string;
  // Keyboard shortcut hint shown in the tooltip (e.g. "L" for loop). Optional.
  shortcut?: string;
  active?: boolean;
  children: ReactNode;
  // Render the button without the tooltip wrapper. Useful for inline contexts
  // (e.g. inside another tooltip / popover) where nesting Radix portals is
  // unnecessary.
  noTooltip?: boolean;
} & Omit<ButtonHTMLAttributes<HTMLButtonElement>, 'children' | 'aria-label'>;

// `forwardRef` is mandatory: this button is used as `<PopoverTrigger asChild>`
// in VolumeControl. Without ref forwarding, Radix can't anchor the popper to
// the trigger, and `<PopoverContent>` renders with zero rect (invisible).
export const IconButton = forwardRef<HTMLButtonElement, Props>(function IconButton(
  { label, shortcut, active, children, noTooltip, className = '', ...rest },
  ref,
) {
  // Active state uses a tinted primary surface — readable, on-brand, not loud.
  const stateClasses = active
    ? 'bg-primary/10 text-primary hover:bg-primary/15'
    : 'text-muted-foreground hover:bg-accent hover:text-foreground';
  const button = (
    <button
      ref={ref}
      type="button"
      aria-label={label}
      aria-pressed={active}
      className={`audioplayer-press grid h-8 w-8 place-items-center rounded-md transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/60 disabled:opacity-50 disabled:pointer-events-none ${stateClasses} ${className}`}
      {...rest}
    >
      {children}
    </button>
  );
  if (noTooltip) return button;
  return (
    <Tooltip>
      <TooltipTrigger asChild>{button}</TooltipTrigger>
      <TooltipContent side="top">
        <span className="flex items-center gap-1.5">
          {label}
          {shortcut && (
            <kbd className="rounded border border-border/40 bg-muted px-1 font-mono text-[10px] text-muted-foreground">
              {shortcut}
            </kbd>
          )}
        </span>
      </TooltipContent>
    </Tooltip>
  );
});
