import { useTranslation } from 'react-i18next';
import type { PipController } from '../../lib/usePictureInPicture.js';

interface Props {
  pip: PipController;
  className?: string;
  /**
   * Hide the button entirely if Document PiP is unsupported. Default true.
   * Set false to render a disabled "PiP 非対応" tag with an explanatory
   * tooltip — useful when you want to surface why PiP isn't available.
   */
  hideWhenUnsupported?: boolean;
}

const REASON_HINT_KEY: Record<string, string> = {
  browser: 'pip.reason.browser',
  'insecure-context': 'pip.reason.insecureContext',
  iframe: 'pip.reason.iframe',
};

/**
 * Small toolbar button that toggles a Document Picture-in-Picture window for
 * a noVNC iframe. Surfaces `lastError` from the controller as the title
 * tooltip + a one-line indicator below the button so failed clicks aren't
 * silent (Document PiP can fail for several reasons — popup blocker, missing
 * user gesture, iframe permission policy, etc).
 */
export function PipButton({ pip, className, hideWhenUnsupported = true }: Props) {
  const { t } = useTranslation('browser');
  if (!pip.supported && hideWhenUnsupported) return null;

  const baseClass = 'text-2xs px-2 py-1 rounded-md border border-hairline bg-canvas hover:bg-surface text-slate-700 disabled:opacity-50';
  const merged = className ? `${baseClass} ${className}` : baseClass;

  if (!pip.supported) {
    const hintKey = REASON_HINT_KEY[pip.unsupportedReason ?? 'browser'] ?? REASON_HINT_KEY.browser;
    return (
      <button type="button" disabled className={merged} title={t(hintKey)}>
        {t('pip.unsupportedTag')}
      </button>
    );
  }

  const tooltip = pip.lastError
    ? t('pip.lastError', { error: pip.lastError })
    : pip.isOpen
      ? t('pip.closeTooltip')
      : t('pip.openTooltip');

  return (
    <span className="inline-flex items-center gap-2">
      <button
        type="button"
        onClick={() => {
          if (pip.isOpen) pip.close();
          else void pip.open();
        }}
        className={merged}
        title={tooltip}
      >
        {pip.isOpen ? t('pip.return') : t('pip.open')}
      </button>
      {pip.lastError && !pip.isOpen && (
        <span
          className="text-[10px] text-rose-600 max-w-[260px] truncate"
          title={pip.lastError}
        >
          {pip.lastError}
        </span>
      )}
    </span>
  );
}
