/**
 * The music control in the header.
 *
 * A single button toggles it; the caret opens the track list. The button's
 * label distinguishes three states rather than two, because "on but waiting
 * for a click" is a real state the browser puts us in and a speaker icon that
 * claims to be playing when nothing is audible is the confusing part.
 */
import { ChevronDown, Music, Volume2, VolumeX } from 'lucide-react';
import { PLATFORM_TRACKS, usePlatformAudio } from '@/lib/audio';
import { Button, cn } from './ui';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuLabel,
  DropdownMenuSeparator,
  DropdownMenuTrigger,
} from './ui/dropdown-menu';

export function AudioControl({ className }: { className?: string }) {
  const audio = usePlatformAudio();
  if (!audio) return null;

  const { enabled, playing, track, toggle, setTrack } = audio;
  const current = PLATFORM_TRACKS.find((entry) => entry.id === track);
  const label = !enabled
    ? 'Play platform music'
    : playing
      ? `Mute platform music (${current?.label})`
      : 'Music starts when you interact with the page';

  return (
    <div className={cn('flex items-center', className)}>
      <Button
        type="button"
        variant="ghost"
        size="icon"
        onClick={toggle}
        aria-pressed={enabled}
        aria-label={label}
        title={label}
        className={cn(enabled ? 'text-fg' : 'text-muted')}
      >
        {enabled ? <Volume2 className="size-4" /> : <VolumeX className="size-4" />}
      </Button>

      <DropdownMenu>
        <DropdownMenuTrigger asChild>
          <Button
            type="button"
            variant="ghost"
            size="icon"
            aria-label="Choose a track"
            // The track list used to hang off a 20px-wide caret, which is the
            // smallest target in the product and sits on the sign-in screen,
            // where a mis-tap mutes the music instead of opening the list.
            className="-ml-2 text-muted"
          >
            <ChevronDown className="size-3.5" />
          </Button>
        </DropdownMenuTrigger>
        <DropdownMenuContent align="end" className="w-52">
          <DropdownMenuLabel className="flex items-center gap-2">
            <Music className="size-3.5" aria-hidden />
            Platform music
          </DropdownMenuLabel>
          <DropdownMenuSeparator />
          {PLATFORM_TRACKS.map((entry) => (
            <DropdownMenuItem
              key={entry.id}
              onSelect={() => setTrack(entry.id)}
              className={cn(entry.id === track && 'font-medium text-accent-fg')}
            >
              {entry.label}
              {entry.id === track ? <span className="ml-auto text-xs">playing</span> : null}
            </DropdownMenuItem>
          ))}
        </DropdownMenuContent>
      </DropdownMenu>
    </div>
  );
}
