'use client';

/**
 * Mute / unmute toggle for chat audio events.
 *
 * Reads the current ``muted`` state from the active chat context and
 * persists changes through ``useChatAudioPrefs`` (cross-tab safe). The
 * button auto-hides when no ``audio.sounds`` config is provided —
 * showing a mute toggle for a chat with no sounds is just clutter.
 *
 * Drop into a ChatRoot ``header`` slot or anywhere inside a chat
 * provider:
 *
 * ```tsx
 * <ChatRoot
 *   header={<AudioToggle />}
 *   audio={{ sounds: { messageReceived: '/ping.mp3' } }}
 *   ...
 * />
 * ```
 */

import { Volume2, VolumeX } from 'lucide-react';

import { Button } from '@djangocfg/ui-core/components';
import { cn } from '@djangocfg/ui-core/lib';

import { useChatContextOptional } from '../context';
import { useChatAudioPrefs } from '../core/audio/preferences';

export interface AudioToggleProps {
  /** Visual size — matches Button sizes. Default: ``icon``. */
  size?: 'sm' | 'icon';
  /** Variant passed to the underlying Button. Default: ``ghost``. */
  variant?: 'ghost' | 'outline' | 'secondary';
  /** Force-show even when no audio config is wired (e.g. for stories). */
  alwaysShow?: boolean;
  className?: string;
}

export function AudioToggle({
  size = 'icon',
  variant = 'ghost',
  alwaysShow = false,
  className,
}: AudioToggleProps) {
  // Read straight from the persist store so the toggle works even
  // when rendered OUTSIDE the ChatRoot (e.g. in a parent header). The
  // chat audio bus reads the same store, so a click here flips the
  // "muted" state for any sibling ChatRoot in the same tab and
  // mirrors across tabs via the storage event.
  const muted = useChatAudioPrefs((s) => s.muted);
  const setMuted = useChatAudioPrefs((s) => s.setMuted);

  // If a ChatRoot is in scope, hide unless it actually wired sounds —
  // otherwise the button is a no-op for that surface. When rendered
  // standalone (no context), default to visible.
  const ctx = useChatContextOptional();
  if (ctx && !ctx.hasAudio && !alwaysShow) return null;

  const Icon = muted ? VolumeX : Volume2;
  const label = muted ? 'Unmute chat sounds' : 'Mute chat sounds';

  return (
    <Button
      type="button"
      variant={variant}
      size={size}
      onClick={() => setMuted(!muted)}
      aria-label={label}
      aria-pressed={muted}
      title={label}
      className={cn(size === 'icon' ? 'h-9 w-9' : '', className)}
    >
      <Icon aria-hidden className="size-4" />
    </Button>
  );
}
