'use client';

import { Fragment } from 'react';

import { useChatContext } from '../../context';
import type { UseChatDockPrefsReturn } from '../../hooks/useChatDockPrefs';

import { ChatHeaderAudioToggle } from './ChatHeaderAudioToggle';
import { ChatHeaderLanguageButton } from './ChatHeaderLanguageButton';
import { ChatHeaderModeToggle } from './ChatHeaderModeToggle';
import { ChatHeaderResetButton } from './ChatHeaderResetButton';
import type { ResolvedChatHeaderSlots } from '../types';

export interface HeaderSlotsRendererProps {
  slots: ResolvedChatHeaderSlots;
  /**
   * Shared dock-prefs instance owned by `<ChatLauncher>`. The mode
   * toggle MUST use the same instance the dock reads from — a separate
   * `useChatDockPrefs` call would hold isolated state and the toggle
   * would no-op.
   */
  dockPrefs: UseChatDockPrefsReturn;
}

/**
 * Renders the declarative `headerSlots` config inside the
 * `<ChatProvider>` mounted by `<ChatLauncher>`.
 *
 * Order (left → right, before the close icon):
 *   custom · languagePicker · modeToggle · audio · reset
 */
export function HeaderSlotsRenderer({ slots, dockPrefs }: HeaderSlotsRendererProps) {
  const ctx = useChatContext();
  return (
    <>
      {slots.custom ? <Fragment>{slots.custom(ctx)}</Fragment> : null}
      {slots.languagePicker ? (
        <ChatHeaderLanguageButton
          allowedTags={slots.languagePicker.allowedTags}
          ariaLabel={slots.languagePicker.ariaLabel}
          hideFallbackIcon={slots.languagePicker.hideFallbackIcon}
        />
      ) : null}
      {slots.modeToggle ? (
        <ModeToggleSlot slot={slots.modeToggle} dockPrefs={dockPrefs} />
      ) : null}
      {slots.audio && !ctx.audio.isSilent ? (
        <ChatHeaderAudioToggle
          muted={ctx.audio.muted}
          onToggle={ctx.audio.toggleMute}
        />
      ) : null}
      {slots.reset && ctx.sessionId ? <ResetSlot slot={slots.reset} /> : null}
    </>
  );
}

function ModeToggleSlot({
  slot,
  dockPrefs,
}: {
  slot: NonNullable<ResolvedChatHeaderSlots['modeToggle']>;
  dockPrefs: UseChatDockPrefsReturn;
}) {
  return (
    <ChatHeaderModeToggle
      mode={dockPrefs.mode}
      onToggle={dockPrefs.toggleMode}
      forceVisible={slot.forceVisible ?? true}
      expandLabel={slot.expandLabel}
      collapseLabel={slot.collapseLabel}
    />
  );
}

function ResetSlot({
  slot,
}: {
  slot: NonNullable<ResolvedChatHeaderSlots['reset']>;
}) {
  const ctx = useChatContext();
  const handleSuccess = () => {
    if (slot.onSuccess) {
      slot.onSuccess(ctx);
      return;
    }
    ctx.clearMessages();
  };
  return (
    <ChatHeaderResetButton
      onReset={slot.onReset}
      onSuccess={handleSuccess}
      onError={slot.onError}
      confirm={slot.confirm}
      confirmTitle={slot.confirmTitle}
      confirmMessage={slot.confirmMessage}
      ariaLabel={slot.ariaLabel}
    />
  );
}
