'use client';

import { useState, useEffect, useCallback, useMemo, type ReactElement } from 'react';
import { useGameStore } from '@/stores/gameStore';
import { apiFetch, api } from '@/lib/api';
import { t } from '@/lib/i18n';
import {
  Newspaper, Briefcase, ShoppingBag,
  Zap,
  Phone, Battery, Signal,
  ChevronRight, ChevronLeft, Lock,
  Users, Clock, MapPin, AlertCircle, UserPlus, Coins,
} from 'lucide-react';
import { MissionModal } from '../ui/MissionModal';
import { MissionResultModal } from '../ui/MissionResultModal';
// Phase 15 — Journal unifié (20-04-2026, consigne user) :
// A (JournalFooterCol inline) + B (ExpandableBlock lightbox) + C (4-tabs)
// sont fusionnés : le lightbox de B affiche le JournalFullPanel (ex-C),
// et son tab « Événements » réintègre l'ancien contenu de B (liste notifs)
// enrichi en blocks + colonnes. JournalOverlay isolé supprimé du rendu.
import { JournalFooterCol } from '../ui/JournalFooterCol';
import { JournalFullPanel } from '../ui/JournalFullPanel';
import { ExpandableBlock } from '../ui/ExpandableBlock';
import { MultiplayerPanel } from '../ui/MultiplayerPanel';
import { EmpireCreateOrderModal } from '../ui/EmpireCreateOrderModal';
import { DealerMissionCreateModal } from '../ui/DealerMissionCreateModal';
// Phase 14 — Cartel/Gang complet (19-04-2026)
import { CartelPaneV2 } from '../cartel/CartelPaneV2';
import { GangPaneV2 } from '../gang/GangPaneV2';
// Phase 15 Commit 2 — map-pick partagé (20-04-2026)
import { useMapPick, MapPickButton } from '../map/useMapPick';

// ─── Mapping backend category → frontend path ───
const CATEGORY_TO_PATH: Record<string, MissionPath> = {
  story_crime: 'crime',
  story_politics: 'politique',
  story_redemption: 'redemption',
  // story_common intentionally omitted — shown in ALL paths via filter logic
};

// ─── Types ───
interface MissionSummary {
  id: string;
  code: string;
  title: string;
  description?: string;
  category: string;
  difficulty?: string;
  duration_minutes?: number;
  men_required?: number;
  base_success_rate?: number;
  police_risk?: number;
}

interface MissionDetail extends MissionSummary {
  narrative?: string | null;
  has_moral_choice?: boolean;
  choice_a_conscience?: number;
  choice_b_conscience?: number;
  prerequisites?: Record<string, any>;
  rewards_success?: Record<string, any>;
  rewards_failure?: Record<string, any>;
  unlocks_tab?: string | null;
}

// ─── Footer ───
export function Footer() {
  const { isAuthenticated, uiVisibility, isJournalOpen, setJournalOpen } = useGameStore();

  if (!isAuthenticated) return null;

  const showMultiplayer = uiVisibility.chat;
  const nothingUnlocked = !uiVisibility.journal && !uiVisibility.missions && !uiVisibility.phone && !showMultiplayer;

  // 5-col grid widths aligned with v2 mockup (vue-normale.html):
  //   Journal 220px · Multijoueur 1fr · Histoire 220px · Empire 1fr · Phone 128px
  // Whichever column is hidden by uiVisibility is simply skipped by React —
  // grid stretches remaining columns naturally.
  return (
    <>
      <footer
        className="w-full h-full shrink-0 grid"
        style={{
          gridTemplateColumns: '220px 1fr 220px 1fr 128px',
          background: 'transparent',
        }}
      >
        {uiVisibility.journal && (
          <div className="footer-col overflow-hidden p-3 relative" style={{ borderRight: '1px solid var(--border-dark)' }}>
            <ExpandableBlock
              label="Journal & événements"
              className="h-full"
              open={isJournalOpen}
              onOpenChange={setJournalOpen}
              lightboxContent={<JournalFullPanel />}
            >
              <JournalFooterCol />
            </ExpandableBlock>
          </div>
        )}

        {showMultiplayer && (
          <div className="footer-col overflow-hidden p-3 relative" style={{ borderRight: '1px solid var(--border-dark)' }}>
            <ExpandableBlock label="Multijoueur" className="h-full">
              <MultiplayerPanel />
            </ExpandableBlock>
          </div>
        )}

        {/* audit 15-04-2026 Phase 12 : SCISSION REELLE des colonnes.
            Missions (Histoire) et Gestion Empire sont maintenant deux colonnes
            distinctes du footer, plus une toggle interne dans une colonne unique. */}
        {uiVisibility.missions && (
          <div className="footer-col overflow-hidden p-3 relative" style={{ borderRight: '1px solid var(--border-dark)' }}>
            <ExpandableBlock label="Histoire & missions" className="h-full">
              <MissionsColumn />
            </ExpandableBlock>
          </div>
        )}

        {uiVisibility.missions_autonomes && (
          <div className="footer-col overflow-hidden p-3 relative" style={{ borderRight: '1px solid var(--border-dark)' }}>
            <ExpandableBlock label="Gestion Gang / Cartel" className="h-full">
              <EmpireColumn />
            </ExpandableBlock>
          </div>
        )}

        {uiVisibility.phone && (
          <div className="footer-col flex items-center justify-center p-2 relative">
            {/* No ExpandableBlock here — the phone column IS a button that
                opens the existing PhoneOverlay (11 screens). Wrapping it
                would intercept the click. */}
            <PhoneColumn />
          </div>
        )}

        {nothingUnlocked && (
          <div className="footer-col flex-1 flex items-center justify-center">
            <p className="text-xs" style={{ color: 'var(--text-muted)' }}>{t('footer.copyright')}</p>
          </div>
        )}
      </footer>
      {/* JournalOverlay supprimé du rendu global — son contenu vit maintenant
          dans le lightbox de l'ExpandableBlock « Journal & événements ». */}
    </>
  );
}

// ─── Journal Column ───
type JournalSection = 'infos' | 'emploi' | 'marche';

function JournalColumn() {
  const [section, setSection] = useState<JournalSection | null>(null);

  const sections: { id: JournalSection; icon: typeof Newspaper; label: string }[] = [
    { id: 'infos', icon: Newspaper, label: t('footer.journal_infos') },
    { id: 'emploi', icon: Briefcase, label: t('footer.journal_emploi') },
    { id: 'marche', icon: ShoppingBag, label: t('footer.journal_marche') },
  ];

  return (
    <div className="h-full flex flex-col">
      <div className="flex items-center gap-1 mb-1">
        {section && (
          <button onClick={() => setSection(null)} className="p-0.5 hover:opacity-70">
            <ChevronLeft size={12} style={{ color: 'var(--color-gold)' }} />
          </button>
        )}
        <h4 className="font-impact text-[10px]" style={{ color: 'var(--color-gold)' }}>{t('footer.journal')}</h4>
      </div>

      {!section ? (
        <div className="flex gap-1 flex-1">
          {sections.map((s) => (
            <button
              key={s.id}
              onClick={() => setSection(s.id)}
              className="flex-1 flex flex-col items-center justify-center gap-1 rounded hover:bg-[var(--bg-hover)] transition-colors"
            >
              <s.icon size={16} style={{ color: 'var(--text-muted)' }} />
              <span className="text-[9px]" style={{ color: 'var(--text-muted)' }}>{s.label}</span>
            </button>
          ))}
        </div>
      ) : (
        <div className="flex-1 overflow-y-auto text-[10px]" style={{ color: 'var(--text-secondary)' }}>
          <JournalContent section={section} />
        </div>
      )}
    </div>
  );
}

function JournalContent({ section }: { section: JournalSection }) {
  const [items, setItems] = useState<{ id: string; title: string; description?: string; content?: string; salary?: number }[]>([]);
  const [loading, setLoading] = useState(true);
  const [selected, setSelected] = useState<typeof items[0] | null>(null);

  useEffect(() => {
    setLoading(true);
    setSelected(null);
    const endpoint =
      section === 'infos' ? '/api/blog/posts' :
      section === 'emploi' ? '/api/employment/catalog' :
      '/api/marketplace/listings';

    apiFetch<any>(endpoint)
      .then((res) => {
        const data = Array.isArray(res) ? res : res?.posts ?? res?.data ?? res?.items ?? [];
        setItems(data.slice(0, 12).map((item: any) => ({
          id: item.id || item._id || item.type || String(Math.random()),
          title: item.title || item.name || item.job_title || t('common.no_title'),
          description: item.description || item.excerpt || item.schedule || '',
          content: item.content || item.body || '',
          salary: item.revenue_per_payslip || item.price || undefined,
        })));
      })
      .catch(() => setItems([]))
      .finally(() => setLoading(false));
  }, [section]);

  if (loading) return <p style={{ color: 'var(--text-muted)' }}>{t('common.loading')}</p>;
  if (items.length === 0) return <p style={{ color: 'var(--text-muted)' }}>{t('footer.no_content')}</p>;

  // Niveau 3 : detail d'un item selectionne
  if (selected) {
    return (
      <div>
        <button onClick={() => setSelected(null)} className="flex items-center gap-0.5 mb-2 text-[9px] hover:opacity-70" style={{ color: 'var(--color-gold)' }}>
          <ChevronLeft size={10} /> {t('common.back')}
        </button>
        <h4 className="text-[10px] font-bold mb-1" style={{ color: 'var(--text-primary)' }}>{selected.title}</h4>
        {selected.salary != null && (
          <p className="text-[9px] mb-1" style={{ color: 'var(--color-gold)' }}>{selected.salary}∞</p>
        )}
        {selected.description && (
          <p className="text-[9px] leading-relaxed" style={{ color: 'var(--text-secondary)' }}>{selected.description}</p>
        )}
        {selected.content && (
          <p className="text-[9px] leading-relaxed mt-1" style={{ color: 'var(--text-muted)' }}>
            {selected.content.length > 300 ? selected.content.slice(0, 300) + '...' : selected.content}
          </p>
        )}
      </div>
    );
  }

  // Niveau 2 : liste des items
  return (
    <div className="space-y-1">
      {items.map((item) => (
        <div
          key={item.id}
          onClick={() => setSelected(item)}
          className="p-1.5 rounded cursor-pointer hover:bg-[var(--bg-hover)] transition-colors flex items-center gap-1"
        >
          <ChevronRight size={8} style={{ color: 'var(--color-gold)' }} />
          <span className="truncate">{item.title}</span>
        </div>
      ))}
    </div>
  );
}

// ─── Missions Column ───
// audit 15-04-2026 Phase 12 : type MissionCategoryUI supprime — scission en 2 colonnes
// distinctes. MissionsColumn gere Histoire uniquement, EmpireColumn gere Empire.
// Phase 8 (2026-04-27) : ajout du path 'prison' qui remplace les 3 paths story_*
// quand le joueur est incarcéré. 1 seul bouton « Histoire Carcérale » couleur #885af2.
type MissionPath = 'crime' | 'politique' | 'redemption' | 'prison' | 'hospital';

/**
 * Phase 8 (2026-04-27) — bouton unique « Histoire Carcérale » qui remplace
 * les 3 PathSelector standards quand le joueur est incarcéré. Style story-tab
 * + couleur #885af2 + SVG personnage derrière barreaux.
 */
function PrisonStoryButton({ onSelect }: { onSelect: () => void }) {
  return (
    <div className="story flex-1 flex flex-col justify-center">
      <div className="story-meta">Évoluez au travers de missions&nbsp;:</div>
      <div className="story-tabs">
        <button
          type="button"
          onClick={onSelect}
          className="story-tab"
          aria-label="Histoire carcérale"
          title="Histoire carcérale"
          style={{
            color: '#885af2',
            border: '1px solid rgba(136,90,242,0.55)',
            background: 'linear-gradient(180deg, rgba(136,90,242,0.10), rgba(14,14,22,0.7))',
          }}
        >
          <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden>
            {/* 4 barreaux verticaux */}
            <rect x="3.5" y="3" width="1.1" height="18" />
            <rect x="9" y="3" width="1.1" height="18" />
            <rect x="14" y="3" width="1.1" height="18" />
            <rect x="19.5" y="3" width="1.1" height="18" />
            {/* Tête du personnage derrière les barreaux */}
            <circle cx="12" cy="9" r="2.4" />
            {/* Corps (épaules + buste) */}
            <path d="M7.5 18.5 Q12 14 16.5 18.5 L16.5 21.5 L7.5 21.5 Z" />
          </svg>
          <span className="n">Carcérale</span>
        </button>
      </div>
    </div>
  );
}

/**
 * Phase 8.5d.2 (2026-04-29) — Bouton "Missions Hôpital" qui remplace
 * les 3 PathSelector standards quand le joueur est hospitalisé. Style
 * story-tab + couleur bleu laser #60a5fa (cohérent border modal hospital).
 */
function HospitalStoryButton({ onSelect }: { onSelect: () => void }) {
  return (
    <div className="story flex-1 flex flex-col justify-center">
      <div className="story-meta">{t('footer.story_meta_default')}</div>
      {/* Phase 8.5d.2 (2026-04-29) — bouton unique centré pleine largeur,
          contour bleu laser cohérent avec border modal HospitalView. */}
      <div className="story-tabs" style={{ display: 'flex', justifyContent: 'center' }}>
        <button
          type="button"
          onClick={onSelect}
          className="story-tab"
          aria-label={t('footer.mission_hospital')}
          title={t('footer.mission_hospital')}
          style={{
            color: '#60a5fa',
            border: '1px solid rgba(96,165,250,0.6)',
            background: 'linear-gradient(180deg, rgba(96,165,250,0.10), rgba(14,14,22,0.7))',
            boxShadow: '0 0 8px rgba(96,165,250,0.25)',
            width: '100%',
            padding: '20px',
          }}
        >
          <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden>
            {/* Croix médicale */}
            <rect x="10" y="3" width="4" height="18" rx="1" />
            <rect x="3" y="10" width="18" height="4" rx="1" />
          </svg>
          <span className="n">{t('footer.mission_hospital')}</span>
        </button>
      </div>
    </div>
  );
}

/** Path selector with lock icons for unavailable tiers */
function PathSelector({ onSelect }: { onSelect: (p: MissionPath) => void }) {
  const player = useGameStore((s) => s.player);

  const paths: Array<{ id: MissionPath; variant: 'c' | 'p' | 'r'; iconPath: ReactElement; labelKey: string; tierField: 'criminal_tier' | 'political_tier' | 'legal_tier' }> = [
    {
      id: 'crime',
      variant: 'c',
      labelKey: 'footer.mission_crime',
      tierField: 'criminal_tier',
      iconPath: (
        <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden>
          <path d="M14 2 8 8l-4-1-2 3 14 12 3-2-1-4 6-6-10-8z" />
        </svg>
      ),
    },
    {
      id: 'politique',
      variant: 'p',
      labelKey: 'footer.mission_politique',
      tierField: 'political_tier',
      iconPath: (
        <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden>
          <path d="M12 2 3 7v6c0 5 4 9 9 10 5-1 9-5 9-10V7z" />
        </svg>
      ),
    },
    {
      id: 'redemption',
      variant: 'r',
      labelKey: 'footer.mission_redemption',
      tierField: 'legal_tier',
      iconPath: (
        <svg viewBox="0 0 24 24" fill="currentColor" aria-hidden>
          <path d="M12 2c3 4 3 8 0 12-3-4-3-8 0-12z" />
        </svg>
      ),
    },
  ];

  return (
    <div className="story flex-1 flex flex-col justify-center">
      <div className="story-meta">Évoluez au travers de missions&nbsp;:</div>
      <div className="story-tabs">
        {paths.map(({ id, variant, iconPath, labelKey, tierField }) => {
          const tier = (player as any)?.[tierField] ?? 0;
          const unlocked = tier > 0;
          return (
            <button
              key={id}
              onClick={() => unlocked && onSelect(id)}
              disabled={!unlocked}
              className={`story-tab story-tab-${variant} ${unlocked ? '' : 'story-tab-locked'}`}
              aria-label={t(labelKey)}
              title={unlocked ? t(labelKey) : 'Verrouillée'}
            >
              {unlocked ? iconPath : <Lock size={18} aria-hidden />}
              <span className="n">{unlocked ? t(labelKey) : 'Verrouillée'}</span>
            </button>
          );
        })}
      </div>
    </div>
  );
}

// audit 15-04-2026 Phase 12 : MissionsColumn simplifiee — HISTOIRE UNIQUEMENT.
// Le panneau Empire (ordres gangsters) est maintenant dans une colonne distincte
// (EmpireColumn) rendue en parallele dans le Footer principal.
type MissionStatusFull = 'completed' | 'in_progress' | 'available' | 'locked';
interface MissionWithStatus extends MissionSummary {
  status: MissionStatusFull;
  locked_reasons: string[];
  order_index?: number;
}

function MissionsColumn() {
  const [path, setPath] = useState<MissionPath | null>(null);
  // Queue of uncompleted next missions for the selected path (first available or locked).
  // Locked missions render with a red notice (user consigne 2026-04-18) instead
  // of being hidden — the player knows what's next and what they need.
  const [missions, setMissions] = useState<MissionWithStatus[]>([]);
  const [loading, setLoading] = useState(false);
  const [selectedMission, setSelectedMission] = useState<MissionDetail | null>(null);
  const [inProgress, setInProgress] = useState<any | null>(null);
  const [showResult, setShowResult] = useState(false);

  const player = useGameStore((s) => s.player);
  // Phase 8 (2026-04-27) — détection prison pour swap PathSelector → PrisonStoryButton
  const prisonStatus = useGameStore((s) => s.prisonStatus);
  const isImprisoned = !!prisonStatus?.is_imprisoned;
  // Phase 8.5d.2 (2026-04-29) — détection hôpital pour swap → HospitalStoryButton
  const hospitalStatus = useGameStore((s) => s.hospitalStatus);
  const isInHospital = !!hospitalStatus?.is_hospitalized;

  // Phase 15 Commit 5 (19-04-2026) — Q5 option C : si membre d'un gang NPC,
  // Mode Histoire cède la place à la ligne de missions du gang NPC.
  // Disparaît si le joueur quitte le gang (retour aux 3 paths classiques).
  const [npcGang, setNpcGang] = useState<any | null>(null);
  useEffect(() => {
    let cancelled = false;
    api.gang.getMy().then((g: any) => {
      if (!cancelled) setNpcGang(g?.gang_code ? g : null);
    }).catch(() => { if (!cancelled) setNpcGang(null); });
    return () => { cancelled = true; };
  }, []);

  // Phase 8.5d.2 fix (2026-05-01) — Hospital + prison sont des situations
  // TEMPORAIRES qui doivent primer sur l'affichage des missions gang NPC,
  // sinon HospitalStoryButton (et PrisonStoryButton) ne s'affichent jamais
  // pour les joueurs membres d'un gang NPC, rendant les missions hôpital
  // (H_01_REVEIL etc.) inaccessibles. Bug user confirmé 2026-05-01.
  //
  // Phase 8 v3 fix (2026-05-02) — React error #310 : l'early return ici
  // était APRÈS 6 useState et 1 useEffect MAIS AVANT 4 useCallback +
  // 5 useEffect plus bas. Quand npcGang passait de null → loaded, le
  // nombre de hooks rendus changeait → React #310 crash. Le branch est
  // déplacé EN BAS du composant (juste avant le return JSX) pour
  // garantir un nombre de hooks constant à chaque render.

  const loadMissions = useCallback(async (currentPath: MissionPath | null) => {
    if (!currentPath) return;
    setLoading(true);
    try {
      if (currentPath === 'prison') {
        // Phase 8 (2026-04-27) — mode incarcéré : on lit /api/prison/status
        // dont la sémantique : 0..1 mission disponible + mission_in_progress
        // séparée. Si in_progress, on rend la prochaine en locked + infobulle.
        const ps = await apiFetch<any>('/api/prison/status');
        const list: any[] = Array.isArray(ps?.available_missions) ? ps.available_missions : [];
        const hasInProgress = !!ps?.mission_in_progress;
        const mapped: MissionWithStatus[] = list.map((m: any) => ({
          id: m.id,
          code: m.code,
          title: m.title,
          description: m.description,
          category: m.category ?? 'prison',
          difficulty: m.difficulty,
          duration_minutes: m.duration_minutes,
          men_required: m.men_required,
          base_success_rate: m.base_success_rate,
          police_risk: m.police_risk,
          order_index: m.order_index,
          status: hasInProgress ? 'locked' : 'available',
          locked_reasons: hasInProgress ? ['Chaque chose en son temps, vous êtes déjà en mission.'] : [],
        }));
        setMissions(mapped);
        return;
      }

      // Phase 8.5d.2 (2026-04-29) — mode hôpital : 3 missions séquentielles
      // (H_01 → H_02 → H_03). Toutes affichées avec status calculé :
      //   - 'completed' si dans completedCodes (label "Fait")
      //   - 'in_progress' si missionInProgress matche
      //   - 'locked' si prereqs non-met OU autre mission hospital en cours
      //   - 'available' sinon
      if (currentPath === 'hospital') {
        const all = await apiFetch<any[]>('/api/mission/catalog/hospital');
        const allProgress = await apiFetch<any[]>('/api/mission/progress');
        const progressList = Array.isArray(allProgress) ? allProgress : [];
        const completedCodes = new Set(
          progressList.filter((p) => p.status === 'completed' && p.mission?.code).map((p) => p.mission.code as string),
        );
        const inProg = progressList.find(
          (p) => p.status === 'in_progress' && p.mission?.code?.startsWith('H_'),
        );
        const inProgCode = inProg?.mission?.code as string | undefined;

        // Phase 8 v2 (2026-05-01) — Consigne user verbatim : "Une mission
        // hopitale effectuée n'est plus représentée." → on filtre les
        // missions completed du catalog (skip avant le map).
        const list = (Array.isArray(all) ? all : [])
          .filter((m: any) => !completedCodes.has(m.code))
          .sort((a, b) => (a.order_index ?? 0) - (b.order_index ?? 0));
        const mapped: MissionWithStatus[] = list.map((m: any) => {
          const isInProgress = inProgCode === m.code;
          const prereqCodes: string[] = m.prerequisites?.missions ?? [];
          const prereqMet = prereqCodes.every((c) => completedCodes.has(c));

          let status: MissionWithStatus['status'] = 'available';
          const lockedReasons: string[] = [];
          if (isInProgress) {
            status = 'in_progress';
          } else if (!prereqMet) {
            status = 'locked';
            lockedReasons.push(t('footer.mission_locked_prereq'));
          } else if (inProgCode) {
            status = 'locked';
            lockedReasons.push(t('footer.mission_locked_in_progress'));
          }

          return {
            id: m.id,
            code: m.code,
            title: m.title,
            description: m.description,
            category: m.category ?? 'hospital',
            difficulty: m.difficulty,
            duration_minutes: m.duration_minutes,
            men_required: m.men_required,
            base_success_rate: m.base_success_rate,
            police_risk: m.police_risk,
            order_index: m.order_index,
            status,
            locked_reasons: lockedReasons,
          } as MissionWithStatus;
        });
        setMissions(mapped);
        return;
      }
      const res = await apiFetch<MissionWithStatus[]>(`/api/mission/path/${currentPath}`);
      const all = Array.isArray(res) ? res : [];
      // story_common priority if this is the chosen_path (first tier).
      const chosenPath = (player as any)?.chosen_path as string | null;
      const isFirstTier = currentPath === chosenPath;

      const uncompleted = all.filter((m) => m.status !== 'completed' && m.status !== 'in_progress');

      const nextCommon = isFirstTier
        ? uncompleted.find((m) => m.category === 'story_common')
        : null;

      if (nextCommon) {
        setMissions([nextCommon]);
      } else {
        const tierMission = uncompleted.find((m) => {
          const mappedPath = CATEGORY_TO_PATH[m.category];
          return mappedPath === currentPath;
        });
        setMissions(tierMission ? [tierMission] : []);
      }
    } catch {
      setMissions([]);
    } finally {
      setLoading(false);
    }
  }, [player]);

  useEffect(() => {
    loadMissions(path);
  }, [path, loadMissions]);

  // Phase 8 (2026-04-27) — reset le path 'prison' au release pour que le joueur
  // retombe naturellement sur le PathSelector standard (Crime/Politique/Rédemption).
  useEffect(() => {
    if (!isImprisoned && path === 'prison') setPath(null);
  }, [isImprisoned, path]);
  // Phase 8.5d.2 (2026-04-29) — Idem pour hôpital : reset path à la sortie.
  useEffect(() => {
    if (!isInHospital && path === 'hospital') setPath(null);
  }, [isInHospital, path]);

  const loadInProgress = useCallback(() => {
    // Ne pas poll quand le modal resultat est ouvert — evite de fermer le modal avant lecture
    if (showResult) return;
    apiFetch<any>('/api/mission/progress?status=in_progress')
      .then((res) => {
        const list = Array.isArray(res) ? res : res?.data ?? [];
        // Ne pas reset inProgress si le modal resultat est affiche
        if (!showResult) {
          setInProgress(list[0] ?? null);
        }
      })
      .catch(() => { if (!showResult) setInProgress(null); });
  }, [showResult]);

  useEffect(() => {
    loadInProgress();
    const id = window.setInterval(loadInProgress, 10000);
    return () => window.clearInterval(id);
  }, [loadInProgress]);

  const handleMissionClick = async (mission: MissionWithStatus) => {
    if (mission.status === 'locked' || mission.status === 'completed') return;
    try {
      const details = await apiFetch<MissionDetail>(`/api/mission/${mission.id}`);
      setSelectedMission(details);
    } catch (err) {
      console.error('Error loading mission details:', err);
    }
  };

  const handleMissionStarted = () => {
    loadMissions(path);
    loadInProgress();
  };

  // Phase 8 v3 fix (2026-05-02) — Bascule conditionnelle vers gang NPC
  // missions DEPUIS LE RENDU FINAL pour préserver l'ordre/nombre des
  // hooks (toutes les useState/useCallback/useEffect ci-dessus sont
  // appelées même quand on rend GangNpcMissionsColumn → React content).
  if (npcGang && !isInHospital && !isImprisoned) {
    return <GangNpcMissionsColumn gang={npcGang} />;
  }

  return (
    <div className="h-full flex flex-col">
      <div className="f-head">
        {path && (
          <button
            onClick={() => { setPath(null); setMissions([]); }}
            className="p-0.5 hover:opacity-70 shrink-0"
            aria-label="Retour"
          >
            <ChevronLeft size={12} style={{ color: 'var(--color-gold)' }} />
          </button>
        )}
        <span className="f-title">
          {/* v2 mockup Histoire SVG (compass crossroads) */}
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden>
            <path d="M4 4 8 8M20 4l-4 4M4 20l4-4M20 20l-4-4M12 6v12M6 12h12" />
          </svg>
          Histoire
        </span>
      </div>

      {inProgress?.mission && (
        <div
          className="mb-2 p-2 rounded"
          style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)' }}
        >
          <div className="flex items-center justify-between gap-2">
            <div className="min-w-0">
              <p className="text-[10px] font-bold truncate" style={{ color: 'var(--text-primary)' }}>{inProgress.mission.title}</p>
              <p className="text-[9px]" style={{ color: 'var(--text-muted)' }}>Mission en cours</p>
            </div>
            <button
              type="button"
              onClick={() => setShowResult(true)}
              className="px-2 py-1 rounded text-[10px] font-bold"
              style={{ background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.12)', color: 'var(--text-primary)' }}
            >
              Ouvrir
            </button>
          </div>
        </div>
      )}

      {/* Niveau 1: Crime | Politique | Redemption (histoire uniquement)
          OU Histoire Carcérale (Phase 8 — incarcéré)
          OU Missions Hôpital (Phase 8.5d.2 — hospitalisé)
          Priorité hôpital > prison > standard (cohérent avec play/page) */}
      {!path && !isInHospital && !isImprisoned && (
        <PathSelector onSelect={setPath} />
      )}
      {!path && isInHospital && (
        <HospitalStoryButton onSelect={() => setPath('hospital')} />
      )}
      {!path && !isInHospital && isImprisoned && (
        <PrisonStoryButton onSelect={() => setPath('prison')} />
      )}

      {/* Niveau 2: Liste missions Histoire */}
      {path && (
        <div className="flex-1 overflow-y-auto">
          {loading ? (
            <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>{t('common.loading')}</p>
          ) : missions.length === 0 ? (
            <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>{t('footer.no_missions')}</p>
          ) : (
            <div className="space-y-1">
              {missions.map((m) => {
                const isLocked = m.status === 'locked';
                const isCompleted = m.status === 'completed';
                const isInProgress = m.status === 'in_progress';
                const isPrison = m.category === 'prison';
                const isHospital = m.category === 'hospital';
                const nonClickable = isLocked || isCompleted;
                return (
                  <div
                    key={m.id}
                    onClick={() => handleMissionClick(m)}
                    title={isLocked && (isPrison || isHospital) && m.locked_reasons[0] ? m.locked_reasons[0] : undefined}
                    className={`p-1.5 rounded transition-colors ${nonClickable ? 'cursor-default' : 'cursor-pointer hover:bg-[var(--bg-hover)]'}`}
                    style={isCompleted ? { opacity: 0.5 } : isLocked ? { opacity: 0.88 } : undefined}
                  >
                    <div className="flex items-center justify-between gap-2">
                      <p className="text-[10px] font-bold truncate flex-1" style={{
                        color: isCompleted ? 'var(--text-muted)' : 'var(--text-primary)',
                        textDecoration: isCompleted ? 'line-through' : 'none',
                      }}>{m.title}</p>
                      {isCompleted && (
                        <span className="text-[9px] font-bold uppercase tracking-[.08em] px-1.5 py-0.5 rounded shrink-0"
                          style={{ background: 'rgba(34,197,94,0.15)', color: '#86efac', border: '1px solid rgba(34,197,94,0.4)' }}>
                          {t('footer.mission_done')}
                        </span>
                      )}
                      {isInProgress && (
                        <span className="text-[9px] font-bold uppercase tracking-[.08em] px-1.5 py-0.5 rounded shrink-0"
                          style={{ background: 'rgba(212,168,67,0.15)', color: 'var(--color-gold-light)', border: '1px solid var(--border-gold)' }}>
                          {t('footer.mission_in_progress')}
                        </span>
                      )}
                    </div>
                    {m.description && !isCompleted && (
                      <p className="text-[9px] truncate" style={{ color: 'var(--text-muted)' }}>{m.description}</p>
                    )}
                    {/* Bloc pré-requis : uniquement pour les missions story (pas prison/hospital) */}
                    {isLocked && !isPrison && !isHospital && (
                      <div
                        className="mt-1.5 p-1.5 rounded text-[9px] leading-tight"
                        style={{
                          background: 'rgba(196,30,30,0.09)',
                          border: '1px solid var(--border-red)',
                          color: 'var(--color-red-light)',
                        }}
                      >
                        <p className="font-bold mb-0.5">Vous devez vous procurer les pré-requis pour commencer.</p>
                        {m.locked_reasons.length > 0 && (
                          <ul className="list-disc pl-3 mt-0.5" style={{ color: 'var(--text-secondary)' }}>
                            {m.locked_reasons.slice(0, 5).map((r, i) => <li key={i}>{r}</li>)}
                          </ul>
                        )}
                      </div>
                    )}
                  </div>
                );
              })}
            </div>
          )}
        </div>
      )}

      {/* Mission Modal */}
      {selectedMission && (
        <MissionModal
          mission={selectedMission}
          onClose={() => setSelectedMission(null)}
          onStarted={handleMissionStarted}
        />
      )}

      <MissionResultModal
        open={showResult}
        onClose={() => {
          setShowResult(false);
          loadMissions(path);
          loadInProgress();
        }}
        progress={inProgress}
      />
    </div>
  );
}

// ═══ EmpireColumn (audit 15-04-2026 Phase 12) ═══
// Wrapper minimal qui pose l'en-tete "GESTION EMPIRE" puis delegue a EmpireOrdersView
// pour la logique (fetch gang + orders + members + modal create). Cette colonne est
// rendue en PARALLELE de MissionsColumn dans le Footer, plus comme sous-vue.
/** Phase 15 Commit 5 — remplace l'encart Histoire pour les membres d'un gang NPC.
 *  Affiche la ligne narrative du gang rejoint (missions séquentielles). La
 *  logique mission en cours / terminée / disponible / verrouillée reprend
 *  la même UX que MissionsColumn original. */
function GangNpcMissionsColumn({ gang }: { gang: any }) {
  const [missions, setMissions] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [active, setActive] = useState<any | null>(null);

  const load = useCallback(() => {
    setLoading(true);
    Promise.all([
      api.gangServices.listMissions(gang.id),
      api.gangServices.activeMission(gang.id),
    ]).then(([list, act]) => {
      setMissions(Array.isArray(list) ? list as any[] : []);
      setActive(act || null);
    }).catch(() => {
      setMissions([]);
      setActive(null);
    }).finally(() => setLoading(false));
  }, [gang.id]);

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

  if (loading) return (
    <div className="h-full flex flex-col p-2">
      <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>Chargement missions gang…</p>
    </div>
  );

  const uncompleted = missions.filter((m: any) => m.status !== 'completed' && m.status !== 'in_progress');
  const nextMission = uncompleted[0] || null;

  return (
    <div className="h-full flex flex-col gap-2 overflow-hidden">
      <div className="f-head">
        <span className="f-title">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden>
            <path d="M4 4 8 8 M20 4 16 8 M12 4v16 M4 20l4-4 M20 20l-4-4"/>
          </svg>
          <span>Missions — {gang.name}</span>
        </span>
      </div>

      <div className="flex-1 overflow-y-auto space-y-2">
        {active && (
          <div className="rounded p-2" style={{ background: 'rgba(196,30,30,0.08)', border: '1px solid var(--border-red)' }}>
            <p className="text-[9px] font-bold mb-1" style={{ color: 'var(--color-red-light)', letterSpacing: '.15em', fontFamily: 'var(--font-subtitle)' }}>
              EN COURS
            </p>
            <p className="text-[11px]" style={{ color: 'var(--text-primary)' }}>
              {active.template_code?.split('_').slice(2).join(' ').replace(/_/g, ' ') || 'Mission gang active'}
            </p>
            <button type="button" className="new-order is-red mt-1" style={{ width: '100%', fontSize: 10, padding: 4 }}
              onClick={() => window.dispatchEvent(new CustomEvent('open-gang-missions', { detail: { gang_id: gang.id, mission_id: active.id } }))}>
              Reprendre
            </button>
          </div>
        )}

        {nextMission ? (
          <div className="rounded p-2" style={{
            background: nextMission.status === 'locked' ? 'rgba(196,30,30,0.04)' : 'rgba(212,168,67,0.04)',
            border: `1px solid ${nextMission.status === 'locked' ? 'var(--border-red)' : 'var(--border-gold)'}`,
          }}>
            <p className="text-[9px] font-bold mb-1" style={{
              color: nextMission.status === 'locked' ? 'var(--color-red-light)' : 'var(--color-gold-light)',
              letterSpacing: '.15em', fontFamily: 'var(--font-subtitle)',
            }}>
              {nextMission.status === 'locked' ? 'VERROUILLÉE' : 'PROCHAINE'}
            </p>
            <p className="text-[11px] font-bold" style={{ color: 'var(--text-primary)' }}>{nextMission.name}</p>
            <p className="text-[10px]" style={{ color: 'var(--text-secondary)', lineHeight: 1.4 }}>{nextMission.description}</p>
            {nextMission.status === 'locked' && nextMission.locked_reasons?.length > 0 && (
              <ul className="text-[9px] mt-1 space-y-0.5" style={{ color: 'var(--color-red-light)' }}>
                {nextMission.locked_reasons.map((r: string, i: number) => <li key={i}>• {r}</li>)}
              </ul>
            )}
            {nextMission.status === 'available' && (
              <button type="button" className="new-order mt-2" style={{ width: '100%', fontSize: 10, padding: 4 }}
                onClick={async () => {
                  try {
                    await api.gangServices.startMission(gang.id, nextMission.code);
                    load();
                  } catch (e: any) { alert(e?.message || 'Erreur'); }
                }}>
                Démarrer ({nextMission.duration_minutes} min)
              </button>
            )}
          </div>
        ) : (
          <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
            Toutes les missions du gang ont été complétées. Bravo !
          </p>
        )}

        {missions.filter((m: any) => m.status === 'completed').length > 0 && (
          <div className="mt-1 pt-1" style={{ borderTop: '1px dashed rgba(255,255,255,0.1)' }}>
            <p className="text-[9px]" style={{ color: 'var(--text-muted)' }}>
              Complétées : {missions.filter((m: any) => m.status === 'completed').length} / {missions.length}
            </p>
          </div>
        )}
      </div>
    </div>
  );
}

function EmpireColumn() {
  const [topTab, setTopTab] = useState<'gang' | 'cartel'>('gang');
  const [empireTab, setEmpireTab] = useState<'orders' | 'recruit' | 'dealer'>('orders');
  return (
    <div className="h-full flex flex-col">
      {/* Top-level tabs — Gestion Gang (left) | Gestion Cartel (right),
          per user consigne point 5. Exclusive switch. */}
      <div className="gest-tabs" role="tablist">
        <button
          type="button"
          role="tab"
          aria-selected={topTab === 'gang'}
          className={`gest-tab ${topTab === 'gang' ? 'gest-tab-on' : ''}`}
          onClick={() => setTopTab('gang')}
          data-tutorial="empire-tab"
        >
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinejoin="round" aria-hidden>
            <path d="M3 10 8 5l4 3 4-3 5 5v9H3z" />
          </svg>
          Gestion Gang
        </button>
        <button
          type="button"
          role="tab"
          aria-selected={topTab === 'cartel'}
          className={`gest-tab ${topTab === 'cartel' ? 'gest-tab-on' : ''}`}
          onClick={() => setTopTab('cartel')}
        >
          Gestion Cartel
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden>
            <path d="M12 2 2 7l10 5 10-5zM2 17l10 5 10-5M2 12l10 5 10-5" />
          </svg>
        </button>
      </div>

      {topTab === 'gang' && (
        <>
          {/* Phase 14 — Pane principal gang (stats + services + missions) */}
          <GangPaneV2 />
          {/* Phase 13 UI: sous-onglets Ordres / Recrutement / Dealer (v2 mockup f-switch) */}
          <div className="f-switch mb-2 mt-2" role="tablist">
            {(['orders', 'recruit', 'dealer'] as const).map((tab) => (
              <button
                key={tab}
                type="button"
                role="tab"
                aria-selected={empireTab === tab}
                onClick={() => setEmpireTab(tab)}
                className={empireTab === tab ? 'on' : ''}
                style={{ flex: 1 }}
              >
                {tab === 'orders' ? 'Ordres' : tab === 'recruit' ? 'Recrutement' : 'Dealer'}
              </button>
            ))}
          </div>
          {empireTab === 'orders' && <EmpireOrdersView />}
          {empireTab === 'recruit' && <EmpireRecruitView />}
          {empireTab === 'dealer' && <DealerTabView onOpenModal={() => {}} />}
        </>
      )}

      {topTab === 'cartel' && <CartelPaneV2 />}
    </div>
  );
}

// Legacy CartelPane supprimé : remplacé par CartelPaneV2 (composants/cartel/).
// Les liens /account#cartel (bugs A-02, B-05 de l'audit 18-04-2026) sont éliminés.

// ─── Dealer Tab View ───
function DealerTabView({ onOpenModal }: { onOpenModal: () => void }) {
  const [missions, setMissions] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [showModal, setShowModal] = useState(false);
  const [gangData, setGangData] = useState<any>(null);

  const refresh = useCallback(async () => {
    setLoading(true);
    try {
      const [mData, gData] = await Promise.all([
        api.dealerMission.list().catch(() => []),
        api.gang.getMy().catch(() => null),
      ]);
      setMissions(Array.isArray(mData) ? mData : []);
      setGangData(gData);
    } finally { setLoading(false); }
  }, []);

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

  return (
    <div className="flex-1 min-h-0 flex flex-col">
      {gangData && (
        <button
          onClick={() => setShowModal(true)}
          className="w-full py-2 mb-2 rounded-lg text-[10px] font-bold flex items-center justify-center gap-1"
          style={{ background: 'rgba(168,85,247,0.15)', color: '#a855f7', border: '1px solid rgba(168,85,247,0.3)' }}
        >
          + Nouvelle mission dealer
        </button>
      )}
      {showModal && gangData && (
        <DealerMissionCreateModal
          gangId={gangData.id}
          members={gangData.members || []}
          onClose={() => setShowModal(false)}
          onCreated={() => { setShowModal(false); refresh(); }}
        />
      )}
      <div className="flex-1 overflow-y-auto space-y-1">
        {loading ? (
          <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>Chargement...</p>
        ) : missions.length === 0 ? (
          <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>Aucune mission dealer.</p>
        ) : missions.slice(0, 10).map((m: any) => (
          <div key={m.id} className="p-2 rounded-lg" style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)' }}>
            <div className="flex items-center justify-between">
              <span className="text-[11px] font-bold" style={{ color: '#a855f7' }}>{m.drug_name}</span>
              <span className="text-[9px] px-1.5 py-0.5 rounded" style={{
                background: m.status === 'completed' ? 'rgba(34,197,94,0.15)' : m.status === 'in_progress' ? 'rgba(59,130,246,0.15)' : 'rgba(255,255,255,0.06)',
                color: m.status === 'completed' ? '#22c55e' : m.status === 'in_progress' ? '#3b82f6' : 'var(--text-muted)',
              }}>{m.status}</span>
            </div>
            <p className="text-[9px]" style={{ color: 'var(--text-muted)' }}>
              {m.gangster_count} gangsters · {m.stock_reserved} unites · {m.duration_hours}h
              {m.revenue_total > 0 ? ` · ${m.revenue_total} ∞` : ''}
            </p>
          </div>
        ))}
      </div>
    </div>
  );
}

// ─── Empire Orders View (audit 15-04-2026, Phase 8) ───
//
// Panneau "Gestion Empire" : liste des ordres gangster actifs (order_type != 'travel'),
// statuts des gangsters du gang du joueur, et recents outcomes.
// Routes consommees (Phase 4) :
//   GET  /api/gang/mine               -> gang + members
//   GET  /api/gang/:id/orders         -> active orders (in_transit, non 'travel')
//   GET  /api/gang/:id/orders/recent  -> last 10 arrived orders with outcome
//   POST /api/gang/order/:id/cancel   -> cancel an in-transit order
//
// Phase 8.1 (MVP) : read-only. Le flow de creation d'ordre (modal avec selection
// gangster/cible/type) sera Phase 8.2.
// ═══ CreateGangForm — formulaire inline de création de gang ═══
function CreateGangForm({ onCreated }: { onCreated: () => void }) {
  const [name, setName] = useState('');
  const [governance, setGovernance] = useState<'hierarchical' | 'cooperative'>('hierarchical');
  const [creating, setCreating] = useState(false);
  const [error, setError] = useState<string | null>(null);
  // Phase 15 Commit 2 — map-pick obligatoire pour le point d'origine du gang
  const { pickedLat, pickedLng, startPick, pickBanner } = useMapPick({
    label: 'Création gang · cliquez sur la carte pour placer le point d\'origine',
    scope: 'gang',
    orderKey: 'create-gang',
  });

  const handleCreate = async () => {
    if (!name.trim() || name.trim().length < 3) { setError('Nom trop court (3 car. min)'); return; }
    if (pickedLat === null || pickedLng === null) {
      setError('Cliquez sur la carte pour choisir le point d\'origine de votre gang.');
      return;
    }
    setCreating(true);
    setError(null);
    try {
      const res: any = await api.gang.create({
        name: name.trim(),
        governance,
        origin_lat: pickedLat,
        origin_lng: pickedLng,
      });
      if (res?.id || res?.name) {
        onCreated();
      } else {
        setError(res?.error || 'Erreur de creation');
      }
    } catch (e: any) { setError(e?.message || 'Erreur'); }
    finally { setCreating(false); }
  };

  if (pickBanner) return pickBanner;

  return (
    <div className="space-y-3">
      <p className="text-[10px] font-bold" style={{ color: 'var(--color-gold)' }}>Creer votre gang</p>
      <input
        type="text"
        value={name}
        onChange={(e) => setName(e.target.value)}
        placeholder="Nom du gang"
        maxLength={40}
        className="w-full px-3 py-2 rounded-lg text-xs"
        style={{ background: 'var(--bg-tertiary)', border: '1px solid var(--border-dark)', color: 'var(--text-primary)' }}
      />
      <select
        value={governance}
        onChange={(e) => setGovernance(e.target.value as any)}
        className="w-full px-3 py-2 rounded-lg text-xs"
        style={{ background: 'var(--bg-tertiary)', border: '1px solid var(--border-dark)', color: 'var(--text-primary)' }}
      >
        <option value="hierarchical">Hierarchique (le chef decide)</option>
        <option value="cooperative">Cooperatif (vote majoritaire)</option>
      </select>
      <MapPickButton
        pickedLat={pickedLat} pickedLng={pickedLng} onClick={startPick}
        idleLabel="Choisir le point d'origine sur la carte"
      />
      {error && <p className="text-[9px]" style={{ color: '#ef4444' }}>{error}</p>}
      <button
        onClick={handleCreate}
        disabled={creating || !name.trim() || pickedLat === null}
        className="w-full py-2 rounded-xl text-xs font-bold disabled:opacity-50"
        style={{ background: 'var(--color-gold)', color: '#000' }}
        title={pickedLat === null ? 'Choisissez d\'abord un point sur la carte' : undefined}
      >
        {creating ? 'Creation...' : 'Creer mon gang'}
      </button>
    </div>
  );
}

function EmpireOrdersView() {
  const { uiVisibility } = useGameStore();
  const [gang, setGang] = useState<any | null>(null);
  const [orders, setOrders] = useState<any[]>([]);
  const [recent, setRecent] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [cancellingId, setCancellingId] = useState<string | null>(null);
  // audit 15-04-2026 Phase 8.2 : modal de creation d'ordre
  const [showCreateModal, setShowCreateModal] = useState(false);
  const [playerVehicles, setPlayerVehicles] = useState<any[]>([]);
  const player = useGameStore((s) => s.player);

  const loadGangData = useCallback(async () => {
    try {
      const g: any = await api.gang.getMy();
      setGang(g);
      if (g?.id) {
        const [act, rec] = await Promise.all([
          api.gang.listOrders(g.id) as Promise<any>,
          api.gang.listRecentOrderOutcomes(g.id, 5) as Promise<any>,
        ]);
        setOrders(Array.isArray(act) ? act : []);
        setRecent(Array.isArray(rec) ? rec : []);
      }
      setError(null);
    } catch (e: any) {
      setError(e?.message || 'Erreur');
    } finally {
      setLoading(false);
    }
  }, []);

  // Fetch available player vehicles for the create modal (Phase 8.2)
  const loadVehicles = useCallback(async () => {
    try {
      const v = await api.property.vehicles.list();
      setPlayerVehicles(Array.isArray(v) ? v : []);
    } catch { setPlayerVehicles([]); }
  }, []);

  useEffect(() => {
    loadGangData();
    loadVehicles();
    const id = window.setInterval(loadGangData, 15000);
    return () => window.clearInterval(id);
  }, [loadGangData, loadVehicles]);

  const handleCancel = async (journeyId: string) => {
    if (cancellingId) return;
    setCancellingId(journeyId);
    try {
      await api.gang.cancelOrder(journeyId);
      await loadGangData();
    } catch (e: any) {
      setError(e?.message || 'Annulation echouee');
    } finally {
      setCancellingId(null);
    }
  };

  // Derived state
  const members = useMemo(() => (gang?.members ?? []) as any[], [gang]);
  const availableCount = useMemo(
    () => members.filter((m: any) =>
      !m.in_transit && !m.guarding_building_id && !m.assigned_racket_zone_id
      && !(m.hospitalized_until && new Date(m.hospitalized_until) > new Date())
    ).length,
    [members],
  );

  if (loading && !gang) {
    return <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>{t('common.loading')}</p>;
  }
  if (error && !gang) {
    return (
      <div className="flex items-center gap-1 p-2 rounded" style={{ background: 'rgba(239,68,68,0.1)', border: '1px solid rgba(239,68,68,0.25)' }}>
        <AlertCircle size={12} style={{ color: '#ef4444' }} />
        <p className="text-[10px]" style={{ color: '#ef4444' }}>{error}</p>
      </div>
    );
  }
  // ─── Phase Gang: états sans gang ─────────────────────
  if (!gang) {
    // Cas 1: le joueur n'a pas encore débloqué le système de gang
    if (!uiVisibility.gang) {
      return (
        <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
          Debloquez en completant la 3eme mission criminelle.
        </p>
      );
    }
    // Cas 2: unlock gang mais pas encore de gang → formulaire de création
    return <CreateGangForm onCreated={loadGangData} />;
  }

  const memberStatus = (m: any): { label: string; color: string } => {
    if (m.hospitalized_until && new Date(m.hospitalized_until) > new Date()) {
      return { label: 'Hospitalise', color: '#94a3b8' };
    }
    if (m.in_transit) return { label: 'En transit', color: '#3b82f6' };
    if (m.guarding_building_id) return { label: 'En garde', color: '#a855f7' };
    if (m.assigned_racket_zone_id) return { label: 'Racket', color: '#f97316' };
    return { label: 'Disponible', color: '#22c55e' };
  };

  const formatETA = (iso: string | null): string => {
    if (!iso) return '—';
    const ms = new Date(iso).getTime() - Date.now();
    if (ms <= 0) return 'arrivé';
    const min = Math.round(ms / 60000);
    return min < 60 ? `${min}min` : `${Math.round(min / 60)}h`;
  };

  const orderTypeLabel: Record<string, string> = {
    mission: 'Mission',
    patrol: 'Patrouille',
    guard: 'Garde',
    racket: 'Racket',
    collect: 'Collecte',
    escort: 'Escorte',
    recon: 'Reconnaissance',
    dead_drop: 'Depot mort',
  };

  return (
    <div className="flex-1 overflow-y-auto space-y-2 pr-1">
      {/* Gang header */}
      <div className="px-1 flex items-center justify-between text-[9px]">
        <span style={{ color: 'var(--color-gold)' }} className="font-bold truncate">{gang.name}</span>
        <span style={{ color: 'var(--text-muted)' }}>
          {members.length}m · <span style={{ color: '#22c55e' }}>{availableCount} dispo</span>
        </span>
      </div>

      {/* + Nouvel ordre button — v2 mockup .new-order (dashed gold border, soft gold gradient) */}
      <button
        type="button"
        onClick={() => setShowCreateModal(true)}
        disabled={availableCount === 0}
        className="new-order"
        style={availableCount === 0 ? { opacity: 0.35, cursor: 'not-allowed' } : undefined}
      >
        ＋ Nouvel ordre
      </button>

      {/* Active orders */}
      <div>
        <p className="text-[9px] font-bold mb-1" style={{ color: 'var(--text-muted)' }}>
          ORDRES ACTIFS ({orders.length})
        </p>
        {orders.length === 0 ? (
          <p className="text-[9px] italic px-1" style={{ color: 'var(--text-muted)' }}>Aucun ordre en cours</p>
        ) : (
          <div className="space-y-1">
            {orders.map((o: any) => (
              <div
                key={o.id}
                className="p-1.5 rounded flex items-center justify-between gap-1"
                style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)' }}
              >
                <div className="min-w-0 flex-1">
                  <p className="text-[10px] font-bold truncate" style={{ color: 'var(--text-primary)' }}>
                    {orderTypeLabel[o.order_type] || o.order_type}
                  </p>
                  <div className="flex items-center gap-1 text-[9px]" style={{ color: 'var(--text-muted)' }}>
                    <Clock size={8} />
                    <span>ETA {formatETA(o.estimated_arrival)}</span>
                  </div>
                </div>
                <button
                  type="button"
                  onClick={() => handleCancel(o.id)}
                  disabled={cancellingId === o.id}
                  className="px-1.5 py-0.5 rounded text-[9px] hover:opacity-80"
                  style={{ background: 'rgba(239,68,68,0.1)', border: '1px solid rgba(239,68,68,0.25)', color: '#ef4444' }}
                >
                  {cancellingId === o.id ? '…' : 'Annuler'}
                </button>
              </div>
            ))}
          </div>
        )}
      </div>

      {/* Gangsters list */}
      <div>
        <p className="text-[9px] font-bold mb-1" style={{ color: 'var(--text-muted)' }}>
          GANGSTERS ({members.length})
        </p>
        {members.length === 0 ? (
          <p className="text-[9px] italic px-1" style={{ color: 'var(--text-muted)' }}>Aucun gangster recrute</p>
        ) : (
          <div className="space-y-0.5">
            {members.slice(0, 12).map((m: any) => {
              const st = memberStatus(m);
              const name = m.player?.username || m.player?.character_name || `#${String(m.player_id).slice(0, 6)}`;
              return (
                <div key={m.player_id} className="px-1 py-0.5 flex items-center justify-between gap-1 text-[9px]">
                  <div className="min-w-0 flex items-center gap-1">
                    <Users size={8} style={{ color: 'var(--text-muted)' }} />
                    <span style={{ color: 'var(--text-primary)' }} className="truncate">{name}</span>
                    <span style={{ color: 'var(--text-muted)' }}>· G{m.grade ?? 1}</span>
                  </div>
                  <span className="font-bold" style={{ color: st.color }}>{st.label}</span>
                </div>
              );
            })}
            {members.length > 12 && (
              <p className="text-[9px] italic px-1" style={{ color: 'var(--text-muted)' }}>
                +{members.length - 12} autres...
              </p>
            )}
          </div>
        )}
      </div>

      {/* Recent outcomes */}
      {recent.length > 0 && (
        <div>
          <p className="text-[9px] font-bold mb-1" style={{ color: 'var(--text-muted)' }}>
            RECENTS ({recent.length})
          </p>
          <div className="space-y-0.5">
            {recent.map((r: any) => (
              <div key={r.id} className="px-1 py-0.5 text-[9px] flex items-center gap-1" style={{ color: 'var(--text-muted)' }}>
                <MapPin size={8} />
                <span>{orderTypeLabel[r.order_type] || r.order_type}</span>
                <span>·</span>
                <span className="truncate">{r.outcome?.status || 'traite'}</span>
              </div>
            ))}
          </div>
        </div>
      )}

      {/* Create order modal (audit 15-04-2026 Phase 8.2) */}
      {showCreateModal && (
        <EmpireCreateOrderModal
          gangId={gang.id}
          members={members}
          defaultDestination={
            player?.current_lat != null && player?.current_lon != null
              ? { lat: Number(player.current_lat), lon: Number(player.current_lon) }
              : null
          }
          vehicles={playerVehicles}
          onClose={() => setShowCreateModal(false)}
          onCreated={() => { loadGangData(); }}
        />
      )}
    </div>
  );
}

// ═══ Phase 13 UI: EmpireRecruitView (onglet Recrutement dans Gestion Empire)
// Affiche le pool NPC quotidien du joueur avec cards candidats.
function EmpireRecruitView() {
  const [pool, setPool] = useState<any>(null);
  const [loading, setLoading] = useState(true);
  const [recruiting, setRecruiting] = useState<string | null>(null);
  const [msg, setMsg] = useState<string | null>(null);

  const fetchPool = useCallback(async () => {
    setLoading(true);
    try {
      const data: any = await api.gang.getRecruitPool();
      setPool(data);
    } catch { setPool(null); }
    finally { setLoading(false); }
  }, []);

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

  const handleRecruit = async (slotId: string) => {
    setRecruiting(slotId);
    setMsg(null);
    try {
      const res: any = await api.gang.recruitFromPool(slotId);
      if (res?.success) {
        setMsg(res.message || 'Recrute !');
        fetchPool(); // refresh pool
      } else {
        setMsg(res?.message || 'Echec');
      }
    } catch (e: any) { setMsg(e?.message || 'Erreur'); }
    finally { setRecruiting(null); }
  };

  if (loading) return <p className="text-[10px] p-2" style={{ color: 'var(--text-muted)' }}>Chargement...</p>;
  if (!pool) return <p className="text-[10px] p-2" style={{ color: 'var(--text-muted)' }}>Aucun pool disponible. Creez un gang d'abord.</p>;

  const slots = Array.isArray(pool.slots) ? pool.slots : [];

  return (
    <div className="flex-1 overflow-y-auto space-y-2">
      {/* Section terrain */}
      <div className="p-2 rounded-lg" style={{ background: 'rgba(34,197,94,0.06)', border: '1px solid rgba(34,197,94,0.15)' }}>
        <p className="text-[10px] font-bold mb-1" style={{ color: '#22c55e' }}>Recruter sur le terrain</p>
        <p className="text-[9px]" style={{ color: 'var(--text-muted)' }}>
          Rendez-vous dans un bar, un dock ou un commerce illegal sur la carte. Clic droit sur un PNJ present pour le recruter. Cout : 2 000 ∞-ombre.
        </p>
      </div>

      {/* Section pool quotidien */}
      <div className="flex items-center justify-between">
        <p className="text-[10px] font-bold" style={{ color: 'var(--text-secondary)' }}>
          Candidatures du jour ({slots.length})
        </p>
        <p className="text-[9px]" style={{ color: 'var(--text-muted)' }}>
          Refresh a minuit
        </p>
      </div>

      {msg && (
        <div className="p-2 rounded text-[10px]" style={{ background: 'rgba(212,168,67,0.1)', color: 'var(--color-gold)' }}>
          {msg}
        </div>
      )}

      {slots.length === 0 && (
        <p className="text-[10px] italic" style={{ color: 'var(--text-muted)' }}>
          Tous les candidats ont ete recrutes aujourd'hui. Revenez demain.
        </p>
      )}

      {slots.map((slot: any) => {
        const archColors: Record<string, string> = {
          street: '#6b7280', soldier: '#3b82f6', specialist: '#8b5cf6',
          veteran: '#f59e0b', elite: '#ef4444',
        };
        const color = archColors[slot.archetype] || '#6b7280';
        return (
          <div
            key={slot.slot_id}
            className="p-2 rounded-lg"
            style={{ background: 'rgba(255,255,255,0.03)', border: `1px solid ${color}30` }}
          >
            <div className="flex items-center justify-between mb-1">
              <div className="flex items-center gap-1.5">
                <div className="w-5 h-5 rounded-full flex items-center justify-center text-[8px] font-bold" style={{ background: `${color}20`, color, border: `1px solid ${color}40` }}>
                  {slot.grade}
                </div>
                <span className="text-[11px] font-bold" style={{ color: 'var(--text-primary)' }}>{slot.name}</span>
              </div>
              <span className="text-[9px] px-1.5 py-0.5 rounded" style={{ background: `${color}15`, color, border: `1px solid ${color}30` }}>
                {slot.archetype}
              </span>
            </div>
            <p className="text-[9px] mb-1.5" style={{ color: 'var(--text-muted)' }}>
              {slot.description}
            </p>
            <div className="flex items-center justify-between">
              <div className="flex gap-2 text-[9px]" style={{ color: 'var(--text-secondary)' }}>
                <span>HP {slot.hit_points}</span>
                <span>Loyaute {slot.loyalty}</span>
                {slot.specialty && <span className="italic">{slot.specialty}</span>}
              </div>
              <button
                onClick={() => handleRecruit(slot.slot_id)}
                disabled={recruiting !== null}
                className="flex items-center gap-1 px-2 py-1 rounded text-[9px] font-bold disabled:opacity-50"
                style={{
                  background: 'rgba(212,168,67,0.15)',
                  border: '1px solid rgba(212,168,67,0.35)',
                  color: 'var(--color-gold)',
                }}
              >
                <Coins size={10} />
                {recruiting === slot.slot_id ? '...' : `${slot.cost} ∞`}
              </button>
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ─── Phone Column ───
function PhoneColumn() {
  const { setPhoneOpen } = useGameStore();

  return (
    <button
      onClick={() => setPhoneOpen(true)}
      className="phone-col"
      aria-label="Ouvrir le téléphone"
      title="Ouvrir le téléphone"
    >
      <div className="phone-frame">
        <Phone size={32} aria-hidden />
      </div>
      <span className="phone-label">BrikFon 1000</span>
      <div className="phone-stats">
        <span className="bat"><Battery size={10} aria-hidden /> 87%</span>
        <span className="sig"><Signal size={10} aria-hidden /> 4/5</span>
      </div>
    </button>
  );
}



