'use client';
/**
 * GangManagementTabs — 3 tabs partagés Gang/Cartel (Phase 15, 19-04-2026).
 *
 * Consigne utilisateur L672 MAFIADIMANCHE :
 *   Sous-tabs attendus = Personnel · Armurerie · Véhicules (strictement 3).
 *   Les Spécialistes (avocats/comptables/informateurs) vivent dans un
 *   bloc rétractable SOUS la zone des tabs (accordéon), pas comme 4ᵉ tab.
 *
 * Utilisé par GangPaneV2 et CartelPaneV2 avec le bon `scope` :
 *   scope = { type: 'gang', id } → endpoints /api/gang/* + /api/allocation/gang/*
 *   scope = { type: 'cartel', id } → endpoints /api/cartel/* + /api/allocation/cartel/*
 */
import { useState, useEffect, useCallback } from 'react';
import { ChevronDown, ChevronUp, Scale } from 'lucide-react';
import { api } from '@/lib/api';
import { ForceBribePanel } from '../ui/ForceBribePanel';
import { DetectiveReportsPanel } from '../specialists/DetectiveReportsPanel';

/** Bouton "Corrompre les forces" dans la card avocat — s'ouvre en lightbox avec gating skill/scope. */
function LawyerBribeButton({ scope, skill }: { scope: 'gang' | 'cartel' | 'player'; skill: number }) {
  const [open, setOpen] = useState(false);
  return (
    <>
      <button
        type="button"
        className="mt-2 w-full py-1 text-[10px] font-bold rounded transition"
        style={{
          color: 'var(--bg-panel)',
          background: 'linear-gradient(180deg, var(--color-gold-light), var(--color-gold))',
          letterSpacing: '.1em',
        }}
        onClick={() => setOpen(true)}
      >
        <Scale size={10} className="inline mr-1" /> SOUS-MAIN AUX FORCES
      </button>
      <ForceBribePanel
        open={open}
        onClose={() => setOpen(false)}
        lawyerSkillLevel={skill}
        lawyerScope={scope}
      />
    </>
  );
}

type Scope = { type: 'gang' | 'cartel'; id: string };
type SubTab = 'personnel' | 'armurerie' | 'vehicules';

/**
 * Phase 17.1 (2026-05-05) — `taulard` : version restreinte du panel
 * affichée quand le joueur est en prison avec MiniKom P1 (mode taulard
 * du téléphone). Restrictions :
 *   • L'onglet Personnel est lisible mais désactive Hire/Fire (le user
 *     ne peut pas physiquement gérer son personnel depuis sa cellule).
 *   • Onglets Armurerie / Véhicules cachés (pas d'allocation depuis
 *     prison — incohérent narrativement).
 *   • Section Spécialistes : lisible mais Hire/Fire désactivés.
 *   • Bras droit : promotion désactivée (mais lecture OK).
 *
 * Les restrictions sont propagées via la prop `taulard?: boolean` et
 * appliquées en CSS pointer-events: none + opacity sur les zones
 * concernées (plus simple qu'un disabled HTML, garde le visuel propre).
 */
export function GangManagementTabs({ scope, taulard = false }: { scope: Scope; taulard?: boolean }) {
  const [tab, setTab] = useState<SubTab>('personnel');
  const [personnelSub, setPersonnelSub] = useState<'embauches' | 'candidats'>('embauches');
  const [specOpen, setSpecOpen] = useState(false);
  // Phase 17 (2026-05-04) — Gel territoire GIGN : si frozen, le panel
  // est flouté avec compte à rebours, tous les ordres sont rejetés.
  const [frozenUntil, setFrozenUntil] = useState<string | null>(null);
  const [now, setNow] = useState(Date.now());

  useEffect(() => {
    let cancel = false;
    const fetchStatus = async () => {
      try {
        const s = await api.territory.getStatus();
        if (cancel) return;
        setFrozenUntil(s.territory_frozen_until);
      } catch { /* silent */ }
    };
    fetchStatus();
    const it = setInterval(fetchStatus, 60_000);
    const tick = setInterval(() => setNow(Date.now()), 1000);
    return () => { cancel = true; clearInterval(it); clearInterval(tick); };
  }, []);

  const frozenRemainingMs = frozenUntil ? new Date(frozenUntil).getTime() - now : 0;
  const isFrozen = frozenRemainingMs > 0;
  const remainingHours = Math.floor(frozenRemainingMs / 3_600_000);
  const remainingMinutes = Math.floor((frozenRemainingMs % 3_600_000) / 60_000);
  const remainingSeconds = Math.floor((frozenRemainingMs % 60_000) / 1000);
  const countdownLabel = `${String(remainingHours).padStart(2, '0')}:${String(remainingMinutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`;

  // Phase 15 Commit 5 — bouton Recruter de l'OrderBar déclenche cet event :
  // on switch sur Personnel → Candidatures.
  useEffect(() => {
    const handler = (e: Event) => {
      const detail = (e as CustomEvent).detail as { scope: any; subtab?: string };
      if (!detail || detail.scope?.type !== scope.type) return;
      setTab('personnel');
      if (detail.subtab === 'candidats') setPersonnelSub('candidats');
    };
    window.addEventListener('open-gang-personnel', handler);
    return () => window.removeEventListener('open-gang-personnel', handler);
  }, [scope.type]);

  // Phase 17.1 (2026-05-05) — En mode taulard, on cache les onglets
  // Armurerie/Véhicules (allocation impossible depuis prison) et on
  // désactive les actions Hire/Fire/Promote via wrapper CSS sur les
  // sous-tabs interactifs.
  const visibleTabs: SubTab[] = taulard ? ['personnel'] : ['personnel', 'armurerie', 'vehicules'];

  return (
    <div className="flex-1 min-h-0 flex flex-col" style={{ position: 'relative' }}>
      {/* Tablist : tabs visibles dépendent de taulard (Phase 17.1).
          En prison MiniKom : Personnel uniquement. Sinon : 3 tabs L672. */}
      {taulard && (
        <div className="mb-2 px-2 py-1.5 rounded text-[9px]" style={{
          background: 'rgba(212,168,67,0.08)',
          border: '1px solid rgba(212,168,67,0.3)',
          color: 'var(--color-gold-light)',
        }}>
          📵 Mode taulard (MiniKom P1) — gestion lecture seule. Allocation et changements de statut indisponibles depuis la prison.
        </div>
      )}
      <div className="f-switch mb-2" role="tablist"
        style={{ overflowX: 'auto', overflowY: 'hidden', flexWrap: 'nowrap' }}>
        {visibleTabs.map(t => (
          <button key={t} type="button" role="tab" aria-selected={tab === t}
            onClick={() => setTab(t)} className={tab === t ? 'on' : ''}
            style={{ flex: '1 1 0%', minWidth: 84, whiteSpace: 'nowrap' }}>
            {t === 'personnel' ? 'Personnel' : t === 'armurerie' ? 'Armurerie' : 'Véhicules'}
          </button>
        ))}
      </div>
      {/* Phase 17.2 (2026-05-05) — Section Underboss visible uniquement
          en scope cartel ET pour le fondateur (le composant filtre lui-même). */}
      {scope.type === 'cartel' && !taulard && <CartelUnderbossSection scope={scope} />}

      <div className="flex-1 min-h-0 overflow-y-auto"
        style={taulard ? { pointerEvents: 'none', opacity: 0.85 } : undefined}>
        {tab === 'personnel' && <PersonnelTab scope={scope} sub={personnelSub} setSub={setPersonnelSub} />}
        {tab === 'armurerie' && !taulard && <AllocationTable scope={scope} kind="inventory" />}
        {tab === 'vehicules' && !taulard && <AllocationTable scope={scope} kind="vehicles" />}
      </div>

      {/* Section Spécialistes rétractable — externalisée hors tablist (L672) */}
      <div className="mt-2 pt-2 shrink-0" style={{ borderTop: '1px dashed var(--border-dark)' }}>
        <button type="button" onClick={() => setSpecOpen(o => !o)}
          className="w-full flex items-center justify-between py-1.5 px-2 rounded text-[10px] font-bold"
          style={{
            background: specOpen ? 'rgba(212,168,67,0.10)' : 'rgba(255,255,255,0.02)',
            border: `1px solid ${specOpen ? 'var(--border-gold)' : 'var(--border-dark)'}`,
            color: 'var(--color-gold-light)',
            letterSpacing: '.15em',
            fontFamily: 'var(--font-subtitle)',
          }}>
          <span className="flex items-center gap-1.5">
            <Scale size={12} aria-hidden /> SPÉCIALISTES
          </span>
          {specOpen ? <ChevronUp size={12} /> : <ChevronDown size={12} />}
        </button>
        {specOpen && (
          <div className="mt-2 max-h-[260px] overflow-y-auto">
            <SpecialistsTab scope={scope} />
          </div>
        )}
      </div>

      {/* Phase 17 (2026-05-04) — Overlay flou + countdown si territoire gelé.
          Consigne user verbatim : "panel gestion gang (...) ou cartel
          (...) est flouté avec compte à rebours". Le user peut toujours
          fermer le panel et faire d'autres actions perso (visiter POIs,
          missions solo, etc.) — c'est juste les ordres au gang/cartel
          qui sont bloqués pendant le gel. */}
      {isFrozen && (
        <div
          className="absolute inset-0 flex items-center justify-center z-10 rounded-lg"
          style={{
            background: 'rgba(0,0,0,0.65)',
            backdropFilter: 'blur(6px)',
            WebkitBackdropFilter: 'blur(6px)',
          }}
        >
          <div className="text-center p-6 rounded-xl max-w-sm"
            style={{
              background: 'linear-gradient(135deg, rgba(220,38,38,0.15), rgba(0,0,0,0.85))',
              border: '1px solid var(--border-red)',
            }}>
            <p className="text-sm font-bold mb-1" style={{ color: 'var(--color-red-light)' }}>
              ⚠ Territoire gelé par le GIGN
            </p>
            <p className="text-[11px] mb-3" style={{ color: 'var(--text-secondary)' }}>
              Aucun ordre au gang/cartel pendant la suspension. Tu peux te
              déplacer, visiter des POIs et faire des missions solo.
            </p>
            <p className="text-2xl font-mono font-bold tabular-nums" style={{ color: 'var(--color-gold-light)' }}>
              {countdownLabel}
            </p>
            <p className="text-[10px] mt-1" style={{ color: 'var(--text-muted)' }}>
              avant reprise
            </p>
          </div>
        </div>
      )}
    </div>
  );
}

// ───────────────────────────────────────────────────────────
// SPÉCIALISTES — Avocats/Comptables/Informateurs (Phase 15 Iter 7.3, 19-04-2026)
// ───────────────────────────────────────────────────────────

/**
 * Phase 17 Phase 4 (2026-05-04) — Labels FR pluriel/singulier des rôles
 * spécialistes. Affichés dans les headers des cards. Pour 'medic',
 * non listé ici car le médecin perso est PLAYER-only (pas gang/cartel).
 */
const SPEC_ROLE_LABEL = {
  lawyer:     { singular: 'Avocat',    plural: 'Avocats' },
  accountant: { singular: 'Comptable', plural: 'Comptables' },
  informant:  { singular: 'Indic',     plural: 'Indics' },
  detective:  { singular: 'Enquêteur', plural: 'Enquêteurs' },
} as const;

type GangCartelSpecRole = keyof typeof SPEC_ROLE_LABEL;

function SpecialistsTab({ scope }: { scope: Scope }) {
  const [hired, setHired] = useState<any[]>([]);
  const [pool, setPool] = useState<Record<GangCartelSpecRole, any[]>>({
    lawyer: [], accountant: [], informant: [], detective: [],
  });
  const [loading, setLoading] = useState(true);
  const [busy, setBusy] = useState<string | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      if (scope.type === 'cartel') {
        const list: any = await api.cartel.getSpecialists(scope.id);
        setHired(Array.isArray(list) ? list : []);
      } else {
        const list: any = await api.specialists.forOwner('gang', scope.id);
        setHired(Array.isArray(list) ? list : []);
      }
      // Phase 17 Phase 4 (2026-05-04) — Ajout du rôle 'detective' au bassin
      // (gang/cartel scope). Le 'medic' est volontairement absent : le
      // médecin perso est PLAYER-only (cf SpecialistService.hire validation).
      const [lw, ac, inf, det] = await Promise.all([
        api.specialists.pool('lawyer').catch(() => []),
        api.specialists.pool('accountant').catch(() => []),
        api.specialists.pool('informant').catch(() => []),
        api.specialists.pool('detective').catch(() => []),
      ]);
      setPool({
        lawyer: Array.isArray(lw) ? lw : [],
        accountant: Array.isArray(ac) ? ac : [],
        informant: Array.isArray(inf) ? inf : [],
        detective: Array.isArray(det) ? det : [],
      });
    } catch { setHired([]); }
    finally { setLoading(false); }
  }, [scope]);

  useEffect(() => { load(); }, [load]);

  const hire = async (specialistId: string) => {
    setBusy(specialistId);
    try {
      if (scope.type === 'cartel') await api.cartel.hireSpecialist(scope.id, specialistId);
      else await api.specialists.hire({ specialist_id: specialistId, owner_type: 'gang', owner_id: scope.id });
      await load();
    } catch (e: any) { alert(e?.message || 'Échec'); }
    finally { setBusy(null); }
  };

  const fire = async (attId: string) => {
    if (!confirm('Libérer ce spécialiste ?')) return;
    setBusy(attId);
    try {
      if (scope.type === 'cartel') await api.cartel.fireSpecialist(scope.id, attId);
      else await api.specialists.fire(attId);
      await load();
    } catch (e: any) { alert(e?.message || 'Échec'); }
    finally { setBusy(null); }
  };

  if (loading) return <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>Chargement…</p>;

  // Phase 17 Phase 4 (2026-05-04) — Group embauchés par rôle pour les
  // afficher avec un header dynamique (1 → singulier "Avocat",
  // 2+ → pluriel "Avocats"). Consigne user verbatim :
  //   "On voit ses spécialistes affichés en liste avec leur header
  //    (Avocat(s si plusieurs recrutés), Comptable, Indic…"
  const groupedHired: Record<GangCartelSpecRole, any[]> = {
    lawyer: [], accountant: [], informant: [], detective: [],
  };
  for (const h of hired) {
    const r = (h.role || h.specialist?.role) as GangCartelSpecRole;
    if (r in groupedHired) groupedHired[r].push(h);
  }
  const hiredSections = (Object.keys(groupedHired) as GangCartelSpecRole[])
    .filter(r => groupedHired[r].length > 0);

  const renderHiredCard = (h: any) => {
    const attachmentId = h.attachment_id || h.id;
    const role = h.role || h.specialist?.role;
    const skill = Number(h.skill_level ?? h.specialist?.skill_level ?? 0);
    const name = h.name || h.specialist?.name || h.specialist?.title || '—';
    const dailyRate = h.chosen_daily_rate ?? h.specialist?.salary_daily ?? null;
    const isLawyer = role === 'lawyer';
    return (
      <div key={attachmentId} className="rounded p-2 text-[10px]"
        style={{ background: 'rgba(255,255,255,0.02)', border: '1px solid var(--border-dark)' }}>
        <div className="flex items-center justify-between">
          <span>
            <b style={{ color: 'var(--text-primary)' }}>{name}</b>
            <span className="ml-2 text-[9px]" style={{ color: 'var(--text-muted)' }}>
              niv.{skill}/10{dailyRate != null ? ` · ${Number(dailyRate).toLocaleString('fr-FR')} ∞/j` : ''}
            </span>
          </span>
          <button type="button" className="new-order is-red" style={{ fontSize: 9, padding: 3 }}
            disabled={busy === attachmentId}
            onClick={() => fire(attachmentId)}>✕ Virer</button>
        </div>
        {isLawyer && skill >= 1 && (
          <LawyerBribeButton scope={scope.type} skill={skill} />
        )}
      </div>
    );
  };

  return (
    <div className="space-y-3">
      {/* Spécialistes embauchés — groupés par rôle */}
      {hiredSections.length === 0 ? (
        <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>Aucun spécialiste employé.</p>
      ) : (
        <div className="space-y-3">
          {hiredSections.map(role => {
            const list = groupedHired[role];
            const headerLabel = list.length === 1
              ? SPEC_ROLE_LABEL[role].singular
              : SPEC_ROLE_LABEL[role].plural;
            return (
              <div key={`hired-${role}`}>
                <p className="text-[9px] font-bold mb-1" style={{
                  color: 'var(--color-gold-light)', letterSpacing: '.15em',
                  fontFamily: 'var(--font-subtitle)',
                }}>
                  {headerLabel.toUpperCase()} ({list.length})
                </p>
                <div className="space-y-1">
                  {list.map(renderHiredCard)}
                </div>
              </div>
            );
          })}
        </div>
      )}

      {/* Phase 17.2 finition (2026-05-06) — Rapports détective si au moins
          un détective embauché sur ce scope (gang/cartel). */}
      {groupedHired.detective.length > 0 && (
        <div className="rounded-lg p-3" style={{
          background: 'rgba(212,168,67,0.04)',
          border: '1px solid rgba(212,168,67,0.2)',
        }}>
          <DetectiveReportsPanel scope={scope.type} ownerId={scope.id} />
        </div>
      )}

      {/* Bassin disponible */}
      {(['lawyer', 'accountant', 'informant', 'detective'] as const).map(role => {
        const items = pool[role] || [];
        if (items.length === 0) return null;
        const headerLabel = items.length === 1
          ? SPEC_ROLE_LABEL[role].singular.toUpperCase()
          : SPEC_ROLE_LABEL[role].plural.toUpperCase();
        return (
          <div key={role}>
            <p className="text-[9px] font-bold mb-1" style={{
              color: 'var(--text-primary)', letterSpacing: '.15em', fontFamily: 'var(--font-subtitle)',
            }}>
              {headerLabel} DISPONIBLES ({items.length})
            </p>
            <div className="space-y-1">
              {items.map((s: any) => (
                <div key={s.id} className="rounded p-2 text-[10px]"
                  style={{ background: 'rgba(255,255,255,0.02)', border: '1px solid var(--border-dark)' }}>
                  <div className="flex items-center justify-between mb-1">
                    <span>
                      <b style={{ color: 'var(--text-primary)' }}>{s.name || s.title}</b>
                      <span className="ml-1 text-[9px]" style={{ color: 'var(--text-muted)' }}>
                        niv.{s.level ?? s.tier ?? 1}
                      </span>
                    </span>
                    <span style={{ color: 'var(--color-gold-light)' }}>
                      {s.fee_per_day ? `${s.fee_per_day.toLocaleString('fr-FR')} ∞/j` : ''}
                    </span>
                  </div>
                  {s.description && (
                    <p className="text-[9px]" style={{ color: 'var(--text-secondary)', lineHeight: 1.3 }}>{s.description}</p>
                  )}
                  <button type="button" className="new-order mt-1" style={{ width: '100%', fontSize: 9, padding: 3 }}
                    disabled={busy === s.id}
                    onClick={() => hire(s.id)}>
                    ✓ Embaucher
                  </button>
                </div>
              ))}
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ───────────────────────────────────────────────────────────
// PERSONNEL — 2 sous-tabs Embauchés / Candidatures
// ───────────────────────────────────────────────────────────

function PersonnelTab({ scope, sub, setSub }: {
  scope: Scope;
  sub: 'embauches' | 'candidats';
  setSub: (s: 'embauches' | 'candidats') => void;
}) {
  return (
    <div className="space-y-2">
      <div className="f-switch" role="tablist">
        {(['embauches', 'candidats'] as const).map(t => (
          <button key={t} type="button" role="tab" aria-selected={sub === t}
            onClick={() => setSub(t)} className={sub === t ? 'on' : ''} style={{ flex: 1 }}>
            {t === 'embauches' ? 'Embauchés' : 'Candidatures'}
          </button>
        ))}
      </div>
      {sub === 'embauches' && <EmployedList scope={scope} />}
      {sub === 'candidats' && <CandidatesList scope={scope} />}
    </div>
  );
}

/**
 * Phase 17.2 (2026-05-05) — Section Underboss pour scope='cartel'.
 * Affichée sous les Stats / au-dessus de la liste des members. Permet
 * au fondateur du cartel (leader du leader_gang) de :
 *   • Promouvoir un CartelMember (gang) en underboss (is_admin=true)
 *   • Démettre l'underboss courant
 *
 * Contraintes (re-validées backend) :
 *   • Caller doit être fondateur (leader du leader_gang)
 *   • Target ne peut pas être le fondateur lui-même
 *   • Max 1 underboss actif (refuse si existe déjà)
 *
 * L'UI montre 3 états :
 *   1. Pas autorisé (caller != fondateur) → caché
 *   2. Underboss actif → card avec bouton "✕ Démettre"
 *   3. Pas d'underboss → liste des members éligibles avec bouton "✓ Nommer"
 */
function CartelUnderbossSection({ scope }: { scope: Scope }) {
  const [data, setData] = useState<any | null>(null);
  const [loading, setLoading] = useState(true);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [callerIsFounder, setCallerIsFounder] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const cartelDetails: any = await api.cartel.getDetails(scope.id);
      setData(cartelDetails);
      // Détection caller=fondateur : vérifie si le current player est
      // leader du leader_gang du cartel.
      const myGang: any = await api.gang.getMy().catch(() => null);
      const isFounder = !!cartelDetails?.leader_gang_id
        && !!myGang?.id
        && cartelDetails.leader_gang_id === myGang.id;
      setCallerIsFounder(isFounder);
    } catch (e: any) {
      setError(e?.message || 'Chargement impossible');
    } finally { setLoading(false); }
  }, [scope.id]);

  useEffect(() => { load(); }, [load]);

  if (loading) return null;
  if (!callerIsFounder) return null;
  if (!data) return null;

  const members: any[] = Array.isArray(data.members) ? data.members : [];
  const founderGangId: string = data.leader_gang_id;
  const currentUnderboss = members.find(
    (m: any) => m.is_admin && m.gang_id !== founderGangId && m.status === 'active',
  );
  const eligibleCandidates = members.filter(
    (m: any) => !m.is_admin && m.gang_id !== founderGangId && m.status === 'active',
  );

  const handlePromote = async (gangId: string) => {
    setBusy(true);
    setError(null);
    try {
      const r = await api.cartel.promoteUnderboss(scope.id, gangId);
      if (!r.success) setError(r.message);
      await load();
    } catch (e: any) {
      setError(e?.message || 'Promotion échouée');
    } finally { setBusy(false); }
  };

  const handleFire = async () => {
    if (!confirm('Démettre l\'underboss actuel ?')) return;
    setBusy(true);
    setError(null);
    try {
      const r = await api.cartel.fireUnderboss(scope.id);
      if (!r.success) setError(r.message);
      await load();
    } catch (e: any) {
      setError(e?.message || 'Démise échouée');
    } finally { setBusy(false); }
  };

  return (
    <div className="rounded p-2 mb-2" style={{
      background: 'rgba(212,168,67,0.06)',
      border: '1px solid var(--border-gold)',
    }}>
      <p className="text-[9px] font-bold mb-1" style={{
        color: 'var(--color-gold-light)', letterSpacing: '.15em',
        fontFamily: 'var(--font-subtitle)',
      }}>
        UNDERBOSS
      </p>
      {currentUnderboss ? (
        <div className="flex items-center justify-between text-[10px]">
          <span style={{ color: 'var(--text-primary)' }}>
            <b>{currentUnderboss.gang?.name || currentUnderboss.gang_name || 'Gang'}</b>
            <span className="ml-2" style={{ color: 'var(--text-muted)' }}>
              tous pouvoirs sauf exclure un membre
            </span>
          </span>
          <button type="button" className="new-order is-red"
            style={{ fontSize: 9, padding: 3 }}
            disabled={busy}
            onClick={handleFire}>
            ✕ Démettre
          </button>
        </div>
      ) : eligibleCandidates.length === 0 ? (
        <p className="text-[10px] italic" style={{ color: 'var(--text-muted)' }}>
          Aucun gang membre éligible (le fondateur ne peut pas être underboss).
        </p>
      ) : (
        <div className="space-y-1">
          <p className="text-[9px] italic" style={{ color: 'var(--text-muted)' }}>
            Choisis un gang membre à promouvoir :
          </p>
          {eligibleCandidates.map((m: any) => (
            <button key={m.gang_id} type="button"
              className="w-full flex items-center justify-between px-2 py-1 rounded text-[10px]"
              style={{
                background: 'rgba(255,255,255,0.03)',
                border: '1px solid var(--border-dark)',
              }}
              disabled={busy}
              onClick={() => handlePromote(m.gang_id)}>
              <span style={{ color: 'var(--text-primary)' }}>
                {m.gang?.name || m.gang_name || m.gang_id?.slice(0, 8)}
              </span>
              <span style={{ color: 'var(--color-gold-light)' }}>✓ Nommer</span>
            </button>
          ))}
        </div>
      )}
      {error && (
        <p className="text-[9px] mt-1" style={{ color: 'var(--color-red-light)' }}>{error}</p>
      )}
    </div>
  );
}

function EmployedList({ scope }: { scope: Scope }) {
  const [members, setMembers] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [expanded, setExpanded] = useState<string | null>(null);
  const [brasDroitBusy, setBrasDroitBusy] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      if (scope.type === 'gang') {
        const g: any = await api.gang.getMy();
        setMembers((g?.members ?? []).filter((m: any) => m.role !== 'leader'));
      } else {
        // Phase 15 Iter 6.1 — gangsters dédiés cartel (jusqu'à 99)
        const list: any = await api.cartel.listGangsters(scope.id);
        setMembers(Array.isArray(list) ? list : []);
      }
    } catch { setMembers([]); }
    finally { setLoading(false); }
  }, [scope]);

  useEffect(() => { load(); }, [load]);

  if (loading) return <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>Chargement…</p>;
  if (members.length === 0) return <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>Aucun gangster embauché.</p>;

  // Phase 17 Phase 4 (2026-05-04) — Bras droit selector pour scope='gang'.
  // Consigne user verbatim :
  //   "bras droit gang c'est parmis les gangsters recrutés. Le type le
  //    plus haut peut etre nommé bras droit, assignement depuis tab
  //    gang / cartel."
  // Backend (gang.service.ts promoteMember Phase 17) valide :
  //   – Le promu doit être un NPC (player.is_npc=true)
  //   – Doit avoir le grade le plus élevé parmi les NPCs du gang
  // Côté UI, on n'affiche le selector QUE pour scope='gang' et on filtre
  // les candidats au grade max (les autres seraient rejetés par le backend).
  const isGangScope = scope.type === 'gang';
  const npcMembers = members.filter((m: any) => m.player?.is_npc || m.is_npc);
  const maxGrade = npcMembers.reduce(
    (max: number, m: any) => Math.max(max, Number(m.grade ?? 0)), 0,
  );
  const brasDroitCandidates = npcMembers.filter(
    (m: any) => Number(m.grade ?? 0) === maxGrade,
  );
  const currentBrasDroit = members.find((m: any) => m.role === 'bras_droit');

  const promoteToBrasDroit = async (memberId: string) => {
    if (!isGangScope || !scope.id) return;
    setBrasDroitBusy(true);
    try {
      await api.gang.promote(scope.id, memberId, 'bras_droit');
      await load();
    } catch (e: any) {
      alert(e?.message || 'Échec promotion bras droit');
    } finally {
      setBrasDroitBusy(false);
    }
  };

  const fireBrasDroit = async () => {
    if (!isGangScope || !scope.id) return;
    if (!confirm('Démettre le bras droit actuel ?')) return;
    setBrasDroitBusy(true);
    try {
      await api.gang.fireBrasDroit(scope.id);
      await load();
    } catch (e: any) {
      alert(e?.message || 'Échec licenciement');
    } finally {
      setBrasDroitBusy(false);
    }
  };

  return (
    <div className="space-y-2">
      {/* Phase 17 Phase 4 (2026-05-04) — Bras droit (gang scope only) */}
      {isGangScope && (
        <div className="rounded p-2" style={{
          background: 'rgba(212,168,67,0.06)',
          border: '1px solid var(--border-gold)',
        }}>
          <p className="text-[9px] font-bold mb-1" style={{
            color: 'var(--color-gold-light)', letterSpacing: '.15em',
            fontFamily: 'var(--font-subtitle)',
          }}>
            BRAS DROIT
          </p>
          {currentBrasDroit ? (
            <div className="flex items-center justify-between text-[10px]">
              <span style={{ color: 'var(--text-primary)' }}>
                <b>{currentBrasDroit.player?.username || currentBrasDroit.player_id?.slice(0, 8) || '—'}</b>
                <span className="ml-2" style={{ color: 'var(--text-muted)' }}>
                  grade {currentBrasDroit.grade ?? '?'}
                </span>
              </span>
              <button type="button" className="new-order is-red"
                style={{ fontSize: 9, padding: 3 }}
                disabled={brasDroitBusy}
                onClick={fireBrasDroit}>
                ✕ Démettre
              </button>
            </div>
          ) : brasDroitCandidates.length === 0 ? (
            <p className="text-[10px] italic" style={{ color: 'var(--text-muted)' }}>
              Aucun candidat éligible. Recrute des gangsters NPCs (le grade le plus
              élevé pourra être nommé bras droit).
            </p>
          ) : (
            <div className="space-y-1">
              <p className="text-[9px] italic" style={{ color: 'var(--text-muted)' }}>
                Candidats grade {maxGrade} (le plus élevé) :
              </p>
              {brasDroitCandidates.map((m: any) => (
                <button key={m.player_id || m.id} type="button"
                  className="w-full flex items-center justify-between px-2 py-1 rounded text-[10px]"
                  style={{
                    background: 'rgba(255,255,255,0.03)',
                    border: '1px solid var(--border-dark)',
                  }}
                  disabled={brasDroitBusy}
                  onClick={() => promoteToBrasDroit(m.player_id)}>
                  <span style={{ color: 'var(--text-primary)' }}>
                    {m.player?.username || m.player_id?.slice(0, 8) || '—'}
                    <span className="ml-1 text-[9px]" style={{ color: 'var(--text-muted)' }}>
                      g{m.grade}
                    </span>
                  </span>
                  <span style={{ color: 'var(--color-gold-light)' }}>✓ Nommer</span>
                </button>
              ))}
            </div>
          )}
        </div>
      )}

      <div className="space-y-1">
      {members.map((m: any) => {
        const id = m.player_id || m.gang_id;
        const isOpen = expanded === id;
        const unpaid = m.unpaid_since != null;
        return (
          <div key={id} className="rounded" style={{
            border: `1px solid ${unpaid ? 'var(--color-red)' : 'var(--border-dark)'}`,
            background: 'rgba(255,255,255,0.02)',
          }}>
            <button type="button" className="w-full flex items-center justify-between px-2 py-1.5 text-[11px]"
              onClick={() => setExpanded(isOpen ? null : id)}>
              <span style={{ color: unpaid ? 'var(--color-red-light)' : 'var(--text-primary)' }}>
                {m.player?.username || m.gang_name || id.slice(0, 8)}
                {m.grade && <span className="ml-1 text-[9px]" style={{ color: 'var(--text-muted)' }}>g{m.grade}</span>}
              </span>
              <span className="text-[9px]" style={{ color: 'var(--color-gold-light)' }}>
                {m.daily_salary ? `${m.daily_salary.toLocaleString('fr-FR')} ∞/j` : '—'}
              </span>
            </button>
            {isOpen && (
              <div className="px-2 pb-2 text-[10px] space-y-1" style={{ color: 'var(--text-secondary)' }}>
                <div>HP {m.hit_points ?? '?'}/100 · Loyauté {m.loyalty ?? '?'} · XP {m.experience?.toLocaleString('fr-FR') ?? '?'}</div>
                {unpaid && <div style={{ color: 'var(--color-red-light)' }}>⚠ Impayé depuis le {new Date(m.unpaid_since).toLocaleDateString('fr-FR')}</div>}
                <div className="flex gap-1 mt-1">
                  {unpaid && scope.type === 'gang' && (
                    <button type="button" className="new-order" style={{ flex: 1, fontSize: 9, padding: 3 }}
                      onClick={async () => {
                        const r = await api.gang.payNow(scope.id, id);
                        if (r.success) load();
                        else alert(r.message);
                      }}>Payer arriéré</button>
                  )}
                  <button type="button" className="new-order is-red" style={{ flex: 1, fontSize: 9, padding: 3 }}
                    onClick={async () => {
                      if (!confirm(`Virer ${m.player?.username || 'ce gangster'} ?`)) return;
                      if (scope.type === 'gang') {
                        await api.gang.removeMember(scope.id, id);
                      } else {
                        const r = await api.cartel.removeGangster(scope.id, id);
                        if (!r.success) alert(r.message);
                      }
                      load();
                    }}>✕ Virer</button>
                </div>
              </div>
            )}
          </div>
        );
      })}
      </div>
    </div>
  );
}

function CandidatesList({ scope }: { scope: Scope }) {
  const [slots, setSlots] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [busy, setBusy] = useState<string | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const pool: any = scope.type === 'gang'
        ? await api.gang.getRecruitPool()
        : await api.cartel.getRecruitPool(scope.id);
      setSlots((pool?.slots ?? []).filter((s: any) => !s.recruited));
    } catch { setSlots([]); }
    finally { setLoading(false); }
  }, [scope]);

  useEffect(() => { load(); }, [load]);

  if (loading) return <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>Chargement…</p>;
  if (slots.length === 0) {
    return <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>Aucun candidat. Prochain refresh à minuit Paris.</p>;
  }

  return (
    <div className="space-y-1">
      {slots.map((s: any) => (
        <div key={s.slot_id} className="rounded p-2 text-[10px]"
          style={{ background: 'rgba(255,255,255,0.02)', border: '1px solid var(--border-dark)' }}>
          <div className="flex items-center justify-between mb-1">
            <span style={{ color: 'var(--text-primary)' }}>
              <b>{s.name}</b> <span className="text-[9px]" style={{ color: 'var(--text-muted)' }}>g{s.grade} · {s.archetype}</span>
            </span>
            <span style={{ color: 'var(--color-gold-light)' }}>{s.cost?.toLocaleString('fr-FR')} ∞</span>
          </div>
          <p style={{ color: 'var(--text-secondary)', lineHeight: 1.35 }}>{s.description}</p>
          <div className="flex gap-1 mt-1">
            <button type="button" className="new-order" style={{ flex: 1, fontSize: 9, padding: 3 }}
              disabled={busy === s.slot_id}
              onClick={async () => {
                setBusy(s.slot_id);
                try {
                  const r: any = scope.type === 'gang'
                    ? await api.gang.recruitFromPool(s.slot_id)
                    : await api.cartel.recruitFromPool(scope.id, s.slot_id);
                  if (r?.success) load();
                  else alert(r?.message || 'Échec');
                } finally { setBusy(null); }
              }}>✓ Recruter</button>
            <button type="button" className="new-order is-red" style={{ flex: 1, fontSize: 9, padding: 3 }}
              disabled={busy === s.slot_id}
              onClick={async () => {
                if (!confirm('Écarter ce candidat ?')) return;
                setBusy(s.slot_id);
                try {
                  if (scope.type === 'gang') await api.gang.dismissFromPool(s.slot_id);
                  else await api.cartel.dismissFromPool(scope.id, s.slot_id);
                  load();
                } finally { setBusy(null); }
              }}>✕ Sortir</button>
          </div>
        </div>
      ))}
    </div>
  );
}

// ───────────────────────────────────────────────────────────
// ALLOCATION TABLE — Armurerie / Véhicules (deux colonnes)
// ───────────────────────────────────────────────────────────

function AllocationTable({ scope, kind }: { scope: Scope; kind: 'inventory' | 'vehicles' }) {
  const [personal, setPersonal] = useState<any[]>([]);
  const [allocated, setAllocated] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      if (kind === 'inventory') {
        const [p, g] = await Promise.all([
          api.allocation.myInventory(),
          scope.type === 'gang' ? api.allocation.gangInventory(scope.id) : api.allocation.cartelInventory(scope.id),
        ]);
        setPersonal(Array.isArray(p) ? p : []);
        setAllocated(Array.isArray(g) ? g : []);
      } else {
        const [p, g] = await Promise.all([
          api.allocation.myVehicles(),
          scope.type === 'gang' ? api.allocation.gangVehicles(scope.id) : api.allocation.cartelVehicles(scope.id),
        ]);
        setPersonal(Array.isArray(p) ? p : []);
        setAllocated(Array.isArray(g) ? g : []);
      }
    } catch { setPersonal([]); setAllocated([]); }
    finally { setLoading(false); }
  }, [scope, kind]);

  useEffect(() => { load(); }, [load]);

  const push = async (itemId: string) => {
    if (kind === 'inventory') {
      if (scope.type === 'gang') await api.allocation.inventoryToGang(itemId, scope.id);
      else await api.allocation.inventoryToCartel(itemId, scope.id);
    } else {
      if (scope.type === 'gang') await api.allocation.vehicleToGang(itemId, scope.id);
      else await api.allocation.vehicleToCartel(itemId, scope.id);
    }
    load();
  };

  const pull = async (itemId: string) => {
    if (kind === 'inventory') {
      if (scope.type === 'gang') await api.allocation.inventoryFromGang(itemId);
      else await api.allocation.inventoryFromCartel(itemId);
    } else {
      if (scope.type === 'gang') await api.allocation.vehicleFromGang(itemId);
      else await api.allocation.vehicleFromCartel(itemId);
    }
    load();
  };

  if (loading) return <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>Chargement…</p>;

  const rightLabel = scope.type === 'gang' ? 'Stock Gang' : 'Stock Cartel';

  return (
    <div className="grid grid-cols-2 gap-2 text-[10px]">
      <div>
        <p className="font-bold mb-1" style={{ color: 'var(--color-gold-light)', letterSpacing: '.1em' }}>Votre stock</p>
        <div className="space-y-1">
          {personal.length === 0 && <p style={{ color: 'var(--text-muted)' }}>Vide.</p>}
          {personal.slice(0, 30).map((item: any) => {
            const label = kind === 'inventory' ? `${item.item_subtype} ×${item.quantity}` : `${item.name || item.type || item.id.slice(0, 8)}`;
            return (
              <div key={item.id} className="flex items-center justify-between gap-1 p-1 rounded"
                style={{ background: 'rgba(255,255,255,0.02)', border: '1px solid var(--border-dark)' }}>
                <span className="truncate" style={{ color: 'var(--text-secondary)' }}>{label}</span>
                <button type="button" onClick={() => push(item.id)}
                  className="text-[10px] px-2 py-0.5 rounded"
                  title="Allouer"
                  style={{ background: 'rgba(212,168,67,0.15)', color: 'var(--color-gold-light)', border: '1px solid var(--border-gold)' }}>
                  →
                </button>
              </div>
            );
          })}
        </div>
      </div>
      <div>
        <p className="font-bold mb-1" style={{ color: 'var(--color-red-light)', letterSpacing: '.1em' }}>{rightLabel}</p>
        <div className="space-y-1">
          {allocated.length === 0 && <p style={{ color: 'var(--text-muted)' }}>Vide.</p>}
          {allocated.slice(0, 30).map((item: any) => {
            const label = kind === 'inventory' ? `${item.item_subtype} ×${item.quantity}` : `${item.name || item.type || item.id.slice(0, 8)}`;
            return (
              <div key={item.id} className="flex items-center justify-between gap-1 p-1 rounded"
                style={{ background: 'rgba(255,255,255,0.02)', border: '1px solid var(--border-dark)' }}>
                <button type="button" onClick={() => pull(item.id)}
                  className="text-[10px] px-2 py-0.5 rounded"
                  title="Désallouer"
                  style={{ background: 'rgba(196,30,30,0.15)', color: 'var(--color-red-light)', border: '1px solid var(--border-red)' }}>
                  ←
                </button>
                <span className="truncate flex-1 text-right" style={{ color: 'var(--text-secondary)' }}>{label}</span>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}
