'use client';

import { useEffect, useMemo, useState, useCallback } from 'react';
import { createPortal } from 'react-dom';
import { X, Building2, ShieldAlert, Package, Scale, AlertTriangle, ShoppingBag, Lock, Flame, Power, PowerOff } from 'lucide-react';
import { api, apiFetch } from '@/lib/api';
import { useGameStore } from '@/stores/gameStore';
import { useMapStore } from '@/stores/mapStore';
import { StorageTransferModal } from '../ui/StorageTransferModal';
import { Users, Eye, Swords } from 'lucide-react';
import { PrisonPoiPanel } from './PrisonPoiPanel';
// Phase 8 v3 (2026-05-02) — Toggle "Tout le monde à sa part" (10% revenu
// racket reversé au commissariat local pour inhiber heat). S'affiche si
// business est dans une zone racket du joueur connecté.
import { RacketBribePoliceToggle } from './RacketBribePoliceToggle';

/**
 * audit 15-04-2026 feedback utilisateur : catalogue d'armes chez l'armurier.
 * Retourne par le backend dans linked.weapon_catalog quand business_type='armurerie'.
 * Le backend filtre deja pour n'inclure que les armes legales (is_legal=true + price > 0).
 */
interface WeaponCatalogEntry {
  name: string;
  price: number;
  attack_bonus: number;
  defense_bonus: number;
  range: number;
  concealability: number;
  noise_level: number;
  is_legal: boolean;
}

export function POILightbox(props: { open: boolean; poiId: string | null; onClose: () => void }) {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [data, setData] = useState<any | null>(null);
  const [executing, setExecuting] = useState<string | null>(null);
  const [actionMsg, setActionMsg] = useState<string | null>(null);
  const [showStorageModal, setShowStorageModal] = useState(false);

  const playerId = useGameStore((s) => s.player?.id);
  const setSelectedPOI = useMapStore((s) => s.setSelectedPOI);
  const [guards, setGuards] = useState<any[]>([]);

  useEffect(() => {
    if (!props.open || !props.poiId) return;
    setLoading(true);
    setError(null);
    setActionMsg(null);
    setData(null);
    api.mapAction.getPoiDetails(props.poiId)
      .then((res: any) => {
        setData(res);
        // Phase 15 Commit 4 — enregistre le POI sélectionné pour OrderBar/Wizard
        if (res?.target?.type && res?.target?.id) {
          setSelectedPOI({ type: res.target.type, id: res.target.id });
          // Fetch guards si POI gardable
          const guardableTypes = ['business', 'residence', 'warehouse', 'hideout', 'cartel_territory'];
          if (guardableTypes.includes(res.target.type)) {
            api.orderWizard.listPoiGuards(res.target.type, res.target.id)
              .then(g => setGuards(Array.isArray(g) ? g : []))
              .catch(() => setGuards([]));
          }
        }
      })
      .catch((e: any) => setError(e?.message || 'Erreur'))
      .finally(() => setLoading(false));
    return () => {
      // Ne vide pas selectedPOI à la fermeture — l'ordre peut être lancé APRÈS
      // fermeture de la lightbox, on garde le contexte.
    };
  }, [props.open, props.poiId, setSelectedPOI]);

  const poi = data?.poi;
  const linked = data?.linked;
  const ownerName = data?.owner_name;
  const actions = Array.isArray(data?.actions) ? data.actions : [];
  const target = data?.target;
  // Phase 15 Iter 7.1 (19-04-2026) — snapshot de la dernière visite pour ce joueur
  const lastReveal = (data as any)?.last_reveal;

  // Phase 15 Commit 4 — quick actions équipe (dispatch wizard)
  const openWizard = (key: string, scope: 'gang' | 'cartel' = 'gang') => {
    if (!target?.type || !target?.id) return;
    window.dispatchEvent(new CustomEvent('order-wizard-open', {
      detail: { scope, key, target: { poi_type: target.type, poi_id: target.id } },
    }));
    props.onClose();
  };

  const releaseGuard = async (guardId: string) => {
    try {
      await api.orderWizard.releaseGuard(guardId);
      setGuards(g => g.filter(x => x.id !== guardId));
    } catch { /* silent */ }
  };

  const isOwner = !!(ownerName && playerId && ((data as any)?.owner_id === playerId || (linked as any)?.player_id === playerId));
  const isGuardableType = !!(target?.type && ['business', 'residence', 'warehouse', 'hideout', 'cartel_territory'].includes(target.type));
  const isForSale = !!(linked?.is_for_sale);

  const title = useMemo(() => {
    if (linked?.name) return linked.name;
    if (poi?.name) return poi.name;
    return 'Point d’intérêt';
  }, [linked?.name, poi?.name]);

  const subtitle = useMemo(() => {
    const parts: string[] = [];
    if (poi?.type) parts.push(String(poi.type));
    if (poi?.icon) parts.push(String(poi.icon));
    return parts.join(' • ');
  }, [poi?.type, poi?.icon]);

  const runAction = async (action: any) => {
    if (!target?.type || !target?.id) return;
    if (executing) return;
    setExecuting(action.code);
    setError(null);
    setActionMsg(null);
    try {
      const res: any = await api.mapAction.executeAction({
        action_code: action.code,
        target_type: target.type,
        target_id: target.id,
      });
      if (res?.message) setActionMsg(String(res.message));
      // Phase 17 Phase 6 (2026-05-04) — Recrutement spécialistes :
      // si le backend renvoie data.open_modal='recruit_specialist' avec
      // un role, on dispatche un event pour que SpecialistRecruitLightbox
      // s'ouvre. Permet le slider tarif négociable côté UI sans surcharger
      // le POILightbox.
      if (res?.data?.open_modal === 'recruit_specialist' && res.data.role) {
        window.dispatchEvent(new CustomEvent('specialist-recruit-open', {
          detail: { role: res.data.role, poi_id: target.id, poi_type: target.type },
        }));
      }
      // Re-fetch POI details to refresh available actions after execution
      if (props.poiId) {
        try {
          const refreshed = await api.mapAction.getPoiDetails(props.poiId);
          setData(refreshed as any);
        } catch { /* ignore refresh errors */ }
      }
    } catch (e: any) {
      setError(e?.message || 'Erreur');
    } finally {
      setExecuting(null);
    }
  };

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

  return createPortal(
    <div className="fixed inset-0 z-[2000] pointer-events-none flex items-center justify-center">
      <div className="absolute inset-0 pointer-events-auto" style={{ background: 'rgba(0,0,0,0.55)' }} onClick={props.onClose} />
      <div
        className="relative pointer-events-auto w-[92vw] max-w-[560px] max-h-[84vh] rounded-2xl overflow-hidden flex flex-col"
        style={{ background: 'var(--bg-panel)', border: '1px solid var(--border-dark)', boxShadow: '0 20px 80px rgba(0,0,0,0.35)' }}
        onClick={(e) => e.stopPropagation()}
      >
        <div className="flex items-center justify-between px-4 py-3" style={{ borderBottom: '1px solid var(--border-dark)' }}>
          <div className="min-w-0">
            <p className="text-sm font-bold truncate" style={{ color: 'var(--text-primary)' }}>{title}</p>
            <p className="text-[10px] truncate" style={{ color: 'var(--text-muted)' }}>{subtitle}</p>
          </div>
          <button onClick={props.onClose} className="w-8 h-8 rounded-lg flex items-center justify-center hover:opacity-80" style={{ background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.06)' }}>
            <X size={16} style={{ color: 'var(--text-secondary)' }} />
          </button>
        </div>

        <div className="flex-1 overflow-y-auto p-4 space-y-3">
          {loading ? (
            <p className="text-xs" style={{ color: 'var(--text-muted)' }}>Chargement…</p>
          ) : error ? (
            <div className="p-3 rounded-xl" style={{ background: 'rgba(239,68,68,0.10)', border: '1px solid rgba(239,68,68,0.25)' }}>
              <p className="text-xs" style={{ color: 'rgba(239,68,68,0.95)' }}>{error}</p>
            </div>
          ) : poi?.icon === 'prison' && props.poiId ? (
            /* Phase 8 Session 2C (2026-04-27) — POI prison : panel dédié
               (stats publiques + tabs proches incarcérés + parloir + avocat).
               Skip le rendu standard business/résidence/etc. */
            <PrisonPoiPanel poiId={props.poiId} />
          ) : (
            <>
              <div className="p-3 rounded-xl space-y-2" style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)' }}>
                <div className="flex items-center justify-between">
                  <div className="flex items-center gap-2">
                    <Building2 size={16} style={{ color: 'var(--color-gold)' }} />
                    <p className="text-xs font-bold" style={{ color: 'var(--text-primary)' }}>Informations</p>
                  </div>
                  {/* audit 15-04-2026 Phase 12.c : badge legal / illegal */}
                  {linked?.is_legal != null && (
                    <div
                      className="flex items-center gap-1 px-2 py-0.5 rounded"
                      style={{
                        background: linked.is_legal ? 'rgba(34,197,94,0.15)' : 'rgba(239,68,68,0.15)',
                        border: `1px solid ${linked.is_legal ? 'rgba(34,197,94,0.35)' : 'rgba(239,68,68,0.35)'}`,
                      }}
                    >
                      {linked.is_legal
                        ? <Scale size={10} style={{ color: '#22c55e' }} />
                        : <AlertTriangle size={10} style={{ color: '#ef4444' }} />}
                      <span
                        className="text-[9px] font-bold uppercase tracking-wide"
                        style={{ color: linked.is_legal ? '#22c55e' : '#ef4444' }}
                      >
                        {linked.is_legal ? 'Légal' : 'Illégal'}
                      </span>
                    </div>
                  )}
                </div>
                {ownerName && (
                  <p className="text-[11px]" style={{ color: 'var(--text-secondary)' }}>
                    Propriétaire : <span style={{ color: 'var(--text-primary)' }}>{ownerName}</span>
                  </p>
                )}
                {linked?.employee_count != null && (
                  <p className="text-[11px]" style={{ color: 'var(--text-secondary)' }}>
                    Employés : <span style={{ color: 'var(--text-primary)' }}>{linked.employee_count}</span>
                  </p>
                )}
                {linked?.revenue_per_day != null && (
                  <p className="text-[11px]" style={{ color: 'var(--text-secondary)' }}>
                    Bénéfice : <span style={{ color: 'var(--text-primary)' }}>{linked.revenue_per_day}∞/jour</span>
                  </p>
                )}
                {linked?.purchase_price != null && (
                  <p className="text-[11px]" style={{ color: 'var(--text-secondary)' }}>
                    Prix : <span style={{ color: 'var(--text-primary)' }}>{linked.purchase_price}∞</span>
                  </p>
                )}
                {/* Warehouse specific fields */}
                {linked?.type === 'warehouse' && (
                  <>
                    {linked?.warehouse_type && (
                      <p className="text-[11px]" style={{ color: 'var(--text-secondary)' }}>
                        Type : <span style={{ color: 'var(--text-primary)' }}>{linked.warehouse_type}</span>
                      </p>
                    )}
                    {linked?.capacity != null && (
                      <p className="text-[11px]" style={{ color: 'var(--text-secondary)' }}>
                        Capacité : <span style={{ color: 'var(--text-primary)' }}>{linked.capacity} kg</span>
                      </p>
                    )}
                  </>
                )}
                {linked?.contested_until && (
                  <div className="flex items-center gap-2 mt-1">
                    <ShieldAlert size={14} style={{ color: '#f97316' }} />
                    <p className="text-[10px]" style={{ color: 'rgba(249,115,22,0.95)' }}>Contesté</p>
                  </div>
                )}
                {/* Phase 8 v3 (2026-05-02) — "Tout le monde à sa part" :
                    si ce business est dans une zone racket du joueur, propose
                    le toggle 10% au commissariat (inhibition heat racket).
                    Auto-hidden si business pas dans une zone du joueur. */}
                {target?.type === 'business' && target?.id && (
                  <RacketBribePoliceToggle businessId={target.id} />
                )}
                {/* Phase 15 Iter 6.5 (19-04-2026) — Panel ACTIVITÉ pour les commerces */}
                {target?.type === 'business' && linked?.is_owned_by_me && (
                  <div className="mt-2 pt-2" style={{ borderTop: '1px dashed rgba(255,255,255,0.1)' }}>
                    <p className="text-[9px] font-bold mb-1.5" style={{ color: 'var(--color-gold-light)', letterSpacing: '.15em', fontFamily: 'var(--font-subtitle)' }}>
                      ACTIVITÉ {linked.is_legal === false ? '— illégale' : ''}
                    </p>
                    <div className="grid grid-cols-2 gap-x-3 gap-y-0.5 text-[10px]" style={{ color: 'var(--text-secondary)' }}>
                      {linked.storage_capacity_kg > 0 && (
                        <p>Stocks : <span style={{ color: 'var(--text-primary)' }}>
                          {linked.current_stock_kg ?? 0}/{linked.storage_capacity_kg} kg
                        </span></p>
                      )}
                      {linked.cash_register != null && (
                        <p>Caisse : <span style={{ color: 'var(--color-gold-light)' }}>
                          {Number(linked.cash_register).toLocaleString('fr-FR')} ∞
                        </span></p>
                      )}
                      {linked.employee_count != null && linked.max_employees != null && (
                        <p>Employés : <span style={{ color: 'var(--text-primary)' }}>
                          {linked.employee_count}/{linked.max_employees}
                        </span></p>
                      )}
                      {linked.gangsters_assigned != null && linked.gangsters_assigned > 0 && (
                        <p>Gangsters : <span style={{ color: 'var(--color-red-light)' }}>
                          {linked.gangsters_assigned}
                        </span></p>
                      )}
                      {linked.production_type && (
                        <p>Prod. : <span style={{ color: 'var(--text-primary)' }}>
                          {linked.production_type} ({linked.production_limit_per_day}/j)
                        </span></p>
                      )}
                      {linked.daily_sales_limit > 0 && (
                        <p>Ventes/j : <span style={{ color: 'var(--text-primary)' }}>
                          {linked.daily_sales_limit}
                        </span></p>
                      )}
                      {linked.heat_generated > 0 && (
                        <p>Heat/j : <span style={{ color: 'var(--color-red-light)' }}>
                          +{linked.heat_generated}
                        </span></p>
                      )}
                    </div>
                    {linked.closed_until && new Date(linked.closed_until) > new Date() && (
                      <p className="text-[10px] mt-1" style={{ color: 'var(--color-red-light)' }}>
                        ⏸ Fermé jusqu'à {new Date(linked.closed_until).toLocaleString('fr-FR')}
                      </p>
                    )}
                    {linked.last_robbed_at && (
                      <p className="text-[9px] mt-0.5 italic" style={{ color: 'var(--text-muted)' }}>
                        Dernier braquage : {new Date(linked.last_robbed_at).toLocaleDateString('fr-FR')}
                      </p>
                    )}
                  </div>
                )}
                {/* Phase 15 Iter 7.1 (19-04-2026) — Dernière visite révélée (snapshot stocks/owner)
                    Phase 6 (2026-04-23) — enrichi : capacité stockage + poids items + véhicules parkés + cooldown 24h */}
                {lastReveal && !linked?.is_owned_by_me && (
                  <div className="mt-2 pt-2" style={{ borderTop: '1px dashed rgba(96,165,250,0.2)' }}>
                    <p className="text-[9px] font-bold mb-1" style={{
                      color: '#93c5fd', letterSpacing: '.15em', fontFamily: 'var(--font-subtitle)',
                    }}>
                      DERNIÈRE VISITE · {new Date(lastReveal.revealed_at).toLocaleString('fr-FR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' })}
                    </p>
                    <div className="text-[10px] space-y-0.5" style={{ color: 'var(--text-secondary)' }}>
                      {lastReveal.is_for_sale && lastReveal.sale_price_light && (
                        <p>
                          <span style={{ color: '#86efac' }}>En vente</span>
                          {' : '}
                          <span style={{ color: 'var(--color-gold-light)' }}>
                            {Number(lastReveal.sale_price_light).toLocaleString('fr-FR')} ∞
                          </span>
                        </p>
                      )}
                      {/* Phase 6 — capacité stockage + remplissage */}
                      {(() => {
                        const cap = Number(lastReveal.content_snapshot?.storage_capacity_kg ?? 0);
                        const cur = Number(lastReveal.content_snapshot?.current_stock_kg ?? 0);
                        if (cap <= 0) return null;
                        const pct = Math.min(100, Math.round((cur / cap) * 100));
                        return (
                          <p>
                            <span style={{ color: 'var(--text-muted)' }}>Stockage : </span>
                            <span style={{ color: 'var(--color-gold-light)' }}>{cur.toLocaleString('fr-FR')} / {cap.toLocaleString('fr-FR')} kg</span>
                            <span style={{ color: 'var(--text-muted)' }}> ({pct}%)</span>
                          </p>
                        );
                      })()}
                      {Array.isArray(lastReveal.content_snapshot?.stocks) && lastReveal.content_snapshot.stocks.length > 0 && (
                        <div>
                          <p style={{ color: 'var(--text-muted)' }}>Items vus :</p>
                          <ul className="text-[9px] pl-3" style={{ listStyle: 'disc inside' }}>
                            {lastReveal.content_snapshot.stocks.slice(0, 8).map((s: any, i: number) => {
                              const totalG = Number(s.total_weight_grams ?? 0);
                              const weightLabel = totalG >= 1_000_000
                                ? `${(totalG / 1_000_000).toFixed(1)} t`
                                : totalG >= 1000
                                ? `${(totalG / 1000).toFixed(1)} kg`
                                : totalG > 0
                                ? `${totalG} g`
                                : null;
                              return (
                                <li key={i}>
                                  {s.item_subtype || s.item || s.name || 'item'}
                                  {s.quantity ? ` × ${s.quantity}` : ''}
                                  {weightLabel ? <span style={{ color: 'var(--text-muted)' }}> ({weightLabel})</span> : null}
                                </li>
                              );
                            })}
                          </ul>
                        </div>
                      )}
                      {/* Phase 6 — véhicules garés (garage_storage) */}
                      {Array.isArray(lastReveal.content_snapshot?.parked_vehicles) && lastReveal.content_snapshot.parked_vehicles.length > 0 && (
                        <div>
                          <p style={{ color: 'var(--text-muted)' }}>Véhicules garés ({lastReveal.content_snapshot.parked_vehicles.length}) :</p>
                          <ul className="text-[9px] pl-3" style={{ listStyle: 'disc inside' }}>
                            {lastReveal.content_snapshot.parked_vehicles.slice(0, 8).map((v: any, i: number) => (
                              <li key={i}>
                                {v.name || v.type || 'véhicule'}
                                {typeof v.condition === 'number' ? ` · ${v.condition} HP` : ''}
                                {v.is_stolen ? <span style={{ color: 'var(--color-red-light)' }}> · volé</span> : ''}
                              </li>
                            ))}
                          </ul>
                        </div>
                      )}
                      {typeof lastReveal.content_snapshot?.gangsters_seen === 'number' && lastReveal.content_snapshot.gangsters_seen > 0 && (
                        <p>
                          <span style={{ color: 'var(--color-red-light)' }}>
                            {lastReveal.content_snapshot.gangsters_seen} gangster(s) aperçu(s)
                          </span>
                        </p>
                      )}
                      {lastReveal.visited_by_scope && (
                        <p className="text-[9px] italic" style={{ color: 'var(--text-muted)' }}>
                          Visite {lastReveal.visited_by_scope === 'gang' ? 'de votre gang' : lastReveal.visited_by_scope === 'cartel' ? 'de votre cartel' : 'solo'}
                        </p>
                      )}
                      {/* Phase 6 — cooldown 24h */}
                      {lastReveal.is_visit_on_cooldown && lastReveal.next_visit_at && (
                        <p className="text-[9px] italic mt-1" style={{ color: 'var(--color-gold-light)' }}>
                          ⏳ Prochaine visite possible le {new Date(lastReveal.next_visit_at).toLocaleString('fr-FR', { day: '2-digit', month: '2-digit', hour: '2-digit', minute: '2-digit' })}
                        </p>
                      )}
                    </div>
                  </div>
                )}
                {/* Phase 15 Commit 4 — Quick actions équipe (wizard 3 étapes) */}
                {isGuardableType && (
                  <div className="mt-2 pt-2" style={{ borderTop: '1px dashed rgba(255,255,255,0.1)' }}>
                    <p className="text-[9px] font-bold mb-2" style={{ color: 'var(--color-gold-light)', letterSpacing: '.15em', fontFamily: 'var(--font-subtitle)' }}>
                      ACTIONS ÉQUIPE
                    </p>
                    <div className="flex flex-wrap gap-1">
                      {/* Phase 6 (2026-04-23) — bouton Visiter désactivé pendant la cooldown 24h */}
                      {lastReveal?.is_visit_on_cooldown ? (
                        <button type="button" className="new-order" disabled
                          style={{ width: 'auto', flex: '1 1 auto', fontSize: 10, padding: '4px 10px', margin: 0, opacity: 0.45, cursor: 'not-allowed' }}
                          title={`Cooldown 24h. Prochaine visite ${lastReveal.next_visit_at ? new Date(lastReveal.next_visit_at).toLocaleString('fr-FR') : 'bientôt'}`}>
                          <Eye size={12} style={{ display: 'inline', marginRight: 4, verticalAlign: 'middle' }} />Visiter (24h)
                        </button>
                      ) : (
                        <button type="button" className="new-order" style={{ width: 'auto', flex: '1 1 auto', fontSize: 10, padding: '4px 10px', margin: 0 }}
                          onClick={() => openWizard('visit')} title="Envoyer une équipe visiter (stocks révélés, combat si gardes)">
                          <Eye size={12} style={{ display: 'inline', marginRight: 4, verticalAlign: 'middle' }} />Visiter
                        </button>
                      )}
                      {isForSale && (
                        <button type="button" className="new-order" style={{ width: 'auto', flex: '1 1 auto', fontSize: 10, padding: '4px 10px', margin: 0 }}
                          onClick={() => openWizard('buy')} title="Acheter ce POI">
                          💰 Acheter
                        </button>
                      )}
                      {isOwner && (
                        <button type="button" className="new-order" style={{ width: 'auto', flex: '1 1 auto', fontSize: 10, padding: '4px 10px', margin: 0 }}
                          onClick={() => openWizard('guard')} title="Assigner des gangsters en garde">
                          <Users size={12} style={{ display: 'inline', marginRight: 4, verticalAlign: 'middle' }} />Garder
                        </button>
                      )}
                      {/* Phase 15 Iter 7.2 (19-04-2026) — Mettre en vente / Dé-lister (owner uniquement) */}
                      {isOwner && ['business', 'residence', 'warehouse'].includes(target?.type || '') && !isForSale && (
                        <button type="button" className="new-order" style={{ width: 'auto', flex: '1 1 auto', fontSize: 10, padding: '4px 10px', margin: 0, background: 'rgba(212,168,67,0.15)' }}
                          onClick={async () => {
                            const raw = prompt('Prix de vente (∞ Lumière, min 100) :');
                            if (!raw) return;
                            const price = Math.max(100, Math.round(Number(raw)));
                            if (!Number.isFinite(price)) return alert('Prix invalide');
                            try {
                              await api.property.listForSale(target.type as any, target.id, price);
                              alert(`Mis en vente pour ${price.toLocaleString('fr-FR')} ∞`);
                              // Rafraîchit la fiche POI
                              const res: any = await api.mapAction.getPoiDetails(props.poiId!);
                              setData(res);
                            } catch (e: any) { alert(e?.message || 'Erreur'); }
                          }} title="Mettre ce POI en vente sur le marketplace">
                          🏷 Mettre en vente
                        </button>
                      )}
                      {isOwner && ['business', 'residence', 'warehouse'].includes(target?.type || '') && isForSale && (
                        <button type="button" className="new-order" style={{ width: 'auto', flex: '1 1 auto', fontSize: 10, padding: '4px 10px', margin: 0, background: 'rgba(212,168,67,0.15)' }}
                          onClick={async () => {
                            if (!confirm('Retirer ce POI de la vente ?')) return;
                            try {
                              await api.property.unlist(target.type as any, target.id);
                              const res: any = await api.mapAction.getPoiDetails(props.poiId!);
                              setData(res);
                            } catch (e: any) { alert(e?.message || 'Erreur'); }
                          }} title="Retirer de la vente">
                          🏷 Dé-lister
                        </button>
                      )}
                      {!isOwner && (
                        <button type="button" className="new-order is-red" style={{ width: 'auto', flex: '1 1 auto', fontSize: 10, padding: '4px 10px', margin: 0 }}
                          onClick={() => openWizard('attack')} title="Attaquer ce POI">
                          <Swords size={12} style={{ display: 'inline', marginRight: 4, verticalAlign: 'middle' }} />Attaquer
                        </button>
                      )}
                      {/* Phase 13 (2026-04-20) — Développer (si pas d'activité illégale) / Légaliser (si activité présente) */}
                      {isOwner && target?.type === 'business' && linked?.illegal_activity_type && (
                        <button type="button" className="new-order" style={{ width: 'auto', flex: '1 1 auto', fontSize: 10, padding: '4px 10px', margin: 0, background: 'rgba(34,197,94,0.15)' }}
                          onClick={() => openWizard('redeem')} title="Retirer l'activité illégale — redevient propre">
                          ⚖ Légaliser
                        </button>
                      )}
                      {isOwner && target?.type === 'business' && !linked?.illegal_activity_type && (
                        <button type="button" className="new-order" style={{ width: 'auto', flex: '1 1 auto', fontSize: 10, padding: '4px 10px', margin: 0, background: 'rgba(239,68,68,0.12)', border: '1px solid rgba(239,68,68,0.35)' }}
                          onClick={() => openWizard('develop')} title="Installer une activité illégale cachée">
                          <AlertTriangle size={12} style={{ display: 'inline', marginRight: 4, verticalAlign: 'middle' }} />Développer
                        </button>
                      )}
                    </div>
                  </div>
                )}
                {/* Phase 15 Iter 7.4 (19-04-2026) — Panneau BANQUE (loan + launder) */}
                {poi?.icon === 'bank' && target?.id && (
                  <BankLoanPanel poiId={target.id} />
                )}

                {/* Phase 4 (2026-04-20) — Panneau Casino */}
                {linked?.business_type === 'casino' && target?.id && (
                  <CasinoPanel casinoId={target.id} isOwner={!!linked?.is_owned_by_me} />
                )}

                {/* Phase 5 (2026-04-20) — Panneau Association (3 types) */}
                {(linked?.business_type === 'association_caritative'
                  || linked?.business_type === 'association_ecologique'
                  || linked?.business_type === 'association_sociale')
                  && target?.id && (
                  <AssociationPanel businessId={target.id} associationType={linked.business_type} />
                )}

                {/* Phase 3 (2026-04-20) — Panneau Concessionnaire (icon=car_rental) */}
                {poi?.icon === 'car_rental' && poi?.entity_id && (
                  <DealershipPanel dealershipId={poi.entity_id} />
                )}

                {/* Phase 3 (2026-04-20) — Panneau Garage Auto (réparation) */}
                {linked?.business_type === 'garage' && target?.id && (
                  <VehicleServicePanel businessId={target.id} mode="garage"
                    pricePerHp={linked?.repair_price_per_hp} />
                )}

                {/* Phase 8.11a (2026-04-29) — Parking : véhicules stockés
                    dans ce garage owned (assign / unassign). Le user appelle
                    ça "Parking" en UX (cf spec), même si business_type='garage'. */}
                {linked?.is_owned_by_me && linked?.business_type === 'garage' && target?.id && (
                  <ParkingPanel businessId={target.id} />
                )}

                {/* Phase 3 (2026-04-20) — Panneau Carrosserie (peinture anti-chaleur) */}
                {linked?.business_type === 'carrosserie' && target?.id && (
                  <VehicleServicePanel businessId={target.id} mode="carrosserie" />
                )}

                {/* Phase 7 (2026-04-20) — Panneau Méditation (lieu de culte) */}
                {poi?.icon === 'place_of_worship' && poi?.id && (
                  <MeditationPanel poiId={poi.id} poiName={poi.name || ''} />
                )}

                {/* Phase 16 (2026-04-21) — Panneau Kiosque Media/Journal */}
                {(poi?.icon === 'kiosk' || poi?.icon === 'newsagent') && (
                  <KioskMediaPanel />
                )}

                {/* Phase 16 (2026-04-21) — Panneau Stock Caviste/Biergarten/Bar (Commander/Importer) */}
                {linked?.is_owned_by_me && target?.id &&
                  ['caviste', 'biergarten', 'bar', 'nightclub', 'restaurant'].includes(linked?.business_type) && (
                  <CommerceStockPanel businessId={target.id} />
                )}
                {/* Panneau Gardes — visible si POI possédé ou si gardes présents (pour voir l'opposition) */}
                {isGuardableType && guards.length > 0 && (
                  <div className="mt-2 pt-2" style={{ borderTop: '1px dashed rgba(255,255,255,0.1)' }}>
                    <p className="text-[9px] font-bold mb-2" style={{ color: 'var(--color-red-light)', letterSpacing: '.15em', fontFamily: 'var(--font-subtitle)' }}>
                      GARDES EN POSTE ({guards.length}/4)
                    </p>
                    <div className="space-y-1">
                      {guards.map((g: any) => (
                        <div key={g.id} className="flex items-center justify-between text-[10px]" style={{ color: 'var(--text-secondary)' }}>
                          <span className="truncate">{String(g.guard_player_id).slice(0, 8)}…</span>
                          {isOwner && (
                            <button type="button"
                              onClick={() => releaseGuard(g.id)}
                              className="text-[9px] px-2 py-0.5 rounded"
                              style={{ background: 'rgba(239,68,68,0.1)', color: '#ef4444', border: '1px solid rgba(239,68,68,0.25)' }}>
                              Relâcher
                            </button>
                          )}
                        </div>
                      ))}
                    </div>
                  </div>
                )}
              </div>

              {actionMsg && (
                <div className="p-3 rounded-xl" style={{ background: 'rgba(34,197,94,0.10)', border: '1px solid rgba(34,197,94,0.25)' }}>
                  <p className="text-[11px]" style={{ color: '#22c55e' }}>{actionMsg}</p>
                </div>
              )}

              {/* audit 15-04-2026 Phase 12.b : Bouton "Stocker" pour les proprietes du joueur.
                  Affiche si le POI cible (target) est business/residence/warehouse/vehicle
                  ET que le joueur en est proprietaire (detecte via linked.is_owned_by_me
                  ou fallback sur ownerName === player username). */}
              {target && isStorableLocation(target.type) && linked?.is_owned_by_me !== false && (
                <button
                  type="button"
                  onClick={() => setShowStorageModal(true)}
                  className="w-full p-2 rounded-xl flex items-center justify-center gap-2 hover:opacity-90"
                  style={{
                    background: 'rgba(212,168,67,0.12)',
                    border: '1px solid rgba(212,168,67,0.3)',
                    color: 'var(--color-gold)',
                  }}
                >
                  <Package size={14} />
                  <span className="text-[11px] font-bold">Stocker / Retirer des items</span>
                </button>
              )}

              {/* Phase 13 UI : Deal spot section pour residences.
                  Visible si target.type='residence' + joueur est proprietaire + planque active.
                  Permet d'activer/desactiver un point de deal fixe. */}
              {linked?.type === 'residence' && linked?.is_owned_by_me && linked?.is_planque_active && (
                <DealSpotPanel
                  residenceId={linked.id}
                  dealSpotActive={!!linked.deal_spot_active}
                  dealSpotDrug={linked.deal_spot_drug}
                  dealSpotHeat={linked.deal_spot_heat ?? 0}
                  executing={executing}
                  onActivate={async (drugName) => {
                    if (executing) return;
                    setExecuting('deal_spot_activate');
                    setError(null);
                    setActionMsg(null);
                    try {
                      const res: any = await api.property.residences.activateDealSpot(linked.id, drugName);
                      if (res?.success) {
                        setActionMsg(res.message || 'Point de deal active');
                        // Refresh POI data
                        if (props.poiId) {
                          const refreshed = await api.mapAction.getPoiDetails(props.poiId);
                          setData(refreshed as any);
                        }
                      } else {
                        setError(res?.message || 'Activation refusee');
                      }
                    } catch (e: any) { setError(e?.message || 'Erreur'); }
                    finally { setExecuting(null); }
                  }}
                  onDeactivate={async () => {
                    if (executing) return;
                    setExecuting('deal_spot_deactivate');
                    setError(null);
                    try {
                      const res: any = await api.property.residences.deactivateDealSpot(linked.id);
                      if (res?.success) {
                        setActionMsg(res.message || 'Point de deal desactive');
                        if (props.poiId) {
                          const refreshed = await api.mapAction.getPoiDetails(props.poiId);
                          setData(refreshed as any);
                        }
                      } else { setError(res?.message || 'Erreur'); }
                    } catch (e: any) { setError(e?.message || 'Erreur'); }
                    finally { setExecuting(null); }
                  }}
                />
              )}

              {/* Phase 4 (2026-04-26) — Soudoyer POI gouvernemental.
                  Visible uniquement pour les infrastructures police/courthouse/townhall.
                  Le clic ouvre le PoiBribeModal mounté dans GameMap (event 'poi-bribe-open'). */}
              {(poi?.icon === 'police' || poi?.icon === 'courthouse' || poi?.icon === 'townhall') && (
                <div className="p-3 rounded-xl space-y-2"
                  style={{ background: 'rgba(212,168,67,0.08)', border: '1px solid var(--border-gold)' }}>
                  <p className="text-xs font-bold" style={{ color: 'var(--color-gold-light)' }}>
                    {poi.icon === 'police' && '⚖ Bakchich aux forces'}
                    {poi.icon === 'courthouse' && '⚖ Affaire au tribunal'}
                    {poi.icon === 'townhall' && '⚖ Sous main à la mairie'}
                  </p>
                  <p className="text-[10px] italic" style={{ color: 'var(--text-secondary)' }}>
                    Réduction de chaleur, items judiciaires, libération du gang. 1× par jour max sur ce POI.
                  </p>
                  <button type="button" className="new-order w-full"
                    style={{ fontSize: 10, padding: '6px 8px' }}
                    onClick={() => {
                      window.dispatchEvent(new CustomEvent('poi-bribe-open', {
                        detail: {
                          poiId: poi.id,
                          poiName: poi.name,
                          poiKind: poi.icon,
                        },
                      }));
                      props.onClose?.();
                    }}>
                    Proposer un arrangement
                  </button>
                </div>
              )}

              {/* audit 15-04-2026 feedback utilisateur : catalogue d'armes chez l'armurier.
                  Visible si le business target est type='armurerie'. Le menu est grise
                  tant que le joueur n'a pas l'item document "Permis de port d'armes". */}
              {linked?.business_type === 'armurerie' && Array.isArray(linked?.weapon_catalog) && (
                <ArmurerieCatalog
                  businessId={target?.id}
                  hasPermit={!!linked?.has_weapon_permit}
                  catalog={linked.weapon_catalog as WeaponCatalogEntry[]}
                  executing={executing}
                  onBuy={async (weaponName) => {
                    if (!target?.id || executing) return;
                    setExecuting('buy_weapon:' + weaponName);
                    setError(null);
                    setActionMsg(null);
                    try {
                      const res: any = await api.mapAction.executeAction({
                        action_code: 'buy_weapon',
                        target_type: 'business',
                        target_id: target.id,
                        params: { weapon_name: weaponName },
                      });
                      if (res?.success === false) {
                        setError(res?.message || 'Achat refuse');
                      } else if (res?.message) {
                        setActionMsg(String(res.message));
                      }
                    } catch (e: any) {
                      setError(e?.message || 'Erreur achat');
                    } finally {
                      setExecuting(null);
                    }
                  }}
                />
              )}

              <div className="p-3 rounded-xl space-y-2" style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)' }}>
                <p className="text-xs font-bold" style={{ color: 'var(--text-primary)' }}>Actions</p>
                {actions.length === 0 ? (
                  <p className="text-[11px]" style={{ color: 'var(--text-muted)' }}>Aucune action disponible</p>
                ) : (
                  <div className="grid grid-cols-2 gap-2">
                    {actions.map((a: any) => (
                      <button
                        key={a.code}
                        type="button"
                        onClick={() => runAction(a)}
                        disabled={executing !== null}
                        className="py-2 rounded-xl text-[11px] font-bold disabled:opacity-50"
                        style={{ background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.12)', color: 'var(--text-primary)' }}
                      >
                        {executing === a.code ? '…' : a.label}
                      </button>
                    ))}
                  </div>
                )}
              </div>
            </>
          )}
        </div>
      </div>

      {/* Storage transfer modal (audit 15-04-2026 Phase 12.b) */}
      {showStorageModal && target && playerId && (
        <StorageTransferModal
          playerId={playerId}
          destinationType={target.type as any}
          destinationId={target.id}
          destinationName={linked?.name || 'Destination'}
          onClose={() => setShowStorageModal(false)}
          onTransferred={() => { /* pas de refresh du POI — l'inventaire est cote joueur */ }}
        />
      )}
    </div>,
    document.body,
  );
}

// audit 15-04-2026 Phase 12.b : helper pour determiner si le POI cible peut recevoir
// des items (via PropertyService.transferItem).
function isStorableLocation(targetType: string | undefined): boolean {
  return targetType === 'business' || targetType === 'residence' || targetType === 'warehouse' || targetType === 'vehicle';
}

// ══════════════════════════════════════════════════════════════════════
// audit 15-04-2026 feedback utilisateur : catalogue d'armes chez l'armurier
// ══════════════════════════════════════════════════════════════════════
function ArmurerieCatalog(props: {
  businessId: string | undefined;
  hasPermit: boolean;
  catalog: WeaponCatalogEntry[];
  executing: string | null;
  onBuy: (weaponName: string) => Promise<void>;
}) {
  const { hasPermit, catalog, executing, onBuy } = props;

  return (
    <div
      className="relative p-3 rounded-xl space-y-2"
      style={{
        background: 'rgba(55,65,81,0.15)', // gray-700 avec transparence (couleur armurerie)
        border: '1px solid rgba(55,65,81,0.4)',
      }}
    >
      {/* Header catalogue */}
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <ShoppingBag size={14} style={{ color: '#9ca3af' }} />
          <p className="text-xs font-bold" style={{ color: 'var(--text-primary)' }}>
            Catalogue d'armes legales
          </p>
        </div>
        {/* Badge permis */}
        {hasPermit ? (
          <div
            className="flex items-center gap-1 px-2 py-0.5 rounded"
            style={{
              background: 'rgba(34,197,94,0.15)',
              border: '1px solid rgba(34,197,94,0.35)',
            }}
          >
            <Scale size={10} style={{ color: '#22c55e' }} />
            <span className="text-[9px] font-bold uppercase tracking-wide" style={{ color: '#22c55e' }}>
              Permis OK
            </span>
          </div>
        ) : (
          <div
            className="flex items-center gap-1 px-2 py-0.5 rounded"
            style={{
              background: 'rgba(239,68,68,0.15)',
              border: '1px solid rgba(239,68,68,0.35)',
            }}
          >
            <Lock size={10} style={{ color: '#ef4444' }} />
            <span className="text-[9px] font-bold uppercase tracking-wide" style={{ color: '#ef4444' }}>
              Sans permis
            </span>
          </div>
        )}
      </div>

      {/* Liste des armes — grisee tant que !hasPermit */}
      <div className="space-y-1.5">
        {catalog.length === 0 && (
          <p className="text-[11px] italic" style={{ color: 'var(--text-muted)' }}>
            Stock vide chez l'armurier.
          </p>
        )}
        {catalog.map((w) => {
          const isBuying = executing === 'buy_weapon:' + w.name;
          return (
            <div
              key={w.name}
              className="flex items-center justify-between p-2 rounded-lg"
              style={{
                background: 'rgba(255,255,255,0.03)',
                border: '1px solid rgba(255,255,255,0.08)',
                opacity: hasPermit ? 1 : 0.45,
              }}
            >
              <div className="min-w-0 flex-1">
                <p className="text-[11px] font-bold truncate" style={{ color: 'var(--text-primary)' }}>
                  {w.name}
                </p>
                <p className="text-[9px]" style={{ color: 'var(--text-muted)' }}>
                  Att {w.attack_bonus} • Portee {w.range}m • Discretion {w.concealability}
                </p>
              </div>
              <div className="flex items-center gap-2 ml-2">
                <span className="text-[11px] font-bold" style={{ color: 'var(--color-gold)' }}>
                  {w.price} ∞
                </span>
                <button
                  type="button"
                  disabled={!hasPermit || executing !== null}
                  onClick={() => onBuy(w.name)}
                  className="px-2 py-1 rounded text-[10px] font-bold disabled:opacity-50 disabled:cursor-not-allowed"
                  style={{
                    background: hasPermit ? 'rgba(212,168,67,0.2)' : 'rgba(100,116,139,0.15)',
                    border: `1px solid ${hasPermit ? 'rgba(212,168,67,0.5)' : 'rgba(100,116,139,0.35)'}`,
                    color: hasPermit ? 'var(--color-gold)' : 'var(--text-muted)',
                  }}
                  title={hasPermit ? `Acheter ${w.name}` : 'Requiert Permis de port d\'armes'}
                >
                  {isBuying ? '...' : 'Acheter'}
                </button>
              </div>
            </div>
          );
        })}
      </div>

      {/* Message gate permis */}
      {!hasPermit && (
        <div
          className="mt-2 p-2 rounded-lg flex items-start gap-2"
          style={{
            background: 'rgba(239,68,68,0.08)',
            border: '1px solid rgba(239,68,68,0.25)',
          }}
        >
          <AlertTriangle size={12} style={{ color: '#ef4444', flexShrink: 0, marginTop: 2 }} />
          <p className="text-[10px]" style={{ color: 'rgba(239,68,68,0.9)' }}>
            Vous n'avez pas de <b>Permis de port d'armes</b>. Obtenez-le a la prefecture,
            via une mission legale, ou achetez un faux sur le marche noir.
          </p>
        </div>
      )}
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════════
// Phase 13 UI : panneau point de deal pour les residences (planque active)
// ══════════════════════════════════════════════════════════════════════

const AVAILABLE_DRUGS = [
  'Cannabis', 'Cocaine', 'Heroine', 'Crack', 'Ecstasy',
  'LSD', 'Champignons', 'Methamphetamine', 'Ketamine', 'Opium',
  'Morphine', 'Fentanyl',
];

function DealSpotPanel(props: {
  residenceId: string;
  dealSpotActive: boolean;
  dealSpotDrug: string | null;
  dealSpotHeat: number;
  executing: string | null;
  onActivate: (drugName: string) => Promise<void>;
  onDeactivate: () => Promise<void>;
}) {
  const [selectedDrug, setSelectedDrug] = useState(props.dealSpotDrug || AVAILABLE_DRUGS[0]);

  if (props.dealSpotActive) {
    // Active: show status + deactivate button
    const heatColor = props.dealSpotHeat >= 70 ? '#ef4444' : props.dealSpotHeat >= 40 ? '#f97316' : '#22c55e';
    return (
      <div
        className="p-3 rounded-xl space-y-2"
        style={{ background: 'rgba(239,68,68,0.06)', border: '1px solid rgba(239,68,68,0.2)' }}
      >
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <Flame size={14} style={{ color: '#ef4444' }} />
            <p className="text-xs font-bold" style={{ color: '#ef4444' }}>Point de deal actif</p>
          </div>
          <div className="flex items-center gap-1 px-2 py-0.5 rounded" style={{ background: `${heatColor}20`, border: `1px solid ${heatColor}40` }}>
            <span className="text-[9px] font-bold" style={{ color: heatColor }}>
              Chaleur {props.dealSpotHeat}%
            </span>
          </div>
        </div>
        <p className="text-[11px]" style={{ color: 'var(--text-secondary)' }}>
          Drogue : <span style={{ color: 'var(--text-primary)' }}>{props.dealSpotDrug}</span>
        </p>
        {props.dealSpotHeat >= 70 && (
          <p className="text-[10px] italic" style={{ color: '#ef4444' }}>
            Risque de raid police eleve ! Desactivez pour reduire la chaleur.
          </p>
        )}
        <button
          type="button"
          onClick={props.onDeactivate}
          disabled={props.executing !== null}
          className="w-full py-2 rounded-xl text-[11px] font-bold disabled:opacity-50"
          style={{ background: 'rgba(239,68,68,0.15)', border: '1px solid rgba(239,68,68,0.3)', color: '#ef4444' }}
        >
          <span className="flex items-center justify-center gap-1.5">
            <PowerOff size={12} />
            {props.executing === 'deal_spot_deactivate' ? '...' : 'Desactiver le point de deal'}
          </span>
        </button>
      </div>
    );
  }

  // Inactive: show activation form
  return (
    <div
      className="p-3 rounded-xl space-y-2"
      style={{ background: 'rgba(34,197,94,0.06)', border: '1px solid rgba(34,197,94,0.2)' }}
    >
      <div className="flex items-center gap-2">
        <Power size={14} style={{ color: '#22c55e' }} />
        <p className="text-xs font-bold" style={{ color: '#22c55e' }}>Activer un point de deal</p>
      </div>
      <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
        Transforme cette planque en point de vente fixe. Genere du revenu horaire mais attire la police.
      </p>
      <select
        value={selectedDrug}
        onChange={(e) => setSelectedDrug(e.target.value)}
        className="w-full py-1.5 px-2 rounded-lg text-[11px]"
        style={{ background: 'var(--bg-tertiary)', border: '1px solid var(--border-dark)', color: 'var(--text-primary)' }}
      >
        {AVAILABLE_DRUGS.map((d) => (
          <option key={d} value={d}>{d}</option>
        ))}
      </select>
      <button
        type="button"
        onClick={() => props.onActivate(selectedDrug)}
        disabled={props.executing !== null}
        className="w-full py-2 rounded-xl text-[11px] font-bold disabled:opacity-50"
        style={{ background: 'rgba(34,197,94,0.15)', border: '1px solid rgba(34,197,94,0.3)', color: '#22c55e' }}
      >
        <span className="flex items-center justify-center gap-1.5">
          <Power size={12} />
          {props.executing === 'deal_spot_activate' ? '...' : 'Activer'}
        </span>
      </button>
    </div>
  );
}



// ══════════════════════════════════════════════════════════════════════
// Phase 15 Iter 7.4 (19-04-2026) — Panneau BANQUE : prêt perso + mes prêts
// Phase 15 Commit 8 (20-04-2026) — Bouton crédit direct (quick actions 25/50/100%)
// ══════════════════════════════════════════════════════════════════════
function BankLoanPanel({ poiId }: { poiId: string }) {
  const [ceiling, setCeiling] = useState<number | null>(null);
  const [loans, setLoans] = useState<any[]>([]);
  const [amount, setAmount] = useState('');
  const [duration, setDuration] = useState<1 | 7 | 30>(7);
  const [busy, setBusy] = useState(false);
  // Phase 4 (2026-04-20) — Blanchiment
  const [launderStatus, setLaunderStatus] = useState<{ is_owned_bank: boolean; cap: number; used: number; remaining: number } | null>(null);
  const [launderAmount, setLaunderAmount] = useState('');
  const [showLaunder, setShowLaunder] = useState(false);

  useEffect(() => {
    (async () => {
      try {
        const c = await api.bank.myCeiling();
        setCeiling(c?.ceiling ?? 0);
        const l = await api.bank.myLoans();
        setLoans(Array.isArray(l) ? l : []);
        const ls = await api.bank.launderStatus(poiId).catch(() => null);
        if (ls) setLaunderStatus(ls);
      } catch { /* silent */ }
    })();
  }, [poiId]);

  const doLaunder = async () => {
    const amt = Math.round(Number(launderAmount));
    if (!Number.isFinite(amt) || amt < 100) return alert('Montant minimum 100 ∞ shadow');
    if (launderStatus && amt > launderStatus.remaining) {
      return alert(`Dépasse le plafond hebdomadaire (${launderStatus.remaining.toLocaleString('fr-FR')} ∞ restants)`);
    }
    setBusy(true);
    try {
      const r = await api.bank.launder(poiId, amt);
      alert(`Blanchiment : ${r.credited.toLocaleString('fr-FR')} ∞ light crédités${r.commission > 0 ? ` (commission ${r.commission} ∞)` : ' (gratuit — banque possédée)'}`);
      setLaunderAmount('');
      const ls = await api.bank.launderStatus(poiId);
      setLaunderStatus(ls);
    } catch (e: any) { alert(e?.message || 'Refusé'); }
    finally { setBusy(false); }
  };

  /** Phase 15 Commit 8 — crédit direct à X% du plafond pour Y jours. */
  const quickLoan = async (pctOfCeiling: number, dur: 1 | 7 | 30) => {
    if (ceiling == null || ceiling < 100) {
      return alert('Plafond trop faible pour un crédit direct (minimum 100 ∞).');
    }
    const amt = Math.max(100, Math.floor((ceiling * pctOfCeiling) / 100 / 100) * 100);
    if (!confirm(`Emprunter ${amt.toLocaleString('fr-FR')} ∞ sur ${dur} jour${dur > 1 ? 's' : ''} ?`)) return;
    setBusy(true);
    try {
      await api.bank.requestLoan(poiId, amt, dur);
      alert(`Prêt accordé : ${amt.toLocaleString('fr-FR')} ∞`);
      const l = await api.bank.myLoans();
      setLoans(Array.isArray(l) ? l : []);
    } catch (e: any) { alert(e?.message || 'Refusé'); }
    finally { setBusy(false); }
  };

  const request = async () => {
    const amt = Math.round(Number(amount));
    if (!Number.isFinite(amt) || amt < 100) return alert('Montant minimum 100 ∞');
    if (ceiling != null && amt > ceiling) return alert(`Montant dépasse votre plafond (${ceiling.toLocaleString('fr-FR')} ∞)`);
    setBusy(true);
    try {
      await api.bank.requestLoan(poiId, amt, duration);
      alert('Prêt accordé !');
      setAmount('');
      const l = await api.bank.myLoans();
      setLoans(Array.isArray(l) ? l : []);
    } catch (e: any) { alert(e?.message || 'Refusé'); }
    finally { setBusy(false); }
  };

  const repay = async (loanId: string, owed: number) => {
    const raw = prompt(`Montant à rembourser (solde dû: ${owed.toLocaleString('fr-FR')} ∞) :`);
    if (!raw) return;
    const amt = Math.max(1, Math.round(Number(raw)));
    if (!Number.isFinite(amt)) return;
    setBusy(true);
    try {
      await api.bank.repay(loanId, amt);
      const l = await api.bank.myLoans();
      setLoans(Array.isArray(l) ? l : []);
    } catch (e: any) { alert(e?.message || 'Erreur'); }
    finally { setBusy(false); }
  };

  return (
    <div className="mt-2 pt-2" style={{ borderTop: '1px dashed rgba(96,165,250,0.25)' }}>
      <p className="text-[9px] font-bold mb-2" style={{ color: '#93c5fd', letterSpacing: '.15em', fontFamily: 'var(--font-subtitle)' }}>
        BANQUE — CRÉDIT
      </p>
      {ceiling != null && (
        <p className="text-[11px] mb-2" style={{ color: 'var(--text-secondary)' }}>
          Plafond calculé : <b style={{ color: 'var(--color-gold-light)' }}>{ceiling.toLocaleString('fr-FR')} ∞</b>
        </p>
      )}

      {/* Phase 15 Commit 8 — Bouton crédit direct : 3 raccourcis à X% du plafond */}
      {ceiling != null && ceiling >= 100 && (
        <div className="mb-3">
          <p className="text-[9px] font-bold mb-1.5" style={{ color: '#93c5fd', letterSpacing: '.1em' }}>
            CRÉDIT DIRECT
          </p>
          <div className="grid grid-cols-3 gap-1 mb-1">
            {([25, 50, 100] as const).map((pct) => {
              const amt = Math.max(100, Math.floor((ceiling * pct) / 100 / 100) * 100);
              return (
                <button
                  key={pct}
                  type="button"
                  onClick={() => quickLoan(pct, 7)}
                  disabled={busy}
                  className="py-2 rounded-lg text-[10px] font-bold transition hover:opacity-90 disabled:opacity-50"
                  style={{
                    background: 'rgba(59,130,246,0.12)',
                    border: '1px solid rgba(59,130,246,0.35)',
                    color: '#93c5fd',
                  }}
                >
                  {pct}% du plafond
                  <div className="text-[9px] font-normal mt-0.5" style={{ color: 'var(--text-muted)' }}>
                    {amt.toLocaleString('fr-FR')} ∞ · 7j
                  </div>
                </button>
              );
            })}
          </div>
          <p className="text-[9px] italic mb-0" style={{ color: 'var(--text-muted)' }}>
            Clic = prêt instantané, durée 7 jours. Intérêts appliqués par la banque.
          </p>
        </div>
      )}

      {/* Phase 4 (2026-04-20) — Panneau Blanchiment */}
      {launderStatus && (
        <div className="mb-3 p-2 rounded-lg" style={{ background: 'rgba(22,163,74,0.08)', border: '1px solid rgba(22,163,74,0.3)' }}>
          <div className="flex items-center justify-between mb-1.5">
            <p className="text-[10px] font-bold" style={{ color: '#86efac' }}>
              💰 BLANCHIMENT {launderStatus.is_owned_bank ? '(votre banque — gratuit)' : '(NPC — 8%)'}
            </p>
            <button type="button" className="text-[9px]" style={{ color: '#86efac' }}
              onClick={() => setShowLaunder(!showLaunder)}>
              {showLaunder ? '▼' : '▶'}
            </button>
          </div>
          <p className="text-[10px] mb-1" style={{ color: 'var(--text-secondary)' }}>
            Restant cette semaine : <b style={{ color: '#86efac' }}>{launderStatus.remaining.toLocaleString('fr-FR')} ∞</b> / {launderStatus.cap.toLocaleString('fr-FR')}
          </p>
          {showLaunder && launderStatus.remaining > 0 && (
            <div className="flex gap-1 mt-2">
              <input type="number" value={launderAmount} onChange={(e) => setLaunderAmount(e.target.value)}
                placeholder="∞ shadow à blanchir" min={100} max={launderStatus.remaining}
                className="flex-1 py-1 px-2 rounded text-[10px]"
                style={{ background: 'var(--bg-tertiary)', border: '1px solid var(--border-dark)', color: 'var(--text-primary)' }} />
              <button type="button" className="new-order" style={{ fontSize: 9, padding: '3px 8px' }}
                onClick={doLaunder} disabled={busy}>
                Blanchir
              </button>
            </div>
          )}
        </div>
      )}

      <p className="text-[9px] font-bold mb-1" style={{ color: 'var(--text-muted)', letterSpacing: '.1em' }}>
        OU MONTANT PERSONNALISÉ
      </p>
      <div className="flex gap-1 mb-2">
        <input type="number" value={amount} onChange={(e) => setAmount(e.target.value)}
          placeholder="Montant ∞" min={100}
          className="flex-1 py-1 px-2 rounded text-[10px]"
          style={{ background: 'var(--bg-tertiary)', border: '1px solid var(--border-dark)', color: 'var(--text-primary)' }} />
        <select value={duration} onChange={(e) => setDuration(Number(e.target.value) as 1 | 7 | 30)}
          className="py-1 px-1 rounded text-[10px]"
          style={{ background: 'var(--bg-tertiary)', border: '1px solid var(--border-dark)', color: 'var(--text-primary)' }}>
          <option value={1}>1j</option>
          <option value={7}>7j</option>
          <option value={30}>30j</option>
        </select>
        <button type="button" className="new-order" style={{ fontSize: 9, padding: '3px 8px' }}
          onClick={request} disabled={busy}>
          Emprunter
        </button>
      </div>
      {loans.length > 0 && (
        <div>
          <p className="text-[9px] font-bold mb-1" style={{ color: 'var(--text-muted)' }}>
            MES PRÊTS EN COURS ({loans.length})
          </p>
          <div className="space-y-1">
            {loans.map((loan: any) => (
              <div key={loan.id} className="rounded p-1.5 text-[10px]"
                style={{ background: 'rgba(255,255,255,0.02)', border: '1px solid var(--border-dark)' }}>
                <div className="flex items-center justify-between">
                  <span>
                    <b style={{ color: 'var(--text-primary)' }}>{Number(loan.amount_owed ?? loan.amount).toLocaleString('fr-FR')} ∞</b>
                    <span className="ml-1 text-[9px]" style={{ color: 'var(--text-muted)' }}>
                      dû · échéance {loan.due_at ? new Date(loan.due_at).toLocaleDateString('fr-FR') : '—'}
                    </span>
                  </span>
                  <button type="button" className="new-order" style={{ fontSize: 9, padding: 3 }}
                    onClick={() => repay(loan.id, Number(loan.amount_owed ?? loan.amount))}
                    disabled={busy}>
                    Rembourser
                  </button>
                </div>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════════
// Phase 4 (2026-04-20) — Casino panel (blanchiment 100k/mois + historique C.A.)
// ══════════════════════════════════════════════════════════════════════
function CasinoPanel({ casinoId, isOwner }: { casinoId: string; isOwner: boolean }) {
  const [biz, setBiz] = useState<any | null>(null);
  const [history, setHistory] = useState<any[]>([]);
  const [amount, setAmount] = useState('');
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    (async () => {
      try {
        const h = await api.casino.history(casinoId);
        setHistory(Array.isArray(h) ? h : []);
        const m = await api.casino.mine().catch(() => null);
        if (m?.id === casinoId) setBiz(m);
      } catch { /* silent */ }
    })();
  }, [casinoId]);

  const doLaunder = async () => {
    const amt = Math.round(Number(amount));
    if (!Number.isFinite(amt) || amt < 100) return alert('Montant minimum 100 ∞ shadow');
    setBusy(true);
    try {
      const r = await api.casino.launder(casinoId, amt);
      alert(`Blanchi : ${r.credited.toLocaleString('fr-FR')} ∞ light. Mensuel restant : ${r.monthly_remaining.toLocaleString('fr-FR')} ∞.`);
      setAmount('');
      const m = await api.casino.mine();
      if (m) setBiz(m);
    } catch (e: any) { alert(e?.message || 'Refusé'); }
    finally { setBusy(false); }
  };

  if (!isOwner) {
    return (
      <div className="p-3 rounded-xl" style={{ background: 'rgba(220,38,38,0.06)', border: '1px solid rgba(220,38,38,0.2)' }}>
        <p className="text-xs font-bold" style={{ color: '#dc2626' }}>🎰 Casino</p>
        <p className="text-[10px] italic mt-1" style={{ color: 'var(--text-muted)' }}>
          Visitez et achetez ce casino pour débloquer le blanchiment gratuit (100 000 ∞/mois).
        </p>
      </div>
    );
  }

  const monthlyUsed = biz?.monthly_launder_used ?? 0;
  const monthlyCap = 100_000;
  const monthlyRemaining = Math.max(0, monthlyCap - monthlyUsed);

  return (
    <div className="p-3 rounded-xl space-y-2" style={{ background: 'rgba(220,38,38,0.08)', border: '1px solid rgba(220,38,38,0.3)' }}>
      <p className="text-xs font-bold" style={{ color: '#dc2626' }}>🎰 CASINO — {biz?.name || '...'}</p>
      <p className="text-[10px]" style={{ color: 'var(--text-secondary)' }}>
        Mensuel disponible : <b style={{ color: '#fca5a5' }}>{monthlyRemaining.toLocaleString('fr-FR')} ∞</b> / {monthlyCap.toLocaleString('fr-FR')}
      </p>
      {monthlyRemaining > 0 && (
        <div className="flex gap-1">
          <input type="number" value={amount} onChange={(e) => setAmount(e.target.value)}
            placeholder="∞ shadow" min={100} max={monthlyRemaining}
            className="flex-1 py-1 px-2 rounded text-[10px]"
            style={{ background: 'var(--bg-tertiary)', border: '1px solid var(--border-dark)', color: 'var(--text-primary)' }} />
          <button type="button" className="new-order" style={{ fontSize: 10, padding: '4px 10px' }}
            onClick={doLaunder} disabled={busy}>
            Blanchir (gratuit)
          </button>
        </div>
      )}
      {history.length > 0 && (
        <div>
          <p className="text-[9px] font-bold mt-2 mb-1" style={{ color: '#fca5a5' }}>C.A. 30 DERNIERS JOURS</p>
          <div className="max-h-32 overflow-y-auto space-y-0.5 text-[9px]" style={{ color: 'var(--text-muted)' }}>
            {history.slice(-30).reverse().map((h, i) => (
              <div key={i} className="flex justify-between">
                <span>{h.date}</span>
                <span>
                  <span style={{ color: '#86efac' }}>+{h.gross}</span>
                  {' − '}
                  <span style={{ color: '#fca5a5' }}>{h.costs}</span>
                  {' = '}
                  <b style={{ color: h.net >= 0 ? '#86efac' : '#fca5a5' }}>{h.net >= 0 ? '+' : ''}{h.net}</b>
                </span>
              </div>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════════
// Phase 5 (2026-04-20) — Association panel (don vs chaleur)
// ══════════════════════════════════════════════════════════════════════
function AssociationPanel({ businessId, associationType }: { businessId: string; associationType: string }) {
  const [canDonate, setCanDonate] = useState<boolean | null>(null);
  const [reduction, setReduction] = useState(5);
  const [busy, setBusy] = useState(false);

  const priceByType: Record<string, number> = {
    association_caritative: 5_500,
    association_ecologique: 5_800,
    association_sociale:    6_500,
  };
  const labelByType: Record<string, string> = {
    association_caritative: 'Caritative',
    association_ecologique: 'Écologique',
    association_sociale:    'Sociale',
  };

  useEffect(() => {
    (async () => {
      try {
        const r = await api.association.canDonate(businessId);
        setCanDonate(r?.can_donate ?? false);
      } catch { setCanDonate(false); }
    })();
  }, [businessId]);

  const price = priceByType[associationType] ?? 0;
  const totalCost = reduction * price;

  const doDonate = async () => {
    if (!confirm(`Donner ${totalCost.toLocaleString('fr-FR')} ∞ pour retirer ${reduction} pt(s) de chaleur ?`)) return;
    setBusy(true);
    try {
      const r = await api.association.donate(businessId, reduction);
      alert(`Don effectué : ${r.amount.toLocaleString('fr-FR')} ∞ → −${r.heat_reduction} chaleur`);
      setCanDonate(false);
    } catch (e: any) { alert(e?.message || 'Refusé'); }
    finally { setBusy(false); }
  };

  return (
    <div className="p-3 rounded-xl space-y-2" style={{ background: 'rgba(225,29,72,0.06)', border: '1px solid rgba(225,29,72,0.3)' }}>
      <p className="text-xs font-bold" style={{ color: '#fb7185' }}>❤ Association {labelByType[associationType] || '...'}</p>
      <p className="text-[10px]" style={{ color: 'var(--text-secondary)' }}>
        Tarif : <b>{price.toLocaleString('fr-FR')} ∞</b> / pt chaleur · max 20 pts · 1 don/semaine
      </p>
      {canDonate === false ? (
        <p className="text-[10px] italic" style={{ color: 'var(--text-muted)' }}>
          Vous avez déjà fait un don cette semaine (ou feature verrouillée — terminez la mission dédiée).
        </p>
      ) : (
        <>
          <div className="flex items-center gap-2">
            <input type="range" min={1} max={20} value={reduction}
              onChange={(e) => setReduction(Number(e.target.value))}
              className="flex-1" />
            <span className="text-[11px] font-bold" style={{ color: '#fb7185', minWidth: 40, textAlign: 'right' }}>
              −{reduction} pt
            </span>
          </div>
          <p className="text-[10px]" style={{ color: 'var(--text-secondary)' }}>
            Coût : <b style={{ color: 'var(--color-gold-light)' }}>{totalCost.toLocaleString('fr-FR')} ∞</b>
          </p>
          <button type="button" className="new-order w-full" style={{ fontSize: 10, padding: '4px 8px' }}
            onClick={doDonate} disabled={busy}>
            Faire un don
          </button>
        </>
      )}
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════════
// Phase 3 (2026-04-20) — Dealership panel (concessionnaire)
// ══════════════════════════════════════════════════════════════════════
function DealershipPanel({ dealershipId }: { dealershipId: string }) {
  const [stock, setStock] = useState<any[]>([]);
  const [dealership, setDealership] = useState<any | null>(null);
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    (async () => {
      try {
        const mine = await api.dealership.mine().catch(() => null);
        if (mine?.dealership?.id === dealershipId) {
          setDealership(mine.dealership);
          setStock(Array.isArray(mine.stock) ? mine.stock : []);
        } else {
          const s = await api.dealership.stock(dealershipId);
          setStock(Array.isArray(s) ? s : []);
        }
      } catch { /* silent */ }
    })();
  }, [dealershipId]);

  const buy = async (stockId: string, price: number, name: string) => {
    if (!confirm(`Acheter ${name} pour ${price.toLocaleString('fr-FR')} ∞ ?`)) return;
    setBusy(true);
    try {
      const r = await api.dealership.buy(dealershipId, stockId);
      alert(`${name} acheté (${r.price.toLocaleString('fr-FR')} ∞) !`);
      setStock(s => s.filter(x => x.id !== stockId));
    } catch (e: any) { alert(e?.message || 'Refusé'); }
    finally { setBusy(false); }
  };

  return (
    <div className="p-3 rounded-xl space-y-2" style={{ background: 'rgba(71,85,105,0.12)', border: '1px solid rgba(71,85,105,0.35)' }}>
      <p className="text-xs font-bold" style={{ color: '#cbd5e1' }}>🚗 Concessionnaire</p>
      {dealership && (
        <p className="text-[10px]" style={{ color: 'var(--text-secondary)' }}>
          Gérant : <b>{dealership.gerant_name}</b>
          {dealership.total_revenue > 0 && (
            <> · C.A. total : <b style={{ color: 'var(--color-gold-light)' }}>{Number(dealership.total_revenue).toLocaleString('fr-FR')} ∞</b></>
          )}
        </p>
      )}
      {stock.length === 0 ? (
        <p className="text-[10px] italic" style={{ color: 'var(--text-muted)' }}>Stock épuisé — rafraîchi chaque lundi.</p>
      ) : (
        <div className="space-y-1.5">
          {stock.map(s => (
            <div key={s.id} className="flex items-center justify-between p-2 rounded-lg"
              style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.08)' }}>
              <div className="min-w-0 flex-1">
                <p className="text-[11px] font-bold truncate" style={{ color: 'var(--text-primary)' }}>{s.vehicle_name}</p>
                <p className="text-[9px]" style={{ color: 'var(--text-muted)' }}>{s.vehicle_type}</p>
              </div>
              <div className="flex items-center gap-2 ml-2">
                <span className="text-[11px] font-bold" style={{ color: 'var(--color-gold)' }}>
                  {Number(s.price_light).toLocaleString('fr-FR')} ∞
                </span>
                <button type="button"
                  onClick={() => buy(s.id, s.price_light, s.vehicle_name)}
                  disabled={busy}
                  className="px-2 py-1 rounded text-[10px] font-bold disabled:opacity-50"
                  style={{ background: 'rgba(212,168,67,0.2)', border: '1px solid rgba(212,168,67,0.5)', color: 'var(--color-gold)' }}>
                  Acheter
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════════
// Phase 3 (2026-04-20) — Garage Auto (repair) & Carrosserie (paint)
// Panneau commun avec mode passé en prop : 'garage' ou 'carrosserie'.
// ══════════════════════════════════════════════════════════════════════
function VehicleServicePanel({ businessId, mode, pricePerHp }: {
  businessId: string;
  mode: 'garage' | 'carrosserie';
  pricePerHp?: number;  // 5 pour garage, 6000 pour carrosserie (chaleur pt)
}) {
  const [vehicles, setVehicles] = useState<any[]>([]);
  const [selectedVehicle, setSelectedVehicle] = useState<string | null>(null);
  const [amount, setAmount] = useState(10);
  const [busy, setBusy] = useState(false);

  useEffect(() => {
    (async () => {
      try {
        const v = await api.property.vehicles.list();
        setVehicles(Array.isArray(v) ? v : []);
      } catch { /* silent */ }
    })();
  }, []);

  const selected = vehicles.find((v: any) => v.id === selectedVehicle);
  const maxAmount = mode === 'garage' ? Math.max(1, 100 - (selected?.condition ?? 100)) : 10;
  const effectivePrice = mode === 'garage'
    ? (pricePerHp ?? 5) * Math.min(amount, maxAmount)
    : 6000 * Math.min(amount, maxAmount);

  const execute = async () => {
    if (!selectedVehicle) return alert('Sélectionnez un véhicule');
    const clampedAmount = Math.min(amount, maxAmount);
    if (clampedAmount < 1) return alert('Rien à faire');
    if (!confirm(`${mode === 'garage' ? 'Réparer' : 'Repeindre'} ${selected?.name} : ${clampedAmount} ${mode === 'garage' ? 'HP' : 'pt chaleur'} pour ${effectivePrice.toLocaleString('fr-FR')} ∞ ?`)) return;

    setBusy(true);
    try {
      const r: any = await api.mapAction.executeAction({
        action_code: mode === 'garage' ? 'repair_vehicle' : 'paint_vehicle',
        target_type: 'business',
        target_id: businessId,
        params: mode === 'garage'
          ? { vehicle_id: selectedVehicle, hp_to_repair: clampedAmount }
          : { vehicle_id: selectedVehicle, heat_reduction: clampedAmount },
      });
      if (r?.success) {
        alert(r.message || 'OK');
        // Refresh véhicules
        const v = await api.property.vehicles.list();
        setVehicles(Array.isArray(v) ? v : []);
      } else alert(r?.message || 'Refusé');
    } catch (e: any) { alert(e?.message || 'Erreur'); }
    finally { setBusy(false); }
  };

  const title = mode === 'garage' ? '🔧 Garage Auto' : '🎨 Carrosserie';
  const unit = mode === 'garage' ? 'HP' : 'pt chaleur';
  const bg = mode === 'garage' ? 'rgba(100,116,139,0.12)' : 'rgba(100,116,139,0.15)';

  return (
    <div className="p-3 rounded-xl space-y-2" style={{ background: bg, border: '1px solid rgba(100,116,139,0.4)' }}>
      <p className="text-xs font-bold" style={{ color: '#cbd5e1' }}>{title}</p>
      {vehicles.length === 0 ? (
        <p className="text-[10px] italic" style={{ color: 'var(--text-muted)' }}>Aucun véhicule. Achetez-en un chez un concessionnaire.</p>
      ) : (
        <>
          <select value={selectedVehicle || ''} onChange={(e) => setSelectedVehicle(e.target.value || null)}
            className="w-full py-1.5 px-2 rounded-lg text-[11px]"
            style={{ background: 'var(--bg-tertiary)', border: '1px solid var(--border-dark)', color: 'var(--text-primary)' }}>
            <option value="">— Sélectionnez un véhicule —</option>
            {vehicles.map((v: any) => (
              <option key={v.id} value={v.id}>
                {v.name} ({v.condition ?? 100} HP){mode === 'garage' && v.condition >= 100 ? ' — parfait' : ''}
              </option>
            ))}
          </select>

          {selectedVehicle && maxAmount > 0 && (
            <>
              <div className="flex items-center gap-2">
                <input type="range" min={1} max={maxAmount} value={Math.min(amount, maxAmount)}
                  onChange={(e) => setAmount(Number(e.target.value))}
                  className="flex-1" />
                <span className="text-[11px] font-bold" style={{ color: '#cbd5e1', minWidth: 55, textAlign: 'right' }}>
                  {Math.min(amount, maxAmount)} {unit}
                </span>
              </div>
              <p className="text-[10px]" style={{ color: 'var(--text-secondary)' }}>
                Coût : <b style={{ color: 'var(--color-gold-light)' }}>{effectivePrice.toLocaleString('fr-FR')} ∞</b>
              </p>
              <button type="button" className="new-order w-full" style={{ fontSize: 10, padding: '4px 8px' }}
                onClick={execute} disabled={busy}>
                {mode === 'garage' ? 'Réparer' : 'Repeindre'}
              </button>
            </>
          )}
          {selectedVehicle && maxAmount <= 0 && mode === 'garage' && (
            <p className="text-[10px] italic" style={{ color: '#86efac' }}>Véhicule en parfait état.</p>
          )}
        </>
      )}
    </div>
  );
}

// ══════════════════════════════════════════════════════════════════════
// Phase 7 (2026-04-20) — Méditation lieu de culte + citation
// ══════════════════════════════════════════════════════════════════════
const RELIGIOUS_QUOTES_FRONT: Array<{ tradition: string; reference: string; text: string; commentary: string; religion: string | null }> = [
  { tradition: 'Christianisme', religion: 'christian', reference: 'Évangile selon Luc, 15:24 — Parabole du Fils prodigue', text: 'Mon fils que voici était mort, et il est revenu à la vie ; il était perdu, et il est retrouvé.', commentary: 'Le père accueille le fils qui a tout dilapidé, sans reproche. La porte reste ouverte, même après la chute.' },
  { tradition: 'Islam (soufisme)', religion: 'muslim', reference: 'Rûmî, Mathnawî, Livre I (v. 3150-3227), XIIIᵉ siècle', text: 'Ne détourne pas la tête. Continue à regarder l\'endroit meurtri. C\'est là que la lumière entre en toi.', commentary: 'La blessure n\'est pas à cacher : c\'est elle qui laisse passer le rachat.' },
  { tradition: 'Taoïsme', religion: 'taoist', reference: 'Lao Tseu, Tao Tö King, chapitre 27', text: 'Le sage sait toujours sauver les hommes, c\'est pourquoi il n\'abandonne personne. L\'homme bon est le maître du mauvais ; le mauvais est la matière première du bon.', commentary: 'Personne n\'est à jeter, même le pire sert à réveiller le meilleur.' },
  { tradition: 'Bouddhisme', religion: 'buddhist', reference: 'Dhammapada, verset 173', text: 'Celui dont les mauvaises actions sont recouvertes par les bonnes illumine ce monde comme la lune libérée des nuages.', commentary: 'Verset prononcé par le Bouddha à propos d\'Angulimâla, brigand devenu saint.' },
  { tradition: 'Hindouisme', religion: 'hindu', reference: 'Bhagavad-Gîtâ, chant IV, verset 36', text: 'Serais-tu le plus coupable de tous les coupables, tu traverseras encore l\'océan du mal sur la barque de la connaissance.', commentary: 'Aucune faute n\'est trop lourde pour être traversée ; le savoir de soi est la barque.' },
  { tradition: 'Shintoïsme', religion: 'shinto', reference: 'Sokyo Ono, Shintō: The Kami Way, 1962', text: 'Le miroir possède une lumière pure qui reflète toute chose telle qu\'elle est ; il symbolise l\'esprit sans tache.', commentary: 'La rédemption passe par harae : se regarder sans fard pour se laver de la souillure.' },
  { tradition: 'Sikhisme', religion: 'sikh', reference: 'Guru Nanak, Sri Guru Granth Sahib', text: 'L\'ascèse, c\'est rester pur au milieu des impuretés.', commentary: 'La rédemption n\'est pas fuite du monde, mais tenue juste dans le monde impur.' },
  { tradition: 'Philosophie antique', religion: null, reference: 'Platon, Apologie de Socrate, 38a (~399 av. J.-C.)', text: 'Une vie sans examen ne mérite pas d\'être vécue.', commentary: 'Premier pas de toute rédemption : s\'arrêter et se regarder.' },
  { tradition: 'Philosophie moderne', religion: null, reference: 'Albert Camus, L\'Été, « Retour à Tipasa », 1954', text: 'Au milieu de l\'hiver, j\'apprenais enfin qu\'il y avait en moi un été invincible.', commentary: 'La force de renaître ne vient pas d\'ailleurs ; elle dormait, intacte, sous la glace.' },
];

function MeditationPanel({ poiId, poiName }: { poiId: string; poiName: string }) {
  const [busy, setBusy] = useState(false);

  // Extrait la religion du nom (convention seeds : "Basilique (christian)")
  const religionMatch = poiName.match(/\(([a-z]+)\)$/);
  const religion = religionMatch ? religionMatch[1] : null;
  const quote = useMemo(() => {
    const matches = religion ? RELIGIOUS_QUOTES_FRONT.filter(q => q.religion === religion) : [];
    const pool = matches.length > 0 ? matches : RELIGIOUS_QUOTES_FRONT;
    return pool[Math.floor(Math.random() * pool.length)];
  }, [religion]);

  const start = async () => {
    if (!confirm('Partir méditer 8h ? Aucune autre action possible pendant ce temps. −1 chaleur à la fin.')) return;
    setBusy(true);
    try {
      const r: any = await api.mapAction.executeAction({
        action_code: 'meditate',
        target_type: 'infrastructure',
        target_id: poiId,
      });
      alert(r?.message || 'Méditation commencée');
    } catch (e: any) { alert(e?.message || 'Refusé'); }
    finally { setBusy(false); }
  };

  return (
    <div className="p-3 rounded-xl space-y-2" style={{ background: 'rgba(212,168,67,0.1)', border: '1px solid rgba(212,168,67,0.3)' }}>
      <p className="text-xs font-bold" style={{ color: 'var(--color-gold)' }}>🕊 Lieu de culte — {quote.tradition}</p>
      <blockquote className="text-[11px] italic border-l-2 pl-2" style={{ borderColor: 'var(--color-gold)', color: 'var(--text-primary)' }}>
        « {quote.text} »
      </blockquote>
      <p className="text-[9px]" style={{ color: 'var(--text-muted)' }}>— {quote.reference}</p>
      <p className="text-[10px] italic" style={{ color: 'var(--text-secondary)' }}>{quote.commentary}</p>
      <button type="button" className="new-order w-full" style={{ fontSize: 10, padding: '4px 8px' }}
        onClick={start} disabled={busy}>
        Aller méditer (8 h)
      </button>
    </div>
  );
}

// ────────────────────────────────────────────────────────────────
// Phase 16 (2026-04-21) — Commerce stock (Caviste/Biergarten/Bar) : Commander/Importer
// ────────────────────────────────────────────────────────────────
function CommerceStockPanel({ businessId }: { businessId: string }) {
  const [stock, setStock] = useState<any>(null);
  const [qty, setQty] = useState(10);
  const [busy, setBusy] = useState(false);

  const refresh = useCallback(async () => {
    try { setStock(await apiFetch<any>(`/api/business/${businessId}/stock`)); } catch { setStock(null); }
  }, [businessId]);
  useEffect(() => { refresh(); }, [refresh]);

  if (!stock) return null;
  const fillPct = stock.storage_capacity_kg > 0
    ? Math.round((stock.current_stock_kg / stock.storage_capacity_kg) * 100)
    : 0;
  const unitCost = stock.price_per_kg * qty;

  const order = async () => {
    setBusy(true);
    try {
      const r: any = await apiFetch(`/api/business/${businessId}/stock/order`, {
        method: 'POST', body: JSON.stringify({ quantity_kg: qty }),
      });
      alert(r?.message || 'Commande envoyée');
      await refresh();
    } catch (e: any) { alert(e?.message || 'Refusé'); }
    finally { setBusy(false); }
  };

  return (
    <div className="p-3 rounded-xl space-y-2" style={{ background: 'rgba(124,45,18,0.1)', border: '1px solid rgba(124,45,18,0.4)' }}>
      <p className="text-xs font-bold" style={{ color: '#fb923c' }}>🍷 Stock {stock.unit_name}</p>
      <div className="flex items-center justify-between text-[11px]">
        <span style={{ color: 'var(--text-secondary)' }}>
          <b style={{ color: 'var(--text-primary)' }}>{stock.current_stock_kg}</b> / {stock.storage_capacity_kg} kg
        </span>
        <span style={{ color: fillPct < 30 ? '#ef4444' : fillPct < 70 ? '#f59e0b' : '#22c55e' }}>{fillPct}%</span>
      </div>
      <div className="h-1.5 rounded overflow-hidden" style={{ background: 'rgba(0,0,0,0.3)' }}>
        <div className="h-full" style={{ width: `${fillPct}%`, background: fillPct < 30 ? '#ef4444' : fillPct < 70 ? '#f59e0b' : '#22c55e' }} />
      </div>
      {stock.current_stock_kg === 0 && (
        <p className="text-[10px] italic" style={{ color: '#ef4444' }}>
          ⚠ Sans stock, le commerce ne génère aucun revenu.
        </p>
      )}
      <div className="flex items-center gap-2">
        <input
          type="number"
          min={1}
          max={stock.storage_capacity_kg - stock.current_stock_kg}
          value={qty}
          onChange={(e) => setQty(Math.max(1, Math.min(stock.storage_capacity_kg - stock.current_stock_kg, Number(e.target.value) || 1)))}
          className="w-20 px-2 py-1 text-[11px] rounded"
          style={{ background: 'rgba(255,255,255,0.03)', color: 'var(--text-primary)', border: '1px solid var(--border-dark)' }}
        />
        <span className="text-[10px]" style={{ color: 'var(--text-muted)' }}>kg × {stock.price_per_kg} ∞ =</span>
        <span className="text-[11px] font-bold" style={{ color: 'var(--color-gold)' }}>
          {unitCost.toLocaleString('fr-FR')} ∞
        </span>
      </div>
      <button
        type="button"
        className="new-order w-full"
        style={{ fontSize: 10, padding: '4px 8px' }}
        onClick={order}
        disabled={busy || qty <= 0 || qty > stock.storage_capacity_kg - stock.current_stock_kg}
      >
        {busy ? '…' : `🛒 Commander ${qty} kg`}
      </button>
      {/* Phase 8.10 (2026-04-29) — Modal "Importer depuis…" : sources owned
          du même type avec stock>0, distance + coût transport carburant. */}
      <ImportStockButton businessId={businessId} onAfterImport={refresh} />
    </div>
  );
}

interface ImportSource {
  id: string;
  name: string;
  type: string;
  current_stock_kg: number;
  distance_km: number;
  transport_cost: number;
}

interface ImportOptions {
  destination: { id: string; name: string; capacity_left_kg: number };
  sources: ImportSource[];
}

function ImportStockButton({ businessId, onAfterImport }: {
  businessId: string;
  onAfterImport: () => Promise<void> | void;
}) {
  const [open, setOpen] = useState(false);
  const [options, setOptions] = useState<ImportOptions | null>(null);
  const [loading, setLoading] = useState(false);
  const [selected, setSelected] = useState<string | null>(null);
  const [qty, setQty] = useState(1);
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const load = useCallback(async () => {
    setLoading(true);
    setError(null);
    try {
      const r = await apiFetch<ImportOptions>(`/api/business/${businessId}/stock/import-options`);
      setOptions(r);
    } catch (e: any) {
      setError(e?.message || 'Erreur chargement sources');
    } finally {
      setLoading(false);
    }
  }, [businessId]);

  const onOpen = () => {
    setOpen(true);
    setSelected(null);
    setQty(1);
    load();
  };

  const onConfirm = async () => {
    if (!selected) return;
    setBusy(true);
    setError(null);
    try {
      const r: any = await apiFetch(`/api/business/${businessId}/stock/import`, {
        method: 'POST',
        body: JSON.stringify({ quantity_kg: qty, source_business_id: selected }),
      });
      alert(r?.message || 'Transfert effectué');
      await onAfterImport();
      setOpen(false);
    } catch (e: any) {
      setError(e?.message || 'Refusé');
    } finally {
      setBusy(false);
    }
  };

  const selectedSource = options?.sources.find((s) => s.id === selected) || null;
  const maxQty = selectedSource
    ? Math.min(selectedSource.current_stock_kg, options?.destination.capacity_left_kg ?? 0)
    : 0;

  return (
    <>
      <button
        type="button"
        onClick={onOpen}
        className="w-full mt-2 py-1.5 text-[10px] font-bold uppercase tracking-[.08em] rounded"
        style={{
          background: 'rgba(124,45,18,0.18)',
          color: '#fb923c',
          border: '1px solid rgba(124,45,18,0.5)',
        }}
      >
        🚚 Importer depuis un de mes commerces
      </button>

      {open && createPortal(
        <div
          className="fixed inset-0 z-[2000] flex items-center justify-center p-4"
          style={{ background: 'rgba(0,0,0,0.78)' }}
          onClick={() => { if (!busy) setOpen(false); }}
        >
          <div
            className="rounded-xl w-full max-w-md p-4 space-y-3"
            style={{ background: 'var(--bg-panel)', border: '1px solid var(--color-gold)' }}
            onClick={(e) => e.stopPropagation()}
          >
            <p className="text-[12px] font-bold" style={{ color: 'var(--color-gold-light)' }}>
              Importer du stock — Transport facturé au km
            </p>

            {loading && <p className="text-[11px] italic" style={{ color: 'var(--text-muted)' }}>Chargement…</p>}
            {error && <p className="text-[11px]" style={{ color: 'var(--color-red-light)' }}>{error}</p>}

            {!loading && options && (
              <>
                <div className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
                  Destination : <b style={{ color: 'var(--text-primary)' }}>{options.destination.name}</b>
                  {' '}({options.destination.capacity_left_kg} kg libres)
                </div>

                {options.sources.length === 0 && (
                  <p className="text-[11px] italic" style={{ color: 'var(--text-muted)' }}>
                    Aucun commerce du même type avec stock disponible.
                  </p>
                )}

                {options.sources.length > 0 && (
                  <>
                    <div className="space-y-1 max-h-[200px] overflow-y-auto">
                      {options.sources.map((s) => (
                        <label
                          key={s.id}
                          className="flex items-center gap-2 p-2 rounded cursor-pointer"
                          style={{
                            background: selected === s.id ? 'rgba(212,168,67,0.12)' : 'rgba(255,255,255,0.03)',
                            border: `1px solid ${selected === s.id ? 'var(--color-gold)' : 'var(--border-subtle)'}`,
                          }}
                        >
                          <input type="radio" checked={selected === s.id}
                            onChange={() => { setSelected(s.id); setQty(Math.min(s.current_stock_kg, options.destination.capacity_left_kg)); }} />
                          <div className="flex-1 min-w-0">
                            <p className="text-[11px] font-bold truncate" style={{ color: 'var(--text-primary)' }}>{s.name}</p>
                            <p className="text-[9px]" style={{ color: 'var(--text-muted)' }}>
                              {s.current_stock_kg} kg dispo · {s.distance_km.toFixed(1)} km · transport <b style={{ color: 'var(--color-gold)' }}>{s.transport_cost} ∞</b>
                            </p>
                          </div>
                        </label>
                      ))}
                    </div>

                    {selected && (
                      <div className="flex items-center gap-2">
                        <input type="number" min={1} max={maxQty} value={qty}
                          onChange={(e) => setQty(Math.max(1, Math.min(maxQty, Number(e.target.value) || 1)))}
                          className="w-24 px-2 py-1 text-[11px] rounded"
                          style={{ background: 'rgba(255,255,255,0.03)', color: 'var(--text-primary)', border: '1px solid var(--border-dark)' }} />
                        <span className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
                          kg / {maxQty} max
                        </span>
                      </div>
                    )}
                  </>
                )}

                <div className="flex gap-2">
                  <button type="button" onClick={() => setOpen(false)} disabled={busy}
                    className="flex-1 py-2 text-[10px] uppercase tracking-[.1em] font-bold rounded"
                    style={{ background: 'rgba(255,255,255,0.05)', color: 'var(--text-muted)', border: '1px solid var(--border-subtle)' }}>
                    Annuler
                  </button>
                  <button type="button" onClick={onConfirm} disabled={busy || !selected || qty <= 0}
                    className="flex-1 py-2 text-[10px] uppercase tracking-[.1em] font-bold rounded disabled:opacity-50"
                    style={{
                      background: 'linear-gradient(135deg, rgba(212,175,55,0.4), rgba(14,14,22,0.9))',
                      color: 'var(--color-gold)',
                      border: '1px solid var(--color-gold)',
                      cursor: busy ? 'wait' : 'pointer',
                    }}>
                    {busy ? '…' : 'Importer'}
                  </button>
                </div>
              </>
            )}
          </div>
        </div>,
        document.body,
      )}
    </>
  );
}

/**
 * Phase 8.11a (2026-04-29) — Panel Parking owned. Affiché dans le POI garage
 * possédé par le joueur. Liste les véhicules stockés + permet d'assigner
 * un nouveau véhicule (parmi ceux owned non encore assignés ailleurs).
 */
function ParkingPanel({ businessId }: { businessId: string }) {
  const [stored, setStored] = useState<Array<{ id: string; name: string; type: string; in_use: boolean }>>([]);
  const [available, setAvailable] = useState<Array<{ id: string; name: string; type: string; parking_business_name: string | null }>>([]);
  const [loading, setLoading] = useState(false);
  const [busy, setBusy] = useState<string | null>(null);

  const refresh = useCallback(async () => {
    setLoading(true);
    try {
      const [parkVehicles, allMine] = await Promise.all([
        api.parking.parkingVehicles(businessId),
        api.parking.myVehicles(),
      ]);
      setStored(parkVehicles);
      setAvailable(allMine.filter(v => v.parking_business_id !== businessId && !v.in_use));
    } catch {
      setStored([]);
      setAvailable([]);
    } finally {
      setLoading(false);
    }
  }, [businessId]);

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

  const onAssign = async (vehicleId: string) => {
    setBusy(vehicleId);
    try {
      await api.parking.assign(vehicleId, businessId);
      await refresh();
    } catch (e: any) {
      alert(e?.message || 'Erreur');
    } finally {
      setBusy(null);
    }
  };

  const onUnassign = async (vehicleId: string) => {
    setBusy(vehicleId);
    try {
      await api.parking.unassign(vehicleId);
      await refresh();
    } catch (e: any) {
      alert(e?.message || 'Erreur');
    } finally {
      setBusy(null);
    }
  };

  return (
    <div className="p-3 rounded-xl space-y-2" style={{ background: 'rgba(34,197,94,0.06)', border: '1px solid rgba(34,197,94,0.3)' }}>
      <p className="text-xs font-bold" style={{ color: '#86efac' }}>🅿️ Parking</p>

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

      {!loading && (
        <>
          <div>
            <p className="text-[10px] font-bold uppercase tracking-[.08em] mb-1" style={{ color: 'var(--text-secondary)' }}>
              Stockés ici ({stored.length})
            </p>
            {stored.length === 0 ? (
              <p className="text-[10px] italic" style={{ color: 'var(--text-muted)' }}>
                Aucun véhicule stocké pour le moment.
              </p>
            ) : (
              <ul className="space-y-1">
                {stored.map((v) => (
                  <li key={v.id} className="flex items-center justify-between gap-2 px-2 py-1 rounded" style={{ background: 'rgba(255,255,255,0.04)' }}>
                    <span className="text-[10px]" style={{ color: 'var(--text-primary)' }}>
                      {v.name} <span style={{ color: 'var(--text-muted)' }}>({v.type})</span>
                      {v.in_use && <span style={{ color: '#fcd34d' }}> · en route</span>}
                    </span>
                    <button type="button" onClick={() => onUnassign(v.id)} disabled={busy === v.id || v.in_use}
                      className="text-[9px] px-2 py-0.5 rounded disabled:opacity-50"
                      style={{ background: 'rgba(239,68,68,0.18)', color: '#fca5a5', border: '1px solid rgba(239,68,68,0.4)' }}>
                      Retirer
                    </button>
                  </li>
                ))}
              </ul>
            )}
          </div>

          {available.length > 0 && (
            <div>
              <p className="text-[10px] font-bold uppercase tracking-[.08em] mb-1 mt-2" style={{ color: 'var(--text-secondary)' }}>
                Disponibles ({available.length})
              </p>
              <ul className="space-y-1">
                {available.map((v) => (
                  <li key={v.id} className="flex items-center justify-between gap-2 px-2 py-1 rounded" style={{ background: 'rgba(255,255,255,0.04)' }}>
                    <span className="text-[10px]" style={{ color: 'var(--text-primary)' }}>
                      {v.name} <span style={{ color: 'var(--text-muted)' }}>({v.type})</span>
                      {v.parking_business_name && (
                        <span style={{ color: 'var(--text-muted)' }}> · ailleurs : {v.parking_business_name}</span>
                      )}
                    </span>
                    <button type="button" onClick={() => onAssign(v.id)} disabled={busy === v.id}
                      className="text-[9px] px-2 py-0.5 rounded disabled:opacity-50"
                      style={{ background: 'rgba(34,197,94,0.18)', color: '#86efac', border: '1px solid rgba(34,197,94,0.4)' }}>
                      Stocker ici
                    </button>
                  </li>
                ))}
              </ul>
            </div>
          )}
        </>
      )}
    </div>
  );
}

// ────────────────────────────────────────────────────────────────
// Phase 16 (2026-04-21) — Kiosque Media/Journal (affiche les 5 derniers blogs)
// ────────────────────────────────────────────────────────────────
function KioskMediaPanel() {
  const [posts, setPosts] = useState<Array<{ id: string; title: string; excerpt?: string; created_at: string; slug?: string }>>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    let mounted = true;
    apiFetch<any>('/api/blog/posts?limit=5')
      .then((data: any) => {
        if (!mounted) return;
        setPosts(Array.isArray(data) ? data : (data?.posts ?? []));
      })
      .catch(() => setPosts([]))
      .finally(() => { if (mounted) setLoading(false); });
    return () => { mounted = false; };
  }, []);

  return (
    <div className="p-3 rounded-xl space-y-2" style={{ background: 'rgba(245,158,11,0.1)', border: '1px solid rgba(245,158,11,0.3)' }}>
      <p className="text-xs font-bold" style={{ color: '#f59e0b' }}>📰 Media / Journal du jour</p>
      {loading && <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>Chargement…</p>}
      {!loading && posts.length === 0 && (
        <p className="text-[10px] italic" style={{ color: 'var(--text-muted)' }}>Aucune actualité pour le moment.</p>
      )}
      {!loading && posts.length > 0 && (
        <ul className="space-y-2">
          {posts.map((p) => (
            <li key={p.id} className="pb-2" style={{ borderBottom: '1px solid var(--border-dark)' }}>
              <a href={p.slug ? `/actu/${p.slug}` : '/actu'} className="text-[11px] font-bold block hover:underline" style={{ color: 'var(--text-primary)' }}>
                {p.title}
              </a>
              {p.excerpt && (
                <p className="text-[10px] mt-0.5" style={{ color: 'var(--text-secondary)', lineHeight: 1.4 }}>
                  {p.excerpt.slice(0, 120)}{p.excerpt.length > 120 ? '…' : ''}
                </p>
              )}
              <span className="text-[9px]" style={{ color: 'var(--text-muted)' }}>
                {new Date(p.created_at).toLocaleDateString('fr-FR', { day: '2-digit', month: 'short', year: 'numeric' })}
              </span>
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}
