'use client';

/**
 * Phase 7 (2026-04-29) — Sub-component Jugement.
 *
 * 4 boutons + porte-document :
 *   - Garder le silence (peine pleine)
 *   - Avocat commis d'office (2000-20000∞L selon chaleur)
 *   - Avocat personnel (gratuit si attaché)
 *   - Bakchich direct juge (5000-50000∞S selon chaleur+crime)
 *   - "Mes documents" → JudicialPorteDocument lightbox (Alibi/Jurisprudence/Vice)
 *
 * Phase 7 i18n (2026-04-29) — toutes les strings via t()/tFmt().
 */
import { useState } from 'react';
import { api, type JudicialActiveFlow } from '@/lib/api';
import { t, tFmt } from '@/lib/i18n';
import { Mic, Scale, Star, HandCoins, FileText } from 'lucide-react';
import { JudicialPorteDocument } from './JudicialPorteDocument';

interface JugementStepProps {
  active: JudicialActiveFlow;
  onResult: (flavor: string) => void;
  onError: (msg: string) => void;
}

function computeOfficeJugementCost(chaleur: number): number {
  const c = Math.max(0, Math.min(100, chaleur));
  return Math.min(20000, Math.round(2000 + c * 180));
}

function computeBakchichJugeAmount(chaleur: number, degree: number, isViolent: boolean): number {
  const raw = 5000 + chaleur * 200 + degree * 5000 + (isViolent ? 5000 : 0);
  return Math.min(50000, Math.round(raw));
}

export function JugementStep({ active, onResult, onError }: JugementStepProps) {
  const [busy, setBusy] = useState<string | null>(null);
  const [docsOpen, setDocsOpen] = useState(false);
  const ctx = active.context;
  const stars = Math.max(1, Math.min(5, Math.ceil(ctx.lawyer_skill / 2)));
  const hasPersonalLawyer = ctx.lawyer_skill > 3;
  const officeCost = computeOfficeJugementCost(ctx.chaleur);
  const bakchichAmount = computeBakchichJugeAmount(ctx.chaleur, ctx.degree, ctx.is_violent);
  const cantAffordOffice = ctx.light_balance < officeCost;
  const cantAffordBakchich = ctx.shadow_balance < bakchichAmount;
  const insufFunds = t('judicial.gav.insufficient_funds');

  const submit = async (choice: 'silence' | 'office' | 'personal' | 'bakchich_direct') => {
    setBusy(choice);
    onError('');
    try {
      const r = await api.judicialFlow.chooseLawyer(active.record_id, choice);
      onResult(r.flavor);
    } catch (e: any) {
      onError(e?.message || t('judicial.flow.action_impossible'));
    } finally {
      setBusy(null);
    }
  };

  return (
    <div className="space-y-2">
      <p className="text-[11px] mb-3" style={{ color: 'var(--text-secondary)' }}>
        {t('judicial.jugement.intro_prefix')}
        <br />
        <span className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
          {tFmt('judicial.flow.sentence_label', { days: active.sentence_days })}
        </span>
      </p>

      {/* Garder le silence */}
      <button
        onClick={() => submit('silence')}
        disabled={!!busy}
        className="w-full p-3 rounded text-left disabled:opacity-50"
        style={{
          background: 'rgba(255,255,255,0.03)',
          border: '1px solid rgba(255,255,255,0.1)',
        }}>
        <div className="flex items-center gap-2 mb-1">
          <Mic size={12} style={{ color: 'var(--text-muted)' }} />
          <span className="text-[11px] font-bold" style={{ color: 'var(--text-primary)' }}>{t('judicial.gav.silence_title')}</span>
          <span className="ml-auto text-[10px]" style={{ color: 'var(--text-muted)' }}>0 ∞</span>
        </div>
        <p className="text-[9px]" style={{ color: 'var(--text-muted)' }}>
          {tFmt('judicial.jugement.silence_desc', { days: active.sentence_days })}
        </p>
        {busy === 'silence' && <p className="text-[9px] mt-1" style={{ color: 'var(--text-muted)' }}>{t('judicial.gav.silence_progress')}</p>}
      </button>

      {/* Avocat commis d'office */}
      <button
        onClick={() => submit('office')}
        disabled={!!busy || cantAffordOffice}
        className="w-full p-3 rounded text-left disabled:opacity-50"
        style={{
          background: 'rgba(255,255,255,0.03)',
          border: '1px solid rgba(255,255,255,0.1)',
          cursor: cantAffordOffice ? 'not-allowed' : 'pointer',
        }}>
        <div className="flex items-center gap-2 mb-1">
          <Scale size={12} style={{ color: 'var(--color-gold-light)' }} />
          <span className="text-[11px] font-bold" style={{ color: 'var(--text-primary)' }}>{t('judicial.gav.office_title')}</span>
          <span className="ml-auto text-[10px]" style={{ color: cantAffordOffice ? '#fca5a5' : 'var(--color-gold-light)' }}>
            {tFmt('judicial.gav.cost_light', { cost: officeCost.toLocaleString('fr-FR') })}{cantAffordOffice ? insufFunds : ''}
          </span>
        </div>
        <p className="text-[9px]" style={{ color: 'var(--text-muted)' }}>
          {t('judicial.jugement.office_desc')}
        </p>
        {busy === 'office' && <p className="text-[9px] mt-1" style={{ color: 'var(--text-muted)' }}>{t('judicial.gav.office_progress')}</p>}
      </button>

      {/* Avocat personnel */}
      <button
        onClick={() => submit('personal')}
        disabled={!!busy || !hasPersonalLawyer}
        className="w-full p-3 rounded text-left disabled:opacity-50"
        style={{
          background: hasPersonalLawyer ? 'rgba(212,168,67,0.08)' : 'rgba(255,255,255,0.02)',
          border: hasPersonalLawyer ? '1px solid var(--border-gold)' : '1px solid rgba(255,255,255,0.1)',
          cursor: !hasPersonalLawyer ? 'not-allowed' : 'pointer',
        }}>
        <div className="flex items-center gap-2 mb-1">
          <Star size={12} style={{ color: hasPersonalLawyer ? 'var(--color-gold)' : 'var(--text-muted)' }} />
          <span className="text-[11px] font-bold" style={{ color: 'var(--text-primary)' }}>{tFmt('judicial.gav.personal_title', { stars })}</span>
          <span className="ml-auto text-[10px]" style={{ color: 'var(--color-gold-light)' }}>{t('judicial.gav.personal_free')}</span>
        </div>
        <p className="text-[9px]" style={{ color: 'var(--text-muted)' }}>
          {hasPersonalLawyer
            ? tFmt('judicial.jugement.personal_desc_active', { bonus: stars * 4, mult: (1 + stars * 0.1).toFixed(1) })
            : t('judicial.gav.personal_desc_inactive')}
        </p>
        {busy === 'personal' && <p className="text-[9px] mt-1" style={{ color: 'var(--text-muted)' }}>{tFmt('judicial.gav.personal_progress', { stars })}</p>}
      </button>

      {/* Bakchich direct juge */}
      <button
        onClick={() => submit('bakchich_direct')}
        disabled={!!busy || cantAffordBakchich}
        className="w-full p-3 rounded text-left disabled:opacity-50"
        style={{
          background: 'rgba(196,30,30,0.08)',
          border: '1px solid var(--border-red)',
          cursor: cantAffordBakchich ? 'not-allowed' : 'pointer',
        }}>
        <div className="flex items-center gap-2 mb-1">
          <HandCoins size={12} style={{ color: 'var(--color-red-light)' }} />
          <span className="text-[11px] font-bold" style={{ color: 'var(--text-primary)' }}>{t('judicial.jugement.bakchich_title')}</span>
          <span className="ml-auto text-[10px]" style={{ color: cantAffordBakchich ? '#fca5a5' : 'var(--color-red-light)' }}>
            {tFmt('judicial.gav.cost_shadow', { cost: bakchichAmount.toLocaleString('fr-FR') })}{cantAffordBakchich ? insufFunds : ''}
          </span>
        </div>
        <p className="text-[9px]" style={{ color: 'var(--text-muted)' }}>
          {t('judicial.jugement.bakchich_desc')}
        </p>
        {busy === 'bakchich_direct' && <p className="text-[9px] mt-1" style={{ color: 'var(--text-muted)' }}>{t('judicial.gav.bakchich_progress')}</p>}
      </button>

      {/* Mes documents */}
      <button
        onClick={() => setDocsOpen(true)}
        disabled={!!busy}
        className="w-full p-3 rounded text-left disabled:opacity-50"
        style={{
          background: 'rgba(34,197,94,0.06)',
          border: '1px solid rgba(34,197,94,0.4)',
        }}>
        <div className="flex items-center gap-2 mb-1">
          <FileText size={12} style={{ color: '#86efac' }} />
          <span className="text-[11px] font-bold" style={{ color: 'var(--text-primary)' }}>{t('judicial.jugement.docs_title')}</span>
        </div>
        <p className="text-[9px]" style={{ color: 'var(--text-muted)' }}>
          {t('judicial.jugement.docs_desc')}
        </p>
      </button>

      {docsOpen && (
        <JudicialPorteDocument
          recordId={active.record_id}
          onClose={() => setDocsOpen(false)}
          onResult={(flavor) => {
            setDocsOpen(false);
            onResult(flavor);
          }}
        />
      )}
    </div>
  );
}
