'use client';

/**
 * Phase 7 (2026-04-29) — Lightbox confirmation bakchich proposé.
 *
 * Affichée quand l'issue 'bakchich' est tirée par le tirage pondéré.
 * Le joueur accepte (débit + libéré) ou refuse (flow continue).
 *
 * Phase 7 i18n (2026-04-29) — toutes les strings via t()/tFmt() vers
 * locales fr.json/en.json/es.json (namespace judicial.bakchich).
 */
import { useState } from 'react';
import { createPortal } from 'react-dom';
import { api } from '@/lib/api';
import { t, tFmt } from '@/lib/i18n';
import { HandCoins, X } from 'lucide-react';

interface BakchichConfirmProps {
  info: {
    record_id: string;
    step: 'garde_a_vue' | 'jugement';
    kind: 'gav' | 'juge';
    amount: number;
  };
  onClose: () => void;
  onResult: (flavor: string) => void;
}

export function BakchichConfirm({ info, onClose, onResult }: BakchichConfirmProps) {
  const [busy, setBusy] = useState<'accept' | 'refuse' | null>(null);
  const [error, setError] = useState<string | null>(null);

  const respond = async (accepts: boolean) => {
    setBusy(accepts ? 'accept' : 'refuse');
    setError(null);
    try {
      const r = await api.judicialFlow.respondToBakchich(info.record_id, accepts);
      onResult(r.flavor);
    } catch (e: any) {
      setError(e?.message || t('judicial.bakchich.response_error'));
    } finally {
      setBusy(null);
    }
  };

  if (typeof document === 'undefined') return null;

  return createPortal(
    <div
      className="fixed inset-0 z-[10000] flex items-center justify-center"
      style={{ background: 'rgba(0,0,0,0.85)' }}
      onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}
    >
      <div
        className="w-full max-w-md rounded-xl p-5 relative"
        style={{ background: 'var(--bg-panel)', border: '1px solid var(--color-red)' }}
      >
        <button onClick={onClose} className="absolute top-3 right-3 p-1 hover:opacity-70">
          <X size={18} style={{ color: 'var(--text-muted)' }} />
        </button>

        <div className="flex items-center gap-2 mb-3">
          <HandCoins size={18} style={{ color: 'var(--color-red-light)' }} />
          <h2 className="font-gothic text-base" style={{ color: 'var(--color-red-light)' }}>
            {info.kind === 'gav' ? t('judicial.bakchich.title_commissioner') : t('judicial.bakchich.title_judge')}
          </h2>
        </div>

        <p className="text-[12px] mb-4" style={{ color: 'var(--text-secondary)' }}>
          {info.kind === 'gav'
            ? tFmt('judicial.bakchich.quote_gav', { amount: info.amount.toLocaleString('fr-FR') })
            : tFmt('judicial.bakchich.quote_judge', { amount: info.amount.toLocaleString('fr-FR') })}
        </p>

        {error && (
          <p className="text-[11px] mb-2" style={{ color: 'var(--color-red-light)' }}>{error}</p>
        )}

        <div className="grid grid-cols-2 gap-2">
          <button
            onClick={() => respond(true)}
            disabled={!!busy}
            className="py-2 rounded font-bold text-[11px] uppercase tracking-[.1em] disabled:opacity-50"
            style={{
              background: 'linear-gradient(135deg, rgba(34,197,94,0.4), rgba(14,14,22,0.9))',
              border: '1px solid rgba(34,197,94,0.6)',
              color: '#86efac',
              cursor: 'pointer',
            }}>
            {busy === 'accept' ? t('judicial.bakchich.accept_progress') : t('judicial.bakchich.accept')}
          </button>
          <button
            onClick={() => respond(false)}
            disabled={!!busy}
            className="py-2 rounded font-bold text-[11px] uppercase tracking-[.1em] disabled:opacity-50"
            style={{
              background: 'rgba(239,68,68,0.18)',
              border: '1px solid rgba(239,68,68,0.5)',
              color: '#fca5a5',
              cursor: 'pointer',
            }}>
            {busy === 'refuse' ? t('judicial.bakchich.refuse_progress') : t('judicial.bakchich.refuse')}
          </button>
        </div>

        <p className="text-[9px] italic mt-3" style={{ color: 'var(--text-muted)' }}>
          {info.kind === 'gav' ? t('judicial.bakchich.consequences_gav') : t('judicial.bakchich.consequences_judge')}
        </p>
      </div>
    </div>,
    document.body,
  );
}
