'use client';
/**
 * OrderWizard — modal 3 étapes déclenché par les boutons OrderBar (Phase 15
 * Commit 3, 19-04-2026).
 *
 * Étapes :
 *   1. Sélection équipe (max 5 gangsters, inclure soi-même optionnel)
 *   2. Équipement : véhicules + armes (1/gangster) + gilets pare-balles
 *      (1 max/gangster). Les armes persistantes (GangMember.assigned_weapon)
 *      sont pré-cochées. Assignations temporaires = désassignées en fin de mission.
 *   3. Cible : POI à cliquer sur la carte, ou coords libres pour 'patrol'/move.
 *
 * Listen : window event 'order-wizard-open' avec detail = { scope, key, target? }
 * Dispatch : api.orderWizard.<key>(payload) puis ferme.
 */
import { useEffect, useState, useCallback } from 'react';
import { createPortal } from 'react-dom';
import { X } from 'lucide-react';
import { api } from '@/lib/api';
import { useGameStore } from '@/stores/gameStore';

type WizardState = {
  open: boolean;
  scope: 'gang' | 'cartel' | null;
  key: string;                  // 'visit' | 'buy' | 'guard' | 'attack' | 'develop' | 'recruit' | 'patrol' | 'extort' | 'rob'
  target?: { poi_type?: string; poi_id?: string; lat?: number; lng?: number };
  /** Phase 15 Iter 6.4 (19-04-2026) — visite multi-POI (chemin cumulé, visit only). */
  targets?: Array<{ poi_type: string; poi_id: string; label?: string }>;
};

const WIZARD_LABELS: Record<string, string> = {
  visit:   'Visiter',
  buy:     'Acheter',
  guard:   'Garder',
  attack:  'Attaquer',
  develop: 'Développer',
  redeem:  'Légaliser',    // Phase 13 (2026-04-20) — retire l'activité illégale cachée
  recruit: 'Recruter',
  patrol:  'Patrouiller',
  extort:  'Extorquer',
  rob:     'Braquer',
};

export function OrderWizard() {
  const { player } = useGameStore();
  // Phase 8.7 (2026-04-29) — si le joueur est en prison, il ne peut PAS
  // se mettre lui-même dans l'équipe (le backend OrderWizardService rejette).
  // On lit prisonStatus du store pour pré-décocher la checkbox.
  const prisonStatus = useGameStore((s) => s.prisonStatus);
  const isImprisoned = !!prisonStatus?.is_imprisoned;
  const [state, setState] = useState<WizardState>({ open: false, scope: null, key: '' });
  const [step, setStep] = useState<1 | 2 | 3>(1);
  const [team, setTeam] = useState<string[]>([]);
  const [includeSelf, setIncludeSelf] = useState(!isImprisoned);
  const [weapons, setWeapons] = useState<Record<string, string | null>>({});
  const [armors, setArmors] = useState<Record<string, string | null>>({});
  const [vehicleIds, setVehicleIds] = useState<string[]>([]);
  // Phase 15 (20-04-2026) — Consigne user : chaque gangster (y compris le
  // joueur) peut être assigné à un véhicule parmi ceux choisis. Le pilote
  // est déduit par le backend (meilleur conducteur parmi les passagers).
  // Gangsters sans assignement → trajet à pied en parallèle.
  const [vehicleAssign, setVehicleAssign] = useState<Record<string, string | null>>({});
  const [gangMembers, setGangMembers] = useState<any[]>([]);
  const [cartelMembers, setCartelMembers] = useState<any[]>([]);
  const [submitting, setSubmitting] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [result, setResult] = useState<any>(null);
  // Phase 15 (20-04-2026) — mode map-pick : le wizard se minimise en
  // bandeau pour laisser la carte visible pendant que l'utilisateur clique
  // un POI / une location. Consigne user : « entre les etapes 2 et 3 le
  // joueur doit cliquer sur un POI ou location sur la carte selon l'ordre »
  const [pickMode, setPickMode] = useState(false);
  // Programmation différée : date+heure pour démarrer la mission plus tard
  const [scheduleEnabled, setScheduleEnabled] = useState(false);
  const [scheduledAt, setScheduledAt] = useState<string>(''); // ISO local datetime-local
  // Phase 16 (2026-04-22) — unification racket : pour 'extort' on peut
  // demander la création/extension d'une RacketZone récurrente après victoire.
  const [createRacketZone, setCreateRacketZone] = useState(false);

  // Listen on event
  useEffect(() => {
    const handler = (e: Event) => {
      const detail = (e as CustomEvent).detail as { scope: 'gang' | 'cartel'; key: string; target?: any };
      setState({ open: true, scope: detail.scope, key: detail.key, target: detail.target });
      setStep(1);
      setTeam([]);
      // Phase 8.7 — si emprisonné, force includeSelf=false (backend rejette sinon).
      setIncludeSelf(!isImprisoned);
      setWeapons({});
      setArmors({});
      setVehicleIds([]);
      setVehicleAssign({});
      setResult(null);
      setError(null);
      setPickMode(false);
      setScheduleEnabled(false);
      setScheduledAt('');
      setCreateRacketZone(false);
    };
    window.addEventListener('order-wizard-open', handler);
    return () => window.removeEventListener('order-wizard-open', handler);
  }, []);

  // Écoute du retour du mode pick (GameMap dispatche ces 2 events)
  useEffect(() => {
    const pickResult = (e: Event) => {
      const d = (e as CustomEvent).detail as { poi_type?: string; poi_id?: string; lat?: number; lng?: number };
      if (!d) return;
      setState(s => ({ ...s, target: { ...d } }));
      setPickMode(false);
      setStep(3);
    };
    const pickCancel = () => { setPickMode(false); };
    window.addEventListener('map-pick-result', pickResult);
    window.addEventListener('map-pick-cancel', pickCancel);
    return () => {
      window.removeEventListener('map-pick-result', pickResult);
      window.removeEventListener('map-pick-cancel', pickCancel);
    };
  }, []);

  // Load gang/cartel members pool
  useEffect(() => {
    if (!state.open) return;
    if (state.scope === 'gang') {
      api.gang.getMy().then((g: any) => {
        // Phase 15 (20-04-2026) — pool Step 1 exclut le joueur lui-même :
        // il est ajouté via la checkbox « Je participe » pour éviter la
        // redondance (plus de double comptage possible).
        setGangMembers((g?.members ?? [])
          .filter((m: any) => m.player_id !== player?.id)
          .filter((m: any) => !m.in_transit && !m.guarding_building_id && !m.unpaid_since));
      }).catch(() => setGangMembers([]));
    } else if (state.scope === 'cartel') {
      api.cartel.getMine().then((c: any) => {
        // Pool = members' gangsters (simplification : on reprend les gangsters des gangs du cartel)
        const all: any[] = [];
        for (const mem of c?.members ?? []) {
          // Pour l'instant on affiche juste le leader de chaque gang (extension future)
          if (mem.leader_player_id) all.push({ player_id: mem.leader_player_id, grade: 1, name: mem.gang_name });
        }
        setCartelMembers(all);
      }).catch(() => setCartelMembers([]));
    }
  }, [state.open, state.scope, player?.id]);

  const close = useCallback(() => setState(s => ({ ...s, open: false })), []);

  const pool = state.scope === 'gang' ? gangMembers : cartelMembers;

  const toggleMember = (pid: string) => {
    setTeam(t => t.includes(pid) ? t.filter(x => x !== pid) : (t.length < 5 ? [...t, pid] : t));
  };

  const submit = async () => {
    // Validation horaire programmé (consigne user : rejet poli « maintenant
    // ou plus tard ? » sans fermer le modal si heure dépassée)
    if (scheduleEnabled && scheduledAt) {
      const target = new Date(scheduledAt).getTime();
      if (!Number.isFinite(target)) {
        setError('Date/heure invalide.'); return;
      }
      if (target <= Date.now()) {
        setError('Maintenant ou plus tard ? L\'heure programmée est déjà passée. Corrigez l\'heure ou décochez « Programmer ».');
        return;
      }
    }

    setSubmitting(true);
    setError(null);
    // scope.id est résolu côté serveur depuis l'identité JWT (req.playerId
    // → gang_member.gang_id ou cartel_member.cartel_id). Le frontend ne
    // l'envoie pas — cf. OrderWizardService.resolveScope (anti-usurpation).
    const payload: any = {
      scope: { type: state.scope },
      team,
      include_player: includeSelf && state.scope === 'gang',
      weapons,
      armors,
      vehicle_ids: vehicleIds,
      // Phase 15 (20-04-2026) — assignation gangster → véhicule (Option A du design)
      vehicle_assignments: vehicleAssign,
      target: state.target,
    };
    // Phase 15 Iter 6.4 — multi-POI pour 'visit' uniquement (chemin cumulé)
    if (state.key === 'visit' && state.targets && state.targets.length > 0) {
      payload.targets = state.targets.map(t => ({ poi_type: t.poi_type, poi_id: t.poi_id }));
    }
    // Phase 17 Phase 3 (2026-05-04) — Mission Recruter multi-POI (1-5)
    // Backend attend `recruit_target_pois` (champ dédié, pas `targets`).
    if (state.key === 'recruit' && state.targets && state.targets.length > 0) {
      payload.recruit_target_pois = state.targets.map(t => ({
        poi_type: t.poi_type,
        poi_id: t.poi_id,
        label: t.label,
      }));
      // 'recruit' n'utilise pas `target` simple — on retire pour éviter
      // une validation parasite côté backend.
      delete payload.target;
    }
    // Programmation différée (consigne 20-04-2026)
    if (scheduleEnabled && scheduledAt) {
      payload.scheduled_at = new Date(scheduledAt).toISOString();
    }
    // Phase 16 (2026-04-22) — option racket récurrent pour extorsion team
    if (state.key === 'extort' && createRacketZone) {
      payload.create_racket_zone = true;
    }
    try {
      const fn = (api.orderWizard as any)[state.key];
      if (!fn) throw new Error(`Action ${state.key} non implémentée (Commit 3.4)`);
      const r = await fn(payload);
      setResult(r);
    } catch (e: any) {
      setError(e?.message || 'Erreur inconnue');
    } finally {
      setSubmitting(false);
    }
  };

  /** Active le mode map-pick : minimise le modal en bandeau bas, dispatche
   *  l'event à GameMap qui active son interception + animation POI. */
  const startMapPick = useCallback(() => {
    const expects =
      state.key === 'patrol' ? 'location' :
      ['visit', 'buy', 'guard', 'attack', 'develop', 'rob', 'extort', 'recruit'].includes(state.key) ? 'poi' :
      'both';
    setPickMode(true);
    window.dispatchEvent(new CustomEvent('map-pick-start', {
      detail: { expects, orderKey: state.key, scope: state.scope },
    }));
  }, [state.key, state.scope]);

  const cancelMapPick = useCallback(() => {
    setPickMode(false);
    window.dispatchEvent(new CustomEvent('map-pick-cancel'));
  }, []);

  // Phase 15 Iter 6.4 — ajoute le POI actuellement sélectionné (map) dans la chaîne.
  // Phase 17 fix (2026-05-04) — `target.type` côté frontend est l'un de :
  //   business / warehouse / point_de_deal / infrastructure / residence /
  //   hideout / cartel_territory / vehicle / player / npc
  // (cf POILightbox.runAction → setSelectedPOI({type: target.type})).
  // Pour Recruter on accepte les 4 catégories générales ci-dessous, et le
  // backend valide finement le sous-type (business_type ∈ {bar, nightclub,
  // casino, port_ferry, restaurant} + infra_type ∈ {police_station, prison}).
  const RECRUIT_ELIGIBLE_POI_TYPES = [
    'business', 'warehouse', 'point_de_deal', 'infrastructure',
  ];
  const RECRUIT_MAX_POIS = 5;

  const addCurrentPoiToChain = () => {
    if (state.key !== 'visit' && state.key !== 'recruit') return;
    if (!state.target?.poi_id || !state.target?.poi_type) return;

    // Filtrage type pour 'recruit' uniquement (consigne user).
    // Phase 17 fix 2026-05-04 — whitelist élargie aux types POI génériques
    // (business / warehouse / point_de_deal / infrastructure). Le backend
    // RecruitMissionService re-valide le sous-type (business_type +
    // infra_type) et rejette avec un message explicite si non éligible.
    if (state.key === 'recruit') {
      const ptype = String(state.target.poi_type || '').toLowerCase();
      if (!RECRUIT_ELIGIBLE_POI_TYPES.includes(ptype)) {
        setError(`Type POI "${ptype}" non éligible pour Recruter. Choisis un bar, nightclub, casino, entrepôt, point de deal, commissariat ou prison.`);
        return;
      }
    }

    setState(s => {
      const existing = s.targets ?? [];
      const already = existing.some(t => t.poi_id === s.target?.poi_id);
      if (already) return s;
      // Limite max 5 POIs pour 'recruit'
      if (s.key === 'recruit' && existing.length >= RECRUIT_MAX_POIS) {
        setError(`Maximum ${RECRUIT_MAX_POIS} POIs par mission Recruter.`);
        return s;
      }
      return {
        ...s,
        targets: [...existing, {
          poi_type: s.target!.poi_type as string,
          poi_id: s.target!.poi_id as string,
        }],
      };
    });
  };

  const removeTargetFromChain = (idx: number) => {
    setState(s => ({ ...s, targets: (s.targets ?? []).filter((_, i) => i !== idx) }));
  };

  if (!state.open) return null;
  if (typeof document === 'undefined') return null;

  // PICK MODE — bandeau bas, modal minimisé, carte visible
  if (pickMode) {
    const expectsLabel =
      state.key === 'patrol' ? 'un point sur la carte (zone de patrouille)' :
      'un POI (vos cibles s\'allument en vert lorsque sélectionnées)';
    return createPortal(
      <div className="fixed left-4 right-4 bottom-4 z-[1950] pointer-events-auto">
        <div className="mx-auto max-w-[720px] flex items-center gap-3 px-4 py-3 rounded-2xl"
          style={{ background: 'rgba(18,18,24,0.95)', border: '1px solid var(--border-gold)',
            boxShadow: '0 20px 60px rgba(0,0,0,0.7)' }}>
          <div className="shrink-0 text-[11px] font-bold uppercase tracking-[.15em]"
            style={{ color: 'var(--color-gold-light)', fontFamily: 'var(--font-subtitle)' }}>
            {WIZARD_LABELS[state.key] || state.key} · cliquez {expectsLabel}
          </div>
          <span className="flex-1 text-[10px] italic" style={{ color: 'var(--text-secondary)' }}>
            ESC ou bouton Annuler pour revenir au wizard
          </span>
          <button type="button" onClick={cancelMapPick}
            className="new-order is-red" style={{ width: 100, margin: 0, fontSize: 10, padding: 6 }}>
            Annuler
          </button>
        </div>
      </div>,
      document.body,
    );
  }

  // Portal to document.body : sort le modal du stacking context de game-middle
  // (zIndex:1) pour qu'il passe DEVANT OrderBar + HudStack + expand-block-btn.
  return createPortal(
    <div className="fixed inset-0 z-[1950] flex items-center justify-center p-4"
      style={{ background: 'rgba(0,0,0,0.7)' }}
      onClick={close}
    >
      <div className="rounded-2xl overflow-hidden w-full"
        style={{ maxWidth: 560, background: 'var(--bg-panel)', border: '1px solid var(--border-gold)' }}
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex items-center justify-between px-4 py-3"
          style={{ borderBottom: '1px solid var(--border-dark)' }}>
          <p className="text-[13px] font-bold" style={{ color: 'var(--color-gold-light)', letterSpacing: '.15em', fontFamily: 'var(--font-subtitle)' }}>
            {WIZARD_LABELS[state.key] || state.key} · {state.scope?.toUpperCase()} · Étape {step}/3
          </p>
          <button onClick={close} className="w-8 h-8 rounded-lg flex items-center justify-center hover:opacity-80"
            style={{ background: 'rgba(255,255,255,0.04)' }}>
            <X size={14} style={{ color: 'var(--text-secondary)' }} />
          </button>
        </div>

        <div className="p-4" style={{ maxHeight: '70vh', overflowY: 'auto' }}>
          {result && (
            <div className="mb-3 p-2 rounded text-[11px]"
              style={{ background: 'rgba(34,197,94,0.1)', border: '1px solid rgba(34,197,94,0.3)', color: '#22c55e' }}>
              <b>Succès.</b> {JSON.stringify(result).slice(0, 200)}
            </div>
          )}
          {error && (
            <div className="mb-3 p-2 rounded text-[11px]"
              style={{
                background: /impayé/i.test(error) ? 'rgba(239,68,68,0.15)' : 'rgba(239,68,68,0.1)',
                border: `1px solid ${/impayé/i.test(error) ? 'rgba(239,68,68,0.5)' : 'rgba(239,68,68,0.3)'}`,
                color: '#ef4444',
              }}>
              {/impayé/i.test(error) ? (
                <>
                  <p className="font-bold mb-1">⚠ Gangster impayé</p>
                  <p style={{ color: 'var(--text-secondary)', lineHeight: 1.4 }}>{error}</p>
                  <p className="mt-1 text-[10px] italic" style={{ color: 'var(--text-muted)' }}>
                    Renflouez la trésorerie du gang puis payez l'arriéré depuis l'onglet Personnel du tab Gang.
                  </p>
                </>
              ) : error}
            </div>
          )}

          {step === 1 && (
            <Step1Team
              pool={pool}
              team={team}
              includeSelf={includeSelf}
              scope={state.scope}
              imprisoned={isImprisoned}
              onToggle={toggleMember}
              onToggleSelf={() => { if (!isImprisoned) setIncludeSelf(!includeSelf); }}
            />
          )}
          {step === 2 && (
            <Step2Equipment
              team={team}
              includeSelf={includeSelf && state.scope === 'gang'}
              selfId={player?.id}
              selfName={player?.username || 'Vous'}
              pool={pool}
              weapons={weapons} armors={armors}
              vehicleIds={vehicleIds}
              vehicleAssign={vehicleAssign}
              onVehicleAssign={setVehicleAssign}
              onWeapons={setWeapons} onArmors={setArmors}
              onVehicles={setVehicleIds}
            />
          )}
          {step === 3 && (
            <Step3Target
              state={state}
              team={team}
              result={result}
              onAddToChain={addCurrentPoiToChain}
              onRemoveFromChain={removeTargetFromChain}
              onStartMapPick={startMapPick}
              scheduleEnabled={scheduleEnabled}
              onToggleSchedule={setScheduleEnabled}
              scheduledAt={scheduledAt}
              onScheduledAt={setScheduledAt}
              createRacketZone={createRacketZone}
              onToggleCreateRacketZone={setCreateRacketZone}
              vehicleIds={vehicleIds}
              playerLat={player?.current_lat ?? null}
              playerLon={player?.current_lon ?? null}
            />
          )}
        </div>

        <div className="flex items-center justify-between p-3" style={{ borderTop: '1px solid var(--border-dark)' }}>
          <button type="button" className="new-order is-red" style={{ width: 120, margin: 0 }}
            onClick={() => step > 1 ? setStep((step - 1) as 1 | 2 | 3) : close()}>
            {step > 1 ? 'Précédent' : 'Annuler'}
          </button>
          {step < 3 && (
            <button type="button" className="new-order" style={{ width: 140, margin: 0 }}
              onClick={() => setStep((step + 1) as 1 | 2 | 3)}
              disabled={step === 1 && team.length === 0 && !includeSelf}>
              Suivant
            </button>
          )}
          {step === 3 && (
            <button type="button" className="new-order" style={{ width: 160, margin: 0 }}
              onClick={result ? close : submit} disabled={submitting}>
              {submitting ? 'Envoi…' : result ? 'Fermer' : 'Valider l\'ordre'}
            </button>
          )}
        </div>
      </div>
    </div>,
    document.body,
  );
}

// ───────────────────────────────────────────────────────────
// Étape 1 : sélection équipe
// ───────────────────────────────────────────────────────────
function Step1Team({ pool, team, includeSelf, scope, imprisoned, onToggle, onToggleSelf }: {
  pool: any[]; team: string[]; includeSelf: boolean; scope: 'gang' | 'cartel' | null;
  imprisoned?: boolean;
  onToggle: (pid: string) => void; onToggleSelf: () => void;
}) {
  const totalSize = team.length + (includeSelf && scope === 'gang' ? 1 : 0);
  return (
    <div className="space-y-2">
      <p className="text-[11px]" style={{ color: 'var(--text-secondary)' }}>
        Sélectionnez les gangsters (max 5). Les gangsters en mission, en garde, hospitalisés ou impayés sont exclus.
      </p>

      {scope === 'gang' && (
        <label className={`flex items-center gap-2 p-2 rounded ${imprisoned ? 'cursor-not-allowed opacity-50' : 'cursor-pointer'}`}
          style={{ background: 'rgba(212,168,67,0.04)', border: '1px solid var(--border-gold)' }}
          title={imprisoned ? 'Vous êtes emprisonné — l\'ordre est exécuté par votre gang via le bras droit.' : undefined}>
          <input type="checkbox" checked={includeSelf} disabled={imprisoned} onChange={onToggleSelf} />
          <span className="text-[11px]" style={{ color: 'var(--color-gold-light)' }}>
            ⊕ Je participe personnellement à la mission{imprisoned ? ' (impossible — emprisonné)' : ''}
          </span>
        </label>
      )}

      {pool.length === 0 ? (
        <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
          Aucun gangster disponible.
        </p>
      ) : (
        <div className="space-y-1" style={{ maxHeight: 260, overflowY: 'auto' }}>
          {pool.map((m: any) => {
            const pid = m.player_id;
            const selected = team.includes(pid);
            return (
              <button key={pid} type="button" onClick={() => onToggle(pid)}
                className="w-full text-left p-2 rounded flex items-center justify-between"
                style={{
                  background: selected ? 'rgba(212,168,67,0.12)' : 'rgba(255,255,255,0.02)',
                  border: selected ? '1px solid var(--color-gold)' : '1px solid var(--border-dark)',
                }}>
                <span className="text-[11px]" style={{ color: 'var(--text-primary)' }}>
                  {m.player?.username || m.name || pid.slice(0, 8)} · G{m.grade ?? 1}
                </span>
                <span className="text-[9px]" style={{ color: 'var(--text-muted)' }}>
                  HP {m.hit_points ?? 100} · loyauté {m.loyalty ?? 80}
                </span>
              </button>
            );
          })}
        </div>
      )}

      <p className="text-[10px] text-right" style={{ color: totalSize > 5 ? 'var(--color-red)' : 'var(--text-muted)' }}>
        Équipe : {totalSize}/5
      </p>
    </div>
  );
}

// ───────────────────────────────────────────────────────────
// Étape 2 : équipement
// ───────────────────────────────────────────────────────────
function Step2Equipment({
  team, includeSelf, selfId, selfName, pool,
  weapons, armors, vehicleIds, vehicleAssign,
  onWeapons, onArmors, onVehicles, onVehicleAssign,
}: {
  team: string[];
  includeSelf: boolean;
  selfId?: string;
  selfName?: string;
  pool: any[];
  weapons: Record<string, string | null>;
  armors: Record<string, string | null>;
  vehicleIds: string[];
  vehicleAssign: Record<string, string | null>;
  onWeapons: (v: Record<string, string | null>) => void;
  onArmors: (v: Record<string, string | null>) => void;
  onVehicles: (v: string[]) => void;
  onVehicleAssign: (v: Record<string, string | null>) => void;
}) {
  const [myInventory, setMyInventory] = useState<any[]>([]);
  const [myVehicles, setMyVehicles] = useState<any[]>([]);

  useEffect(() => {
    api.allocation.myInventory().then(i => setMyInventory(Array.isArray(i) ? i : [])).catch(() => setMyInventory([]));
    api.allocation.myVehicles().then(v => setMyVehicles(Array.isArray(v) ? v : [])).catch(() => setMyVehicles([]));
  }, []);

  const weaponsList = myInventory.filter(i => i.item_type === 'weapon');
  const armorsList = myInventory.filter(i => i.item_type === 'armor' || i.item_subtype === 'Gilet Pare-Balles');

  // Phase 15 (20-04-2026) — équipe affichée = team + joueur si includeSelf
  // (consigne user : l'étape suivante affiche le joueur dans la liste)
  const fullTeam = includeSelf && selfId ? [selfId, ...team.filter(t => t !== selfId)] : team;
  const nameFor = (pid: string): string => {
    if (pid === selfId) return selfName || 'Vous';
    const m = pool.find((x: any) => x.player_id === pid);
    return m?.player?.username || m?.name || pid.slice(0, 8);
  };

  // Véhicules sélectionnés pour la mission (ceux qu'un gangster au moins occupe)
  const selectedVehicles = myVehicles.filter(v => vehicleIds.includes(v.id));
  // Compute passagers actuels par véhicule (pour afficher places occupées)
  const passengersPerVehicle: Record<string, string[]> = {};
  for (const pid of fullTeam) {
    const vid = vehicleAssign[pid];
    if (vid) {
      if (!passengersPerVehicle[vid]) passengersPerVehicle[vid] = [];
      passengersPerVehicle[vid].push(pid);
    }
  }
  const onFoot = fullTeam.filter(pid => !vehicleAssign[pid]);

  const toggleVehicleSelected = (vid: string) => {
    if (vehicleIds.includes(vid)) {
      // Désélectionner : retire aussi les passagers assignés
      const next = { ...vehicleAssign };
      for (const pid of Object.keys(next)) {
        if (next[pid] === vid) next[pid] = null;
      }
      onVehicleAssign(next);
      onVehicles(vehicleIds.filter(id => id !== vid));
    } else {
      onVehicles([...vehicleIds, vid]);
    }
  };

  const assignGangsterToVehicle = (pid: string, vid: string | null) => {
    // Valider capacité avant d'assigner
    if (vid) {
      const v = myVehicles.find(x => x.id === vid);
      const currentCount = (passengersPerVehicle[vid] || []).length;
      const alreadyInThis = vehicleAssign[pid] === vid;
      if (v && !alreadyInThis && currentCount >= (v.seats || 4)) {
        alert(`Véhicule complet (${v.seats} places).`);
        return;
      }
    }
    onVehicleAssign({ ...vehicleAssign, [pid]: vid });
  };

  return (
    <div className="space-y-3">
      <p className="text-[11px]" style={{ color: 'var(--text-secondary)' }}>
        1 arme et 1 gilet max par gangster. Assignation véhicule optionnelle : les gangsters sans véhicule suivent à pied. Le pilote est automatiquement le meilleur conducteur par véhicule.
      </p>

      {/* Weapons */}
      <div>
        <p className="text-[10px] font-bold mb-1" style={{ color: 'var(--color-gold-light)', letterSpacing: '.15em', fontFamily: 'var(--font-subtitle)' }}>
          ARMES
        </p>
        <div className="space-y-1">
          {fullTeam.map(pid => (
            <div key={pid} className="flex items-center gap-2 text-[10px]">
              <span className="truncate" style={{ flex: 1, color: pid === selfId ? 'var(--color-gold-light)' : 'var(--text-secondary)' }}>
                {pid === selfId ? '★ ' : ''}{nameFor(pid)}
              </span>
              <select value={weapons[pid] || ''}
                onChange={(e) => onWeapons({ ...weapons, [pid]: e.target.value || null })}
                className="px-2 py-1 rounded text-[10px]"
                style={{ background: 'var(--bg-tertiary)', border: '1px solid var(--border-dark)', color: 'var(--text-primary)' }}>
                <option value="">— Mains nues —</option>
                {weaponsList.map((w, i) => (
                  <option key={i} value={w.item_subtype}>{w.item_subtype}</option>
                ))}
              </select>
            </div>
          ))}
        </div>
      </div>

      {/* Armors */}
      <div>
        <p className="text-[10px] font-bold mb-1" style={{ color: 'var(--color-gold-light)', letterSpacing: '.15em', fontFamily: 'var(--font-subtitle)' }}>
          GILETS PARE-BALLES
        </p>
        <div className="space-y-1">
          {fullTeam.map(pid => (
            <div key={pid} className="flex items-center gap-2 text-[10px]">
              <span className="truncate" style={{ flex: 1, color: pid === selfId ? 'var(--color-gold-light)' : 'var(--text-secondary)' }}>
                {pid === selfId ? '★ ' : ''}{nameFor(pid)}
              </span>
              <select value={armors[pid] || ''}
                onChange={(e) => onArmors({ ...armors, [pid]: e.target.value || null })}
                className="px-2 py-1 rounded text-[10px]"
                style={{ background: 'var(--bg-tertiary)', border: '1px solid var(--border-dark)', color: 'var(--text-primary)' }}>
                <option value="">— Aucun —</option>
                {armorsList.map((a, i) => (
                  <option key={i} value={a.item_subtype}>{a.item_subtype}</option>
                ))}
              </select>
            </div>
          ))}
        </div>
      </div>

      {/* Vehicles — Phase 15 (20-04-2026) : sélection + assignation par gangster */}
      <div>
        <p className="text-[10px] font-bold mb-1" style={{ color: 'var(--color-gold-light)', letterSpacing: '.15em', fontFamily: 'var(--font-subtitle)' }}>
          VÉHICULES ({vehicleIds.length} sélectionné{vehicleIds.length > 1 ? 's' : ''})
        </p>

        {/* Sélection des véhicules à embarquer pour la mission */}
        <div className="space-y-1 mb-2" style={{ maxHeight: 120, overflowY: 'auto' }}>
          {myVehicles.length === 0 ? (
            <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>Aucun véhicule disponible</p>
          ) : myVehicles.map((v: any) => {
            const selected = vehicleIds.includes(v.id);
            const passengers = passengersPerVehicle[v.id] || [];
            return (
              <button key={v.id} type="button"
                onClick={() => toggleVehicleSelected(v.id)}
                className="w-full text-left p-2 rounded flex items-center justify-between text-[10px]"
                style={{
                  background: selected ? 'rgba(212,168,67,0.12)' : 'rgba(255,255,255,0.02)',
                  border: selected ? '1px solid var(--color-gold)' : '1px solid var(--border-dark)',
                }}>
                <span style={{ color: 'var(--text-primary)' }}>
                  {v.name || v.type}
                  {selected && (
                    <span className="ml-2 text-[9px]" style={{ color: 'var(--text-muted)' }}>
                      {passengers.length}/{v.seats || 4} places
                    </span>
                  )}
                </span>
                <span style={{ color: 'var(--text-muted)' }}>{v.speed ?? 50} km/h · {v.seats || 4} places</span>
              </button>
            );
          })}
        </div>

        {/* Assignation gangster → véhicule (dispo seulement si véhicules sélectionnés) */}
        {selectedVehicles.length > 0 && (
          <div className="space-y-1 p-2 rounded" style={{ background: 'rgba(255,255,255,0.02)', border: '1px dashed rgba(212,168,67,0.25)' }}>
            <p className="text-[9px] font-bold" style={{ color: 'var(--color-gold-light)', letterSpacing: '.1em' }}>
              ASSIGNATION GANGSTER → VÉHICULE
            </p>
            {fullTeam.map(pid => (
              <div key={pid} className="flex items-center gap-2 text-[10px]">
                <span className="truncate" style={{ flex: 1, color: pid === selfId ? 'var(--color-gold-light)' : 'var(--text-secondary)' }}>
                  {pid === selfId ? '★ ' : ''}{nameFor(pid)}
                </span>
                <select value={vehicleAssign[pid] || ''}
                  onChange={(e) => assignGangsterToVehicle(pid, e.target.value || null)}
                  className="px-2 py-1 rounded text-[10px]"
                  style={{ background: 'var(--bg-tertiary)', border: '1px solid var(--border-dark)', color: 'var(--text-primary)' }}>
                  <option value="">🚶 À pied</option>
                  {selectedVehicles.map((v: any) => {
                    const passengers = passengersPerVehicle[v.id] || [];
                    const alreadyIn = vehicleAssign[pid] === v.id;
                    const full = !alreadyIn && passengers.length >= (v.seats || 4);
                    return (
                      <option key={v.id} value={v.id} disabled={full}>
                        🚗 {v.name || v.type} ({passengers.length}/{v.seats || 4}){full ? ' — complet' : ''}
                      </option>
                    );
                  })}
                </select>
              </div>
            ))}
            {onFoot.length > 0 && (
              <p className="text-[9px] italic mt-1" style={{ color: 'var(--text-muted)' }}>
                {onFoot.length} gangster{onFoot.length > 1 ? 's' : ''} à pied — trajet plus long, arrivée en décalé.
              </p>
            )}
          </div>
        )}
      </div>
    </div>
  );
}

// ───────────────────────────────────────────────────────────
// Étape 3 : cible + programmation différée
// ───────────────────────────────────────────────────────────
function Step3Target({
  state, team, result, onAddToChain, onRemoveFromChain, onStartMapPick,
  scheduleEnabled, onToggleSchedule, scheduledAt, onScheduledAt,
  createRacketZone, onToggleCreateRacketZone,
  vehicleIds, playerLat, playerLon,
}: {
  state: WizardState;
  team: string[];
  result: any;
  onAddToChain?: () => void;
  onRemoveFromChain?: (idx: number) => void;
  onStartMapPick?: () => void;
  scheduleEnabled?: boolean;
  onToggleSchedule?: (v: boolean) => void;
  scheduledAt?: string;
  onScheduledAt?: (v: string) => void;
  createRacketZone?: boolean;
  onToggleCreateRacketZone?: (v: boolean) => void;
  vehicleIds?: string[];
  playerLat?: number | null;
  playerLon?: number | null;
}) {
  const needsPoi = ['visit', 'buy', 'guard', 'attack', 'develop', 'rob', 'extort'].includes(state.key);
  const needsCoords = state.key === 'patrol';
  // Phase 17 Phase 3 (2026-05-04) — 'recruit' utilise aussi le mode multi-POI
  // (1-5 POIs, pas de cible "principale") au lieu de chain visite.
  const isMultiVisit = state.key === 'visit';
  const isMultiRecruit = state.key === 'recruit';
  const isMultiPoi = isMultiVisit || isMultiRecruit;
  const chain = state.targets ?? [];
  return (
    <div className="space-y-2 text-[11px]" style={{ color: 'var(--text-secondary)' }}>
      <p>
        <b style={{ color: 'var(--color-gold-light)' }}>{WIZARD_LABELS[state.key]}</b> avec {team.length} gangster(s).
      </p>
      {state.target?.poi_id && (
        <p>Cible : POI <code>{state.target.poi_type} / {state.target.poi_id.slice(0, 8)}…</code></p>
      )}
      {state.target?.lat && state.target?.lng && !state.target?.poi_id && (
        <p>Zone patrouille : <code>{state.target.lat.toFixed(4)}, {state.target.lng.toFixed(4)}</code></p>
      )}
      {/* Phase 15 Iter 6.4 — chemin cumulé (visit only) */}
      {isMultiPoi && chain.length > 0 && (
        <div className="p-2 rounded" style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid var(--border-dark)' }}>
          <p style={{ color: 'var(--color-gold-light)' }}>
            <b>{isMultiRecruit ? `Lieux à visiter (${chain.length}/5) :` : `Chaîne de visite (${chain.length}) :`}</b>
          </p>
          <ol className="text-[10px] mt-1 space-y-0.5" style={{ listStyle: 'decimal inside', color: 'var(--text-primary)' }}>
            {chain.map((t, i) => (
              <li key={`${t.poi_id}-${i}`} className="flex items-center justify-between">
                <span><code>{t.poi_type}</code> / {t.poi_id.slice(0, 8)}…</span>
                <button type="button" onClick={() => onRemoveFromChain?.(i)}
                  className="text-[9px]" style={{ color: 'var(--color-red-light)' }}>✕</button>
              </li>
            ))}
          </ol>
          <p className="text-[9px] mt-1 italic" style={{ color: 'var(--text-muted)' }}>
            {isMultiRecruit
              ? `L'équipe parcourt chaque lieu (20 min sur place) puis rentre. Au retour : 1-3 candidats si 1 lieu, 0-3/lieu (min 1 total) si plusieurs. Risque bagarre 5 %/lieu, +1 chaleur/lieu.`
              : `L'équipe visitera chaque POI dans l'ordre. Si majorité hospitalisée en route, les POIs restants sont skippés.`}
          </p>
        </div>
      )}
      {isMultiPoi && state.target?.poi_id && (
        <button type="button" onClick={onAddToChain}
          className="new-order" style={{ width: '100%', margin: 0, fontSize: 10, padding: 4 }}>
          + Ajouter ce POI à la chaîne ({chain.length + 1}{chain.length === 0 ? 'er' : 'ème'})
        </button>
      )}
      {/* Mission Recruter — message d'aide types POI */}
      {isMultiRecruit && chain.length === 0 && (
        <p className="text-[10px] italic" style={{ color: 'var(--text-muted)' }}>
          Sélectionne 1 à 5 POIs parmi : bars, nightclubs, casinos, entrepôts, points de deal, docks, ports, commissariats, prisons.
        </p>
      )}
      {/* Phase 15 (20-04-2026) — bouton map-pick intégré : plus de message
          d'erreur renvoyant faire un détour par la fiche POI. Cliquer active
          le mode sélection carte, le modal se minimise en bandeau bas. */}
      {(needsPoi || isMultiRecruit) && !state.target?.poi_id && chain.length === 0 && (
        <button type="button" onClick={onStartMapPick}
          className="new-order w-full" style={{ margin: 0, padding: 10 }}>
          🎯 Sélectionner {isMultiRecruit ? 'un lieu' : 'la cible'} sur la carte
        </button>
      )}
      {needsCoords && (!state.target?.lat || !state.target?.lng) && (
        <button type="button" onClick={onStartMapPick}
          className="new-order w-full" style={{ margin: 0, padding: 10 }}>
          🎯 Définir la zone de patrouille sur la carte
        </button>
      )}
      {/* Bouton « changer la cible » si déjà sélectionnée */}
      {(state.target?.poi_id || (state.target?.lat && state.target?.lng)) && (
        <button type="button" onClick={onStartMapPick}
          className="text-[10px] underline"
          style={{ color: 'var(--text-muted)', background: 'transparent', border: 'none', padding: 0 }}>
          Changer la cible
        </button>
      )}
      <p className="text-[10px] italic" style={{ color: 'var(--text-muted)' }}>
        La durée de mission est calculée automatiquement (trajet + action + retour). −1 % par gangster supplémentaire. Le véhicule réduit le trajet.
      </p>

      {/* Phase 8.9 (2026-04-29) — Estimation carburant (afficher quand cible
          ET au moins un véhicule définis). Per-vehicle, multiplier mentalement
          par N véhicules. */}
      {(state.target?.lat || state.target?.poi_id) && (vehicleIds?.length ?? 0) > 0
        && playerLat != null && playerLon != null && state.target?.lat && state.target?.lng && (
        <FuelEstimateRow
          fromLat={playerLat}
          fromLon={playerLon}
          toLat={state.target.lat}
          toLon={state.target.lng}
          vehicleId={vehicleIds?.[0]}
          vehicleCount={vehicleIds?.length ?? 0}
        />
      )}

      {/* Phase 15 (20-04-2026) — programmation différée (scheduling) */}
      <div className="mt-2 p-2 rounded" style={{ background: 'rgba(255,255,255,0.02)', border: '1px solid var(--border-dark)' }}>
        <label className="flex items-center gap-2 text-[10px] cursor-pointer" style={{ color: 'var(--text-primary)' }}>
          <input type="checkbox" checked={!!scheduleEnabled}
            onChange={(e) => onToggleSchedule?.(e.target.checked)} />
          <span>Programmer l'ordre à un horaire précis</span>
        </label>
        {scheduleEnabled && (
          <input type="datetime-local" value={scheduledAt || ''}
            onChange={(e) => onScheduledAt?.(e.target.value)}
            className="mt-2 w-full px-2 py-1 rounded text-[11px]"
            style={{ background: 'var(--bg-tertiary)', border: '1px solid var(--border-dark)', color: 'var(--text-primary)' }} />
        )}
        {scheduleEnabled && (
          <p className="mt-1 text-[9px] italic" style={{ color: 'var(--text-muted)' }}>
            L'équipe reste libre tant que l'heure n'est pas atteinte. Une heure passée sera rejetée (corrigez ou décochez).
          </p>
        )}
      </div>

      {/* Phase 16 (2026-04-22) — unification racket : option RacketZone récurrente */}
      {state.key === 'extort' && (
        <div className="mt-2 p-2 rounded" style={{ background: 'rgba(255,255,255,0.02)', border: '1px solid var(--border-dark)' }}>
          <label className="flex items-center gap-2 text-[10px] cursor-pointer" style={{ color: 'var(--text-primary)' }}>
            <input type="checkbox" checked={!!createRacketZone}
              onChange={(e) => onToggleCreateRacketZone?.(e.target.checked)} />
            <span>Installer une zone de racket récurrente sur le commerce (si victoire)</span>
          </label>
          <p className="mt-1 text-[9px] italic" style={{ color: 'var(--text-muted)' }}>
            Après combat gagné, le commerce est ajouté à votre zone (ou une zone est créée).
            Les gangsters assignés à la zone défendront le commerce contre vos rivaux et
            un revenu passif tombe à chaque cycle (24h).
          </p>
        </div>
      )}
      {result && (
        <div className="mt-2 p-2 rounded text-[10px]"
          style={{
            background: result.refused ? 'rgba(212,168,67,0.08)'
              : result.mode === 'cordial' ? 'rgba(96,165,250,0.08)'
              : 'rgba(34,197,94,0.08)',
            border: result.refused ? '1px solid rgba(212,168,67,0.35)'
              : result.mode === 'cordial' ? '1px solid rgba(96,165,250,0.35)'
              : '1px solid rgba(34,197,94,0.3)',
          }}>
          {/* Phase 15 Iter 7 — visite alliée refusée */}
          {result.refused && (
            <p style={{ color: 'var(--color-gold-light)' }}>
              <b>⚠ {result.message || 'Visite refusée.'}</b>
            </p>
          )}
          {/* Phase 15 Iter 7 — visite cordiale (info sans combat) */}
          {!result.refused && result.mode === 'cordial' && (
            <>
              <p style={{ color: '#93c5fd' }}>
                <b>🕊 {result.message || 'Visite cordiale : informations obtenues.'}</b>
              </p>
              {result.reveal && (
                <p className="mt-1" style={{ color: 'var(--text-secondary)' }}>
                  Informations révélées sur ce POI (voir fiche carte).
                </p>
              )}
            </>
          )}
          {/* Phase 15 Iter 7 — tenancier illégal qui a cédé sans se battre */}
          {!result.refused && result.mode === 'resistance' && !result.combat && (
            <p style={{ color: '#93c5fd' }}>
              <b>🕊 {result.message || 'Le tenancier a préféré parler.'}</b>
            </p>
          )}
          {result.multi ? (
            <>
              <p style={{ color: 'var(--color-gold-light)' }}>
                <b>Chemin multi-POI : {result.total_steps} étape(s), {result.total_xp_per_member} XP total/membre</b>
              </p>
              <ul className="mt-1 space-y-0.5">
                {result.steps?.map((s: any, i: number) => (
                  <li key={i} style={{ color: s.skipped ? 'var(--text-muted)' : 'var(--text-primary)' }}>
                    {i + 1}. <code>{s.poi_type}</code> {s.poi_id?.slice(0, 8)}… —{' '}
                    {s.skipped
                      ? (
                        s.reason === 'cooldown_active' && s.next_visit_at
                          ? <span style={{ color: 'var(--color-gold-light)' }}>
                              ⏳ Cooldown 24h — prochaine visite {new Date(s.next_visit_at).toLocaleString('fr-FR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' })}
                            </span>
                          : <span style={{ color: 'var(--text-muted)' }}>⏸ skippé ({s.reason})</span>
                      )
                      : s.refused
                        ? <span style={{ color: 'var(--color-gold-light)' }}>⚠ allié (refusé)</span>
                        : s.mode === 'cordial'
                          ? <span style={{ color: '#93c5fd' }}>🕊 cordial</span>
                          : s.mode === 'resistance' && !s.combat
                            ? <span style={{ color: '#93c5fd' }}>🕊 parole</span>
                            : s.combat?.victory
                              ? <span style={{ color: '#22c55e' }}>✓ reveal</span>
                              : <span style={{ color: '#ef4444' }}>✕ défaite</span>}
                  </li>
                ))}
              </ul>
            </>
          ) : result.combat ? (
            <>
              <p style={{ color: result.combat.victory ? '#22c55e' : '#ef4444' }}>
                <b>{result.combat.victory ? '✓ Victoire' : '✕ Défaite'}</b>
                {' · '}Attaque {result.combat.attack_score} vs Défense {result.combat.defense_score} (ratio {result.combat.ratio?.toFixed(2)})
              </p>
              {result.combat.attacker_casualties?.length > 0 && (
                <p style={{ color: 'var(--text-secondary)' }}>
                  Vos victimes : {result.combat.attacker_casualties.length} hospitalisé(s) 24h
                </p>
              )}
              {result.combat.defender_casualties?.length > 0 && (
                <p style={{ color: 'var(--text-secondary)' }}>
                  Ennemis neutralisés : {result.combat.defender_casualties.length}
                </p>
              )}
              {result.loot?.shadow > 0 && (
                <p style={{ color: 'var(--color-gold-light)' }}>
                  Butin : {result.loot.shadow.toLocaleString('fr-FR')} ∞ ombre
                </p>
              )}
              {/* Phase 15 (20-04-2026) — takeover auto sur cartel_territory */}
              {result.takeover && !result.takeover.error && (
                <div className="mt-2 p-2 rounded"
                  style={{ background: 'rgba(212,168,67,0.12)', border: '1px solid var(--border-gold)' }}>
                  <p className="font-bold" style={{ color: 'var(--color-gold-light)' }}>
                    🏴 Cartel pris en contrôle ({result.takeover.case === 'B' ? 'vous êtes le nouvel administrateur' : 'possessions transférées à votre cartel'})
                  </p>
                  {result.takeover.summary && (
                    <p className="mt-1 text-[9px]" style={{ color: 'var(--text-secondary)' }}>
                      {typeof result.takeover.summary === 'string'
                        ? result.takeover.summary
                        : JSON.stringify(result.takeover.summary).slice(0, 160)}
                    </p>
                  )}
                </div>
              )}
              {result.takeover?.error && (
                <p className="text-[10px] mt-1" style={{ color: 'var(--color-red-light)' }}>
                  ⚠ Takeover automatique échoué : {result.takeover.error}
                </p>
              )}
              {result.tribute > 0 && (
                <p style={{ color: 'var(--color-gold-light)' }}>
                  Tribut : {result.tribute.toLocaleString('fr-FR')} ∞ ombre
                </p>
              )}
            </>
          ) : result.journeys ? (
            <p style={{ color: 'var(--text-primary)' }}>
              ✓ {result.journeys.filter((j: any) => !j.error).length} ordre(s) assigné(s).
            </p>
          ) : result.assigned ? (
            <p style={{ color: 'var(--text-primary)' }}>
              ✓ {result.assigned.length}/{result.total_requested} garde(s) en poste.
            </p>
          ) : (
            <p style={{ color: 'var(--text-primary)' }}>✓ Ordre validé.</p>
          )}
        </div>
      )}
    </div>
  );
}

/**
 * Phase 8.9 (2026-04-29) — Affiche le coût carburant estimé pour le trajet
 * (origine → cible) avec le véhicule sélectionné. Mis à jour quand les
 * coordonnées ou le véhicule changent (avec debounce 400ms).
 *
 * Affiche le coût UNITAIRE (1 véhicule). Si plusieurs véhicules dans le
 * convoy, le total mental = N × coût (le wizard ne supporte pas vehicule
 * différent par gangster pour l'instant).
 */
function FuelEstimateRow({
  fromLat, fromLon, toLat, toLon, vehicleId, vehicleCount,
}: {
  fromLat: number;
  fromLon: number;
  toLat: number;
  toLon: number;
  vehicleId?: string;
  vehicleCount: number;
}) {
  const [estimate, setEstimate] = useState<{
    cost: number;
    distance_km: number;
    avg_speed_kmh: number;
  } | null>(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    if (!vehicleId) return;
    setLoading(true);
    const timer = setTimeout(() => {
      api.fuel.estimate({
        from_lat: fromLat, from_lon: fromLon,
        to_lat: toLat, to_lon: toLon,
        vehicle_id: vehicleId,
      }).then((res) => setEstimate({
        cost: res.cost,
        distance_km: res.routed_distance_km,
        avg_speed_kmh: res.avg_speed_kmh,
      })).catch(() => setEstimate(null))
        .finally(() => setLoading(false));
    }, 400);
    return () => clearTimeout(timer);
  }, [fromLat, fromLon, toLat, toLon, vehicleId]);

  if (!vehicleId || (!estimate && !loading)) return null;

  const totalCost = estimate ? estimate.cost * vehicleCount : 0;

  return (
    <div
      className="mt-2 p-2 rounded text-[10px] flex items-center justify-between gap-2"
      style={{
        background: 'rgba(212,168,67,0.06)',
        border: '1px solid rgba(212,168,67,0.25)',
        color: 'var(--text-secondary)',
      }}
    >
      <span>⛽ Carburant estimé{vehicleCount > 1 ? ` (×${vehicleCount} véhicules)` : ''} :</span>
      <span style={{ color: 'var(--color-gold-light)', fontWeight: 'bold' }}>
        {loading ? '…' : estimate
          ? `${totalCost} ∞ Light · ${estimate.distance_km.toFixed(1)}km à ${Math.round(estimate.avg_speed_kmh)}km/h`
          : '—'}
      </span>
    </div>
  );
}
