'use client';

import { useState, useEffect } from 'react';
import { useGameStore } from '@/stores/gameStore';
import { api, apiFetch } from '@/lib/api';
import { t, tFmt } from '@/lib/i18n';
import {
  Phone as PhoneIcon, X, User, MessageSquare, ShoppingBag, Target,
  Briefcase, Battery, Signal, ChevronLeft, Wallet, Skull, Scale, Factory, HeartPulse, GraduationCap
} from 'lucide-react';
import { BrowserLightbox } from './BrowserLightbox';
// Phase 17 Phase 5 (2026-05-04) — Mount GangManagementTabs in Phone apps
// Gestion Gang / Gestion Cartel.
import { GangManagementTabs } from '@/components/gang/GangManagementTabs';

// Phase 17 Phase 5 (2026-05-04) — apps Gestion Gang/Cartel ajoutées
type PhoneScreen =
  | 'home' | 'contacts' | 'messages' | 'marketplace' | 'missions'
  | 'jobs' | 'finances' | 'judicial' | 'production' | 'health' | 'skills'
  | 'gang_management' | 'cartel_management';

type PhoneAccessMode = 'normal' | 'taulard' | 'none';

interface Contact {
  player_id: string;
  name: string;
  phone_number: string;
  is_npc: boolean;
}

interface Message {
  id: string;
  sender_id: string;
  sender?: { username?: string; character_name?: string };
  subject: string;
  content: string;
  is_read: boolean;
  created_at: string;
}

interface JobEntry {
  type: string;
  name: string;
  revenue_per_payslip: number;
  schedule?: string;
}

interface ActiveJob {
  id: string;
  type: string;
  employer_name: string;
  revenue_per_payslip: number;
  hired_at: string;
}

export function PhoneOverlay() {
  const { isPhoneOpen, setPhoneOpen, player, uiVisibility } = useGameStore();
  const [screen, setScreen] = useState<PhoneScreen>('home');
  const [browser, setBrowser] = useState<{ kind: 'listing' | 'blackmarket'; listing?: Listing } | null>(null);
  // Phase 17 Phase 5 (2026-05-04) — accès téléphone (normal | taulard | none)
  const [phoneAccess, setPhoneAccess] = useState<PhoneAccessMode>('normal');
  const [accessReason, setAccessReason] = useState<string>('');
  // Phase 17 Phase 5 — détection bras_droit gang/cartel pour afficher
  // les apps "Gestion Gang"/"Gestion Cartel" en mode normal.
  const [hasBrasDroitGang, setHasBrasDroitGang] = useState(false);
  const [hasUnderbossCartel, setHasUnderbossCartel] = useState(false);

  // Phase 17.1 (2026-05-05) — Refonte : un seul appel /phone/access qui
  // retourne déjà les drapeaux has_bras_droit_gang + has_underboss_cartel
  // calculés proprement côté backend (gating exact, pas heuristique).
  useEffect(() => {
    if (!isPhoneOpen) return;
    let cancel = false;
    (async () => {
      try {
        const access = await api.player.phoneAccess();
        if (cancel) return;
        setPhoneAccess(access.access);
        setAccessReason(access.reason);
        setHasBrasDroitGang(!!access.has_bras_droit_gang);
        setHasUnderbossCartel(!!access.has_underboss_cartel);
      } catch {
        if (!cancel) {
          setPhoneAccess('normal');
          setAccessReason('');
          setHasBrasDroitGang(false);
          setHasUnderbossCartel(false);
        }
      }
    })();
    return () => { cancel = true; };
  }, [isPhoneOpen]);

  if (!isPhoneOpen || !uiVisibility.phone) return null;

  // Phase 17 Phase 5 — Si téléphone confisqué (none), afficher un lock screen
  // au lieu du contenu normal. L'utilisateur ferme avec X.
  if (phoneAccess === 'none') {
    return (
      <div className="fixed inset-0 z-[2000] flex items-center justify-end pr-6 pointer-events-none">
        <div className="absolute inset-0 pointer-events-auto" style={{ background: 'rgba(0,0,0,0.3)' }} onClick={() => setPhoneOpen(false)} />
        <div className="relative w-[300px] h-[560px] rounded-[2rem] overflow-hidden pointer-events-auto flex flex-col items-center justify-center p-6 text-center"
          style={{ background: 'linear-gradient(180deg, #1a1a2e 0%, #0f0f1a 100%)', border: '3px solid #333' }}>
          <PhoneIcon size={42} style={{ color: 'var(--color-red-light)', opacity: 0.5 }} />
          <p className="mt-4 text-sm font-bold" style={{ color: 'var(--text-primary)' }}>
            Téléphone confisqué
          </p>
          <p className="mt-2 text-[11px] leading-relaxed" style={{ color: 'var(--text-muted)' }}>
            {accessReason || 'Tu ne peux pas accéder à ton téléphone pour le moment.'}
          </p>
          <button onClick={() => setPhoneOpen(false)}
            className="mt-6 px-4 py-2 rounded text-[10px]"
            style={{ background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.08)', color: 'var(--text-secondary)' }}>
            Fermer
          </button>
        </div>
      </div>
    );
  }

  // Phase 17 Phase 5 — Mode taulard : badge "MiniKom P1" + apps réduites
  // (Contacts / Marché Noir / Gestion Gang / Gestion Cartel).
  const isTaulard = phoneAccess === 'taulard';

  return (
    <div className="fixed inset-0 z-[2000] flex items-center justify-end pr-6 pointer-events-none">
      {/* Backdrop */}
      <div
        className="absolute inset-0 pointer-events-auto"
        style={{ background: 'rgba(0,0,0,0.3)' }}
        onClick={() => setPhoneOpen(false)}
      />

      {/* Phone body */}
      <div
        className="relative w-[300px] h-[560px] rounded-[2rem] overflow-hidden pointer-events-auto flex flex-col"
        style={{
          background: 'linear-gradient(180deg, #1a1a2e 0%, #0f0f1a 100%)',
          border: '3px solid #333',
          boxShadow: '0 20px 60px rgba(0,0,0,0.5), inset 0 0 30px rgba(212,168,67,0.05)',
        }}
      >
        {/* Status bar */}
        <div className="flex items-center justify-between px-5 pt-3 pb-1">
          <span className="text-[10px] font-mono" style={{ color: 'var(--text-muted)' }}>
            {new Date().toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' })}
          </span>
          <span className="text-[10px] font-bold" style={{ color: 'var(--color-gold)' }}>
            BrikFon
          </span>
          <div className="flex items-center gap-1">
            <Signal size={10} style={{ color: 'var(--text-muted)' }} />
            <Battery size={10} style={{ color: '#22c55e' }} />
          </div>
        </div>

        {/* Screen content */}
        <div className="relative flex-1 overflow-y-auto px-4 py-2">
          {screen === 'home' && (
            <HomeScreen
              onNavigate={setScreen}
              onOpenBlackMarket={() => setBrowser({ kind: 'blackmarket' })}
              showBlackMarket={uiVisibility.marche_noir}
              showJudicial={uiVisibility.casier_judiciaire}
              showProduction={uiVisibility.production}
              phoneModelName={isTaulard ? 'MiniKom P1' : player?.phone_model_name}
              isTaulard={isTaulard}
              showGangManagement={hasBrasDroitGang}
              showCartelManagement={hasUnderbossCartel}
            />
          )}
          {screen === 'contacts' && <ContactsScreen contacts={player?.contacts || []} />}
          {screen === 'messages' && <MessagesScreen playerId={player?.id} />}
          {screen === 'marketplace' && (
            <MarketplaceScreen onOpenListing={(listing) => setBrowser({ kind: 'listing', listing })} />
          )}
          {screen === 'missions' && <PhoneMissionsScreen />}
          {screen === 'jobs' && <JobsScreen playerId={player?.id} />}
          {screen === 'finances' && <FinancesScreen />}
          {screen === 'judicial' && <JudicialScreen />}
          {screen === 'production' && <ProductionScreen />}
          {screen === 'health' && <HealthScreen />}
          {screen === 'skills' && <SkillsScreen />}
          {/* Phase 17 Phase 5 (2026-05-04) — Apps Gestion Gang/Cartel */}
          {/* Phase 17.1 (2026-05-05) — passe taulard pour restreindre
              les actions sensibles (allocation, hire/fire) en prison */}
          {screen === 'gang_management' && <GangManagementScreen taulard={isTaulard} />}
          {screen === 'cartel_management' && <CartelManagementScreen taulard={isTaulard} />}

          <BrowserLightbox
            open={!!browser}
            onClose={() => setBrowser(null)}
            position="absolute"
            title={browser?.kind === 'blackmarket' ? t('phone.blackmarket') : t('phone.marketplace')}
            address={browser?.kind === 'blackmarket'
              ? '/marche-noir'
              : browser?.listing ? `/marketplace/listing/${browser.listing.id}` : '/marketplace'}
          >
            {browser?.kind === 'listing' && browser.listing && (
              <ListingDealPanel listing={browser.listing} onClose={() => setBrowser(null)} />
            )}
            {browser?.kind === 'blackmarket' && (
              <BlackMarketPanel />
            )}
          </BrowserLightbox>
        </div>

        {/* Bottom nav */}
        <div
          className="flex items-center justify-between px-6 py-3"
          style={{ borderTop: '1px solid rgba(255,255,255,0.1)' }}
        >
          {screen !== 'home' ? (
            <button onClick={() => setScreen('home')} className="p-2 rounded-full hover:bg-white/10">
              <ChevronLeft size={18} style={{ color: 'var(--text-secondary)' }} />
            </button>
          ) : (
            <div className="w-[34px]" />
          )}
          <button
            onClick={() => setPhoneOpen(false)}
            className="w-10 h-10 rounded-full flex items-center justify-center"
            style={{ background: 'rgba(255,255,255,0.1)' }}
          >
            <X size={16} style={{ color: 'var(--text-secondary)' }} />
          </button>
          <div className="w-[34px]" />
        </div>
      </div>
    </div>
  );
}

/** Phone floating button (visible in game when phone is unlocked) */
export function PhoneButton() {
  const { setPhoneOpen, uiVisibility } = useGameStore();

  if (!uiVisibility.phone) return null;

  return (
    <button
      onClick={() => setPhoneOpen(true)}
      className="fixed bottom-6 right-6 z-40 w-14 h-14 rounded-full flex items-center justify-center shadow-xl hover:scale-110 transition-transform"
      style={{
        background: 'linear-gradient(135deg, var(--bg-tertiary), var(--bg-secondary))',
        border: '2px solid var(--border-gold)',
      }}
    >
      <PhoneIcon size={22} style={{ color: 'var(--color-gold)' }} />
    </button>
  );
}

/* ─── Screens ─── */

/**
 * FIX(story-phase8): Phone model gating.
 * BrikFon 1000/2000 → no camera, no gps, no internet → apps requiring these are locked.
 * SmartEntry S1+ → full access.
 * GhostLine → no GPS (stealth phone, untraceable).
 *
 * Mapping:
 *   - contacts, messages, jobs, health, skills, missions → toujours dispo (fonctions de base)
 *   - finances, marketplace → requires has_internet
 *   - production → requires has_internet
 *   - black market → requires has_internet
 *   - judicial/casier → toujours dispo (info publique via SMS)
 */
const PHONE_MODELS: Record<string, { has_camera: boolean; has_gps: boolean; has_internet: boolean; encryption: number }> = {
  'MiniKom P1':      { has_camera: false, has_gps: false, has_internet: false, encryption: 0 },
  'BrikFon 1000':    { has_camera: false, has_gps: false, has_internet: false, encryption: 0 },
  'BrikFon 2000':    { has_camera: false, has_gps: false, has_internet: false, encryption: 1 },
  'SmartEntry S1':   { has_camera: true,  has_gps: true,  has_internet: true,  encryption: 1 },
  'SmartEntry S2':   { has_camera: true,  has_gps: true,  has_internet: true,  encryption: 2 },
  'NexPhone Pro':    { has_camera: true,  has_gps: true,  has_internet: true,  encryption: 3 },
  'NexPhone Ultra':  { has_camera: true,  has_gps: true,  has_internet: true,  encryption: 3 },
  'GhostLine Basic': { has_camera: false, has_gps: false, has_internet: true,  encryption: 4 },
  'GhostLine Pro':   { has_camera: true,  has_gps: false, has_internet: true,  encryption: 5 },
  'GhostLine Ultra': { has_camera: true,  has_gps: true,  has_internet: true,  encryption: 5 },
};

function HomeScreen(props: {
  onNavigate: (s: PhoneScreen) => void;
  onOpenBlackMarket: () => void;
  showBlackMarket: boolean;
  showJudicial: boolean;
  showProduction: boolean;
  phoneModelName?: string;
  // Phase 17 Phase 5 (2026-05-04) — flags taulard + apps Gestion
  isTaulard?: boolean;
  showGangManagement?: boolean;
  showCartelManagement?: boolean;
}) {
  // Resolve phone capabilities from model name
  const model = PHONE_MODELS[props.phoneModelName || 'BrikFon 1000'] || PHONE_MODELS['BrikFon 1000'];

  type AppEntry = {
    id: PhoneScreen;
    icon: any;
    label: string;
    color: string;
    onClick?: () => void;
    locked?: boolean;
    lockReason?: string;
  };

  // Phase 17 Phase 5 — Mode taulard : apps réduites (Contacts, Marché Noir,
  // Gestion Gang, Gestion Cartel uniquement). Les Gestion ne sont visibles
  // que si le bras_droit/underboss est actif.
  let apps: AppEntry[];
  if (props.isTaulard) {
    apps = [
      { id: 'contacts', icon: User, label: t('phone.contacts'), color: '#22c55e' },
    ];
    if (props.showBlackMarket) {
      apps.push({
        id: 'marketplace', icon: Skull, label: t('phone.blackmarket'), color: '#ef4444',
        onClick: props.onOpenBlackMarket,
      });
    }
    if (props.showGangManagement) {
      apps.push({ id: 'gang_management', icon: Briefcase, label: 'Gestion Gang', color: '#dc2626' });
    }
    if (props.showCartelManagement) {
      apps.push({ id: 'cartel_management', icon: Scale, label: 'Gestion Cartel', color: '#d4a843' });
    }
  } else {
    apps = [
      { id: 'contacts', icon: User, label: t('phone.contacts'), color: '#22c55e' },
      { id: 'messages', icon: MessageSquare, label: t('phone.sms'), color: '#3b82f6' },
      { id: 'jobs', icon: Briefcase, label: t('phone.jobs'), color: '#8b5cf6' },
      { id: 'finances', icon: Wallet, label: t('phone.finances'), color: '#d4a843',
        locked: !model.has_internet, lockReason: 'Requires internet' },
      { id: 'health', icon: HeartPulse, label: 'Santé', color: '#ef4444' },
      { id: 'skills', icon: GraduationCap, label: 'Compétences', color: '#38bdf8' },
      { id: 'marketplace', icon: ShoppingBag, label: t('phone.marketplace'), color: '#f59e0b',
        locked: !model.has_internet, lockReason: 'Requires internet' },
      { id: 'missions', icon: Target, label: t('phone.missions'), color: '#e63946' },
    ];

    if (props.showBlackMarket) {
      apps.splice(4, 0, {
        id: 'marketplace', icon: Skull, label: t('phone.blackmarket'), color: '#ef4444',
        onClick: props.onOpenBlackMarket,
        locked: !model.has_internet, lockReason: 'Requires internet',
      });
    }

    if (props.showJudicial) {
      apps.splice(5, 0, { id: 'judicial', icon: Scale, label: 'Casier', color: '#a855f7' });
    }

    if (props.showProduction) {
      apps.splice(5, 0, {
        id: 'production', icon: Factory, label: 'Production', color: '#22c55e',
        locked: !model.has_internet, lockReason: 'Requires internet',
      });
    }

    // Phase 17 Phase 5 — Apps Gestion Gang/Cartel (mode normal aussi).
    // Visibles si bras_droit/underboss actif (passes via props).
    if (props.showGangManagement) {
      apps.push({ id: 'gang_management', icon: Briefcase, label: 'Gestion Gang', color: '#dc2626' });
    }
    if (props.showCartelManagement) {
      apps.push({ id: 'cartel_management', icon: Scale, label: 'Gestion Cartel', color: '#d4a843' });
    }
  }

  const displayName = props.phoneModelName || 'BrikFon 1000';

  return (
    <div>
      <p className="text-center text-xs mb-4" style={{ color: 'var(--text-muted)' }}>
        {displayName}
      </p>
      <div className="grid grid-cols-3 gap-3">
        {apps.map((app, idx) => {
          const Icon = app.icon;
          const isLocked = !!app.locked;
          return (
            <button
              key={`${app.label}-${idx}`}
              onClick={() => {
                if (isLocked) return;
                app.onClick ? app.onClick() : props.onNavigate(app.id);
              }}
              disabled={isLocked}
              title={isLocked ? `${app.lockReason} — ameliorez votre telephone` : app.label}
              className="flex flex-col items-center gap-1 p-3 rounded-xl transition-colors"
              style={{ opacity: isLocked ? 0.35 : 1, cursor: isLocked ? 'not-allowed' : 'pointer' }}
            >
              <div
                className="w-11 h-11 rounded-xl flex items-center justify-center"
                style={{
                  background: isLocked ? 'rgba(100,100,100,0.15)' : `${app.color}20`,
                  border: `1px solid ${isLocked ? 'rgba(100,100,100,0.3)' : `${app.color}40`}`,
                }}
              >
                <Icon size={20} style={{ color: isLocked ? '#6b7280' : app.color }} />
              </div>
              <span className="text-[9px]" style={{ color: isLocked ? '#6b7280' : 'var(--text-secondary)' }}>{app.label}</span>
            </button>
          );
        })}
      </div>
      {!model.has_internet && (
        <p className="text-[9px] text-center mt-3 italic" style={{ color: 'var(--text-muted)' }}>
          Certaines apps necessitent un smartphone avec internet.
        </p>
      )}
    </div>
  );
}

function JudicialScreen() {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [status, setStatus] = useState<any | null>(null);
  const [pardonLoading, setPardonLoading] = useState(false);

  const load = async () => {
    setLoading(true);
    setError(null);
    try {
      const res = await apiFetch<any>('/api/judicial/status');
      setStatus(res);
    } catch (e: any) {
      setError(e?.message || t('common.error'));
      setStatus(null);
    } finally {
      setLoading(false);
    }
  };

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

  const requestPardon = async () => {
    if (pardonLoading) return;
    setPardonLoading(true);
    setError(null);
    try {
      await apiFetch('/api/judicial/pardon', { method: 'POST' });
      await load();
    } catch (e: any) {
      setError(e?.message || t('common.error'));
    } finally {
      setPardonLoading(false);
    }
  };

  if (loading) {
    return <p className="text-xs text-center py-6" style={{ color: 'var(--text-muted)' }}>{t('common.loading')}</p>;
  }

  if (error) {
    return (
      <div className="text-center py-6">
        <p className="text-xs" style={{ color: 'var(--color-red)' }}>{error}</p>
        <button type="button" onClick={load} className="mt-3 px-3 py-2 rounded-lg text-xs font-bold" style={{ background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.12)', color: 'var(--text-primary)' }}>
          Réessayer
        </button>
      </div>
    );
  }

  const file = status?.file;
  const level = status?.level;
  const imprisonedUntil = status?.imprisoned_until ? new Date(status.imprisoned_until) : null;
  const records: any[] = Array.isArray(status?.records) ? status.records : [];

  return (
    <div className="space-y-3">
      <div className="p-3 rounded-xl" 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(--color-gold)' }}>Casier judiciaire</p>
        <div className="mt-2 grid grid-cols-2 gap-2">
          <div className="p-2 rounded-lg" style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)' }}>
            <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>Statut</p>
            <p className="text-[11px] font-bold" style={{ color: status?.judicial_status?.imprisoned ? 'rgba(239,68,68,0.9)' : 'var(--text-primary)' }}>{status?.judicial_status?.label || level?.name || '—'}</p>
          </div>
          <div className="p-2 rounded-lg" style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)' }}>
            <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>Points</p>
            <p className="text-[11px] font-bold" style={{ color: 'var(--text-primary)' }}>{file?.crime_points ?? 0}</p>
          </div>
          <div className="p-2 rounded-lg" style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)' }}>
            <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>Recherche</p>
            <p className="text-[11px] font-bold" style={{ color: 'var(--text-primary)' }}>{level?.name || 'Normal'}</p>
          </div>
        </div>
        {imprisonedUntil && imprisonedUntil > new Date() && (
          <p className="text-[10px] mt-2" style={{ color: 'rgba(239,68,68,0.9)' }}>
            Incarcéré jusqu’au {imprisonedUntil.toLocaleString('fr-FR')}
          </p>
        )}
        <button
          type="button"
          onClick={requestPardon}
          disabled={pardonLoading}
          className="mt-3 w-full py-2 rounded-xl text-xs 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)' }}
        >
          {pardonLoading ? 'Traitement…' : 'Demander un Pardon Officiel'}
        </button>
      </div>

      <div className="p-3 rounded-xl" style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)' }}>
        <p className="text-xs font-bold mb-2" style={{ color: 'var(--text-primary)' }}>Derniers faits</p>
        {records.length === 0 ? (
          <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>Aucun enregistrement</p>
        ) : (
          <div className="space-y-2">
            {records.slice(0, 12).map((r) => (
              <div key={r.id} className="p-2 rounded-lg" style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)' }}>
                <div className="flex items-center justify-between gap-2">
                  <p className="text-[10px] font-bold truncate" style={{ color: 'var(--text-primary)' }}>{r.crime_type}</p>
                  <div className="flex items-center gap-1">
                    {/* Phase 8.5 (2026-04-29) — Flag "Évadé" si record.evaded=true */}
                    {r.evaded && (
                      <span
                        className="px-1.5 py-0.5 rounded text-[8px] font-bold uppercase tracking-[.1em]"
                        style={{
                          background: 'rgba(239,68,68,0.22)',
                          border: '1px solid rgba(239,68,68,0.6)',
                          color: '#fca5a5',
                        }}
                        title={t('prison_phase8.casier.evaded_tooltip')}
                      >
                        {t('prison_phase8.casier.evaded_label')}
                      </span>
                    )}
                    <p className="text-[9px]" style={{ color: 'var(--text-muted)' }}>{r.crime_date ? new Date(r.crime_date).toLocaleDateString('fr-FR') : ''}</p>
                  </div>
                </div>
                {r.description && <p className="text-[9px] mt-1 truncate" style={{ color: 'var(--text-muted)' }}>{r.description}</p>}
                <div className="flex gap-2 mt-1 text-[9px]" style={{ color: 'var(--text-muted)' }}>
                  <span>{r.was_arrested ? t('prison_phase8.casier.arrested') : t('prison_phase8.casier.free')}</span>
                  <span>•</span>
                  <span>{r.was_convicted
                    ? tFmt('prison_phase8.casier.convicted_days', { days: r.sentence_days })
                    : t('prison_phase8.casier.not_convicted')}</span>
                  {r.held_added_ms != null && r.held_added_ms > 0 && (
                    <>
                      <span>•</span>
                      <span style={{ color: 'rgba(239,68,68,0.9)' }} title={t('prison_phase8.casier.held_tooltip')}>
                        {tFmt('prison_phase8.casier.held_inherited', { hours: Math.round(r.held_added_ms / 3600000) })}
                      </span>
                    </>
                  )}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </div>
  );
}

function ProductionScreen() {
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [chains, setChains] = useState<any[]>([]);
  const [batches, setBatches] = useState<any[]>([]);
  const [businesses, setBusinesses] = useState<any[]>([]);
  const [chainType, setChainType] = useState<'textile' | 'alimentaire' | 'metallurgie' | 'drogue'>('textile');
  const [productName, setProductName] = useState('');
  const [quantityKg, setQuantityKg] = useState(50);
  const [businessId, setBusinessId] = useState<string>('');
  const [starting, setStarting] = useState(false);
  const [collecting, setCollecting] = useState<string | null>(null);
  const [drugCatalog, setDrugCatalog] = useState<any[]>([]);

  const load = async () => {
    setLoading(true);
    setError(null);
    try {
      const [chainRes, batchRes, bizRes] = await Promise.all([
        apiFetch<any>('/api/production/chains'),
        apiFetch<any>('/api/production/batches'),
        api.property.businesses.list(),
      ]);
      const c = (chainRes as any)?.chains ?? [];
      setChains(Array.isArray(c) ? c : []);
      setBatches(Array.isArray(batchRes) ? batchRes : []);
      setBusinesses(Array.isArray(bizRes) ? bizRes : ((bizRes as any)?.businesses ?? []));

      const defaultBizId = (Array.isArray(bizRes) ? bizRes : ((bizRes as any)?.businesses ?? []))?.[0]?.id;
      if (!businessId && defaultBizId) setBusinessId(defaultBizId);
    } catch (e: any) {
      setError(e?.message || t('common.error'));
    } finally {
      setLoading(false);
    }
  };

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

  useEffect(() => {
    if (chainType !== 'drogue') return;
    api.player.getBlackmarketDrugs()
      .then((res: any) => setDrugCatalog(Array.isArray(res) ? res : []))
      .catch(() => setDrugCatalog([]));
  }, [chainType]);

  useEffect(() => {
    if (chainType === 'drogue') {
      const first = drugCatalog?.[0]?.name;
      if (!productName && first) setProductName(first);
      return;
    }
    const chain = chains.find((c) => c.type === chainType);
    const suggested = chain?.stages?.[0]?.output;
    if (suggested) setProductName(suggested);
  }, [chainType, chains, drugCatalog]);

  const start = async () => {
    if (starting) return;
    setStarting(true);
    setError(null);
    try {
      await apiFetch('/api/production/start', {
        method: 'POST',
        body: JSON.stringify({
          business_id: businessId,
          chain_type: chainType,
          product_name: productName,
          quantity_kg: quantityKg,
        }),
      });
      await load();
    } catch (e: any) {
      setError(e?.message || t('common.error'));
    } finally {
      setStarting(false);
    }
  };

  const collect = async (batchId: string) => {
    if (collecting) return;
    setCollecting(batchId);
    setError(null);
    try {
      await apiFetch(`/api/production/${batchId}/collect`, { method: 'POST' });
      await load();
    } catch (e: any) {
      setError(e?.message || t('common.error'));
    } finally {
      setCollecting(null);
    }
  };

  if (loading) {
    return <p className="text-xs text-center py-6" style={{ color: 'var(--text-muted)' }}>{t('common.loading')}</p>;
  }

  return (
    <div className="space-y-3">
      <div className="p-3 rounded-xl" 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(--color-gold)' }}>Production</p>
        {error && <p className="text-[10px] mt-2" style={{ color: 'var(--color-red)' }}>{error}</p>}

        <div className="mt-3 space-y-2">
          <select value={businessId} onChange={(e) => setBusinessId(e.target.value)} className="w-full px-2 py-2 rounded-lg text-xs outline-none"
            style={{ background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.10)', color: 'var(--text-primary)' }}>
            {businesses.length === 0 ? (
              <option value="">Aucun commerce</option>
            ) : (
              businesses.map((b: any) => <option key={b.id} value={b.id}>{b.name}</option>)
            )}
          </select>

          <div className="flex gap-2">
            <select value={chainType} onChange={(e) => setChainType(e.target.value as any)} className="flex-1 px-2 py-2 rounded-lg text-xs outline-none"
              style={{ background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.10)', color: 'var(--text-primary)' }}>
              <option value="textile">Textile</option>
              <option value="alimentaire">Alimentaire</option>
              <option value="metallurgie">Métallurgie</option>
              <option value="drogue">Drogue</option>
            </select>
            <input type="number" min={1} value={quantityKg} onChange={(e) => setQuantityKg(Number(e.target.value))} className="w-20 px-2 py-2 rounded-lg text-xs outline-none"
              style={{ background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.10)', color: 'var(--text-primary)' }} />
          </div>

          {chainType === 'drogue' ? (
            <select value={productName} onChange={(e) => setProductName(e.target.value)} className="w-full px-2 py-2 rounded-lg text-xs outline-none"
              style={{ background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.10)', color: 'var(--text-primary)' }}>
              {drugCatalog.map((d: any) => <option key={d.id} value={d.name}>{d.name}</option>)}
            </select>
          ) : (
            <input value={productName} onChange={(e) => setProductName(e.target.value)} className="w-full px-2 py-2 rounded-lg text-xs outline-none"
              style={{ background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.10)', color: 'var(--text-primary)' }} />
          )}

          <button type="button" disabled={starting || !businessId || !productName} onClick={start} className="w-full py-2 rounded-xl text-xs font-bold disabled:opacity-50"
            style={{ background: 'var(--color-gold)', color: '#000' }}>
            {starting ? 'Démarrage…' : 'Démarrer un lot'}
          </button>
        </div>
      </div>

      <div className="p-3 rounded-xl" style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)' }}>
        <p className="text-xs font-bold mb-2" style={{ color: 'var(--text-primary)' }}>Lots</p>
        {batches.length === 0 ? (
          <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>Aucun lot</p>
        ) : (
          <div className="space-y-2">
            {batches.slice(0, 8).map((b: any) => {
              const ready = b.stage !== 'delivered' && b.completes_at && new Date(b.completes_at) <= new Date();
              return (
                <div key={b.id} className="p-2 rounded-lg" style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)' }}>
                  <div className="flex items-center justify-between gap-2">
                    <p className="text-[10px] font-bold truncate" style={{ color: 'var(--text-primary)' }}>{b.product_name} • {b.quantity_kg}kg</p>
                    <p className="text-[9px]" style={{ color: 'var(--text-muted)' }}>{b.stage}</p>
                  </div>
                  {b.completes_at && (
                    <p className="text-[9px] mt-1" style={{ color: 'var(--text-muted)' }}>Fin: {new Date(b.completes_at).toLocaleString('fr-FR')}</p>
                  )}
                  <button type="button" disabled={!ready || collecting === b.id} onClick={() => collect(b.id)} className="mt-2 w-full py-1.5 rounded-lg text-[10px] 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)' }}>
                    {collecting === b.id ? 'Collecte…' : ready ? 'Récupérer' : 'En cours'}
                  </button>
                </div>
              );
            })}
          </div>
        )}
      </div>
    </div>
  );
}

function HealthScreen() {
  const player = useGameStore((s) => s.player);
  const gauges = useGameStore((s) => s.gauges);
  const health = useGameStore((s) => s.health);
  const balances = useGameStore((s) => s.balances);
  const setGauges = useGameStore((s) => s.setGauges);
  const setHealth = useGameStore((s) => s.setHealth);
  const setBalances = useGameStore((s) => s.setBalances);

  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [hasCareCard, setHasCareCard] = useState(false);
  const [hasDoctor, setHasDoctor] = useState(false);
  const [action, setAction] = useState<'hospital' | 'doctor' | null>(null);

  const refresh = async () => {
    if (!player?.id) return;
    setLoading(true);
    setError(null);
    try {
      const inv = await api.player.getInventory(player.id).catch(() => []);
      const items = Array.isArray(inv) ? inv : [];
      setHasCareCard(items.some((i: any) => String(i.item_subtype || '').toLowerCase() === 'carte_soin' && (i.storage_condition === 'on_person' || !i.storage_condition)));
      setHasDoctor(Array.isArray(player.contacts) && player.contacts.some((c: any) => c?.player_id === 'npc:doctor'));
    } catch (e: any) {
      setError(e?.message || t('common.error'));
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => { refresh(); }, [player?.id]);

  const syncState = async () => {
    if (!player?.id) return;
    const [g, b, h] = await Promise.all([
      api.player.getGauges(player.id).catch(() => null),
      api.player.getBalances(player.id).catch(() => null),
      // Phase 8 v2 (2026-05-01) — fetch PlayerHealth (physical_health, etc.)
      api.player.getHealth(player.id).catch(() => null),
    ]);
    if (g) setGauges(g as any);
    if (b) setBalances(b as any);
    if (h) setHealth(h as any);
  };

  const goHospital = async () => {
    if (!player?.id || action) return;
    setAction('hospital');
    setError(null);
    try {
      await api.player.hospitalHeal(player.id);
      await syncState();
      await refresh();
    } catch (e: any) {
      setError(e?.message || t('common.error'));
    } finally {
      setAction(null);
    }
  };

  const callDoctor = async () => {
    if (!player?.id || action) return;
    setAction('doctor');
    setError(null);
    try {
      await api.player.doctorCall(player.id);
      await syncState();
      await refresh();
    } catch (e: any) {
      setError(e?.message || t('common.error'));
    } finally {
      setAction(null);
    }
  };

  if (!player?.id) {
    return <p className="text-xs text-center py-6" style={{ color: 'var(--text-muted)' }}>Connexion requise</p>;
  }

  if (loading) {
    return <p className="text-xs text-center py-6" style={{ color: 'var(--text-muted)' }}>{t('common.loading')}</p>;
  }

  return (
    <div className="space-y-3">
      <div className="p-3 rounded-xl" style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)' }}>
        <p className="text-xs font-bold flex items-center gap-2" style={{ color: 'var(--color-gold)' }}>
          <HeartPulse size={16} /> Santé
        </p>

        {error && <p className="text-[10px] mt-2" style={{ color: 'var(--color-red)' }}>{error}</p>}

        <div className="mt-3 grid grid-cols-2 gap-2">
          <div className="p-2 rounded-lg" style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)' }}>
            <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>Points de vie</p>
            <p className="text-[12px] font-bold" style={{ color: 'var(--text-primary)' }}>{health?.physical_health ?? 0}/100</p>
          </div>
          <div className="p-2 rounded-lg" style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)' }}>
            <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>Infini</p>
            <p className="text-[12px] font-bold" style={{ color: 'var(--text-primary)' }}>{balances?.infinite_light ?? 0}∞</p>
          </div>
        </div>

        <div className="mt-3 space-y-2">
          <button type="button" onClick={goHospital} disabled={action !== null} className="w-full py-2 rounded-xl text-xs 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)' }}>
            {action === 'hospital' ? 'Soins…' : `Aller à l’hôpital (${hasCareCard ? 'gratuit' : '100∞'})`}
          </button>

          <button type="button" onClick={callDoctor} disabled={action !== null || !hasDoctor} className="w-full py-2 rounded-xl text-xs 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)' }}>
            {action === 'doctor' ? 'Appel…' : `Appeler le docteur (${hasCareCard ? 'gratuit' : '50∞'})`}
          </button>

          {!hasDoctor && (
            <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
              Contact docteur non obtenu.
            </p>
          )}
        </div>
      </div>
    </div>
  );
}

function SkillsScreen() {
  const player = useGameStore((s) => s.player);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [catalog, setCatalog] = useState<any[]>([]);
  const [rows, setRows] = useState<any[]>([]);

  useEffect(() => {
    if (!player?.id) return;
    setLoading(true);
    setError(null);
    Promise.all([
      api.skills.getCatalog().catch(() => ({ skills: [] })),
      api.player.getSkills(player.id).catch(() => []),
    ])
      .then(([cat, skills]) => {
        setCatalog(Array.isArray((cat as any)?.skills) ? (cat as any).skills : []);
        setRows(Array.isArray(skills) ? skills : []);
      })
      .catch((e: any) => setError(e?.message || t('common.error')))
      .finally(() => setLoading(false));
  }, [player?.id]);

  if (!player?.id) {
    return <p className="text-xs text-center py-6" style={{ color: 'var(--text-muted)' }}>Connexion requise</p>;
  }

  if (loading) {
    return <p className="text-xs text-center py-6" style={{ color: 'var(--text-muted)' }}>{t('common.loading')}</p>;
  }

  if (error) {
    return <p className="text-xs text-center py-6" style={{ color: 'var(--color-red)' }}>{error}</p>;
  }

  const byId: Record<number, any> = {};
  for (const r of rows) byId[Number(r.skill_id)] = r;

  const merged = (catalog.length ? catalog : Object.values(byId).map((r: any) => ({ id: r.skill_id, name: `Compétence ${r.skill_id}`, description: '' })))
    .map((c: any) => {
      const s = byId[Number(c.id)] || { level: 0, experience: 0 };
      const next = 100 * (Number(s.level) + 1);
      return { ...c, level: Number(s.level) || 0, experience: Number(s.experience) || 0, next };
    });

  return (
    <div className="space-y-3">
      <div className="p-3 rounded-xl" style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)' }}>
        <p className="text-xs font-bold flex items-center gap-2" style={{ color: 'var(--color-gold)' }}>
          <GraduationCap size={16} /> Compétences
        </p>
        <p className="text-[10px] mt-1" style={{ color: 'var(--text-muted)' }}>Chaque mission peut faire progresser certaines compétences.</p>
      </div>

      <div className="space-y-2">
        {merged.map((s: any) => (
          <div key={s.id} className="p-3 rounded-xl" style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)' }}>
            <div className="flex items-center justify-between gap-2">
              <p className="text-xs font-bold truncate" style={{ color: 'var(--text-primary)' }}>{s.name}</p>
              <p className="text-[10px] font-bold" style={{ color: 'var(--color-gold)' }}>Lv {s.level}</p>
            </div>
            {s.description && <p className="text-[10px] mt-1" style={{ color: 'var(--text-muted)' }}>{s.description}</p>}
            <div className="mt-2">
              <div className="flex justify-between text-[9px]" style={{ color: 'var(--text-muted)' }}>
                <span>XP</span>
                <span>{s.experience}/{s.next}</span>
              </div>
              <div className="mt-1 h-1.5 rounded overflow-hidden" style={{ background: 'rgba(255,255,255,0.06)' }}>
                <div className="h-full" style={{ width: `${Math.min(100, Math.round((s.experience / s.next) * 100))}%`, background: 'var(--color-gold)' }} />
              </div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

function ContactsScreen({ contacts }: { contacts: Contact[] }) {
  // Phase 8.12 (2026-04-29) — appel à Hugues révèle le voleur du dernier
  // vol non identifié (gratuit). Au reveal réussi → ouvre PlayerProfileLightbox.
  const openPlayerProfile = useGameStore((s) => s.openPlayerProfile);
  const player = useGameStore((s) => s.player);
  // Phase 8 v2 (2026-05-01) — appel urgentiste démarre une session de soin
  // (POI Croix rouge généré 500m, +1 PV/min). Ouvre UrgentistCareLightbox via
  // event window-level pour découpler de Phone (la lightbox est montée
  // globalement dans play/page.tsx).
  const [calling, setCalling] = useState<string | null>(null);
  const [callMessage, setCallMessage] = useState<string | null>(null);

  // Phase 17.1 (2026-05-05) — Ajout virtuel du médecin perso embauché
  // (specialist_attachment role='medic' is_active=true) à la liste des
  // contacts. On fetch les specialists du player et on injecte une card
  // dédiée avec call to action "Appeler le médecin" (ouvre une mini-form
  // pour choisir le nombre de PV à acheter et la devise).
  const [medicAttachment, setMedicAttachment] = useState<any | null>(null);
  const [showMedicCallForm, setShowMedicCallForm] = useState(false);
  const [medicPoints, setMedicPoints] = useState<number>(10);
  const [medicCurrency, setMedicCurrency] = useState<'shadow' | 'light'>('shadow');

  // Phase 17.2 (2026-05-05) — Contacts spécialistes multi-rôle multi-scope.
  // Pour chaque attachment actif (perso + gang + cartel), on render une
  // card dédiée avec format selon le rôle :
  //   • lawyer     → "Maître {nom_famille}"
  //   • accountant → "Expert {nom_famille}"
  //   • informant  → nom complet (consigne user : pas de préfixe)
  //   • detective  → "Enquêteur {nom_famille}"
  //   • medic      → géré séparément (form on-call existant A6)
  // Si plusieurs scopes (ex: 1 avocat perso + 1 avocat gang), on
  // affiche les 3 cards distinctement avec badge "Perso/Gang/Cartel".
  type SpecCard = {
    attachmentId: string;
    role: 'lawyer' | 'accountant' | 'informant' | 'detective';
    scope: 'player' | 'gang' | 'cartel';
    rawName: string;       // ex "Maître Corvaldi"
    displayName: string;   // formatted selon role
    skill: number;
  };
  const [specCards, setSpecCards] = useState<SpecCard[]>([]);

  useEffect(() => {
    if (!player?.id) return;
    let cancel = false;
    (async () => {
      try {
        const playerList: any = await api.specialists.forOwner('player', player.id);
        if (cancel) return;
        const arr = Array.isArray(playerList) ? playerList : [];
        const medic = arr.find((a: any) => (a.role || a.specialist?.role) === 'medic' && a.is_active !== false);
        setMedicAttachment(medic ?? null);

        // Phase 17.2 — Multi-scope : récupère gang_id + cartel_id pour
        // fetch les spécialistes attachés à ces scopes en parallèle
        const [gangData, cartelData]: [any, any] = await Promise.all([
          api.gang.getMy().catch(() => null),
          api.cartel.getMine().catch(() => null),
        ]);
        const gangList: any[] = gangData?.id
          ? await api.specialists.forOwner('gang', gangData.id).catch(() => []) as any[]
          : [];
        const cartelList: any[] = cartelData?.id
          ? await api.specialists.forOwner('cartel', cartelData.id).catch(() => []) as any[]
          : [];

        const buildCard = (a: any, scope: 'player' | 'gang' | 'cartel'): SpecCard | null => {
          const role = (a.role || a.specialist?.role) as SpecCard['role'];
          if (!['lawyer', 'accountant', 'informant', 'detective'].includes(role)) return null;
          if (a.is_active === false) return null;
          const rawName: string = a.name || a.specialist?.name || '—';
          const skill = Number(a.skill_level ?? a.specialist?.skill_level ?? 0);
          // Format display selon role
          // Conversion "Maître Corvaldi" → "Corvaldi" pour les rôles qui
          // ont un préfixe différent : lawyer/detective utilisent juste
          // le nom de famille (le seed les nomme déjà "Maître X" et
          // "Enquêteur X" — on enlève le préfixe seed et on remet le
          // bon préfixe contact).
          const stripPrefix = (s: string, prefixes: string[]) => {
            for (const p of prefixes) if (s.startsWith(p + ' ')) return s.slice(p.length + 1);
            return s;
          };
          const familyName = stripPrefix(rawName, ['Maître', 'Enquêteur', 'Docteur']);
          let displayName: string;
          if (role === 'lawyer')        displayName = `Maître ${familyName}`;
          else if (role === 'accountant') displayName = `Expert ${familyName}`;
          else if (role === 'detective')  displayName = `Enquêteur ${familyName}`;
          else                           displayName = rawName; // informant : nom complet (surnoms type "Joseph Le Corbeau")
          return {
            attachmentId: a.attachment_id || a.id,
            role,
            scope,
            rawName,
            displayName,
            skill,
          };
        };

        const cards: SpecCard[] = [];
        for (const a of arr) {
          const card = buildCard(a, 'player');
          if (card) cards.push(card);
        }
        for (const a of (Array.isArray(gangList) ? gangList : [])) {
          const card = buildCard(a, 'gang');
          if (card) cards.push(card);
        }
        for (const a of (Array.isArray(cartelList) ? cartelList : [])) {
          const card = buildCard(a, 'cartel');
          if (card) cards.push(card);
        }
        if (!cancel) setSpecCards(cards);
      } catch {
        if (!cancel) {
          setMedicAttachment(null);
          setSpecCards([]);
        }
      }
    })();
    return () => { cancel = true; };
  }, [player?.id]);

  const handleMedicCall = async () => {
    setCalling('medic_perso');
    setCallMessage(null);
    try {
      const r = await api.specialists.medicCall(medicPoints, medicCurrency);
      if (r.accepted) {
        setCallMessage(`${r.message} Coût ${r.cost.toLocaleString('fr-FR')} ∞ ${r.currency}, livraison ~${r.estimated_minutes} min.`);
        setShowMedicCallForm(false);
      } else {
        setCallMessage(r.message);
      }
    } catch (e: any) {
      setCallMessage(e?.message || 'Appel médecin échoué.');
    } finally {
      setCalling(null);
    }
  };

  const handleHuguesCall = async () => {
    setCalling('npc:hugo_indic');
    setCallMessage(null);
    try {
      const r = await api.phone.revealThief();
      setCallMessage(tFmt('phone.hugues_reveal_ok', {
        thief: r.thief_name,
        vehicle: r.vehicle_name,
        remaining: r.remaining_unrevealed,
      }));
      // Ouvre le lightbox profil du voleur après 800ms (laisse lire le flavor)
      setTimeout(() => openPlayerProfile(r.thief_player_id), 800);
    } catch (e: any) {
      const msg = e?.message || '';
      if (msg.includes('Aucun vol')) {
        setCallMessage(t('phone.hugues_no_unrevealed'));
      } else {
        setCallMessage(msg || t('phone.hugues_call_error'));
      }
    } finally {
      setCalling(null);
    }
  };

  // Phase 8 v2 (2026-05-01) — handlers urgentistes (nurse / doctor)
  const handleUrgentistCall = async (kind: 'nurse' | 'doctor') => {
    const contactCode = kind === 'nurse' ? 'npc:nurse_urgentist' : 'npc:doctor_urgentist';
    setCalling(contactCode);
    setCallMessage(null);
    try {
      const r = await api.hospital.urgentist.start(kind);
      const costMsg = r.cost > 0 ? ` (${r.cost} ∞ prélevés)` : '';
      setCallMessage(`Soin démarré${costMsg}. POI Croix rouge généré à 500m, vous y êtes téléporté.`);
      // Déclenche l'ouverture de la lightbox via event window
      // (UrgentistCareLightbox monté globalement dans play/page.tsx l'écoute)
      window.dispatchEvent(new CustomEvent('urgentist-care-started', {
        detail: { session_id: r.session_id, poi_lat: r.poi_lat, poi_lon: r.poi_lon },
      }));
    } catch (e: any) {
      setCallMessage(e?.message || 'Erreur lors de l\'appel.');
    } finally {
      setCalling(null);
    }
  };

  if (contacts.length === 0) {
    return (
      <div className="text-center py-8">
        <User size={28} style={{ color: 'var(--text-muted)' }} className="mx-auto mb-2" />
        <p className="text-xs" style={{ color: 'var(--text-muted)' }}>{t('phone.no_contacts')}</p>
        <p className="text-[10px] mt-1" style={{ color: 'var(--text-muted)' }}>
          {t('phone.meet_npcs')}
        </p>
      </div>
    );
  }

  // Phase 17.2 (2026-05-05) — Helpers UI pour les specCards
  const SCOPE_BADGE: Record<SpecCard['scope'], { label: string; color: string }> = {
    player: { label: 'Perso', color: '#a855f7' },
    gang:   { label: 'Gang', color: '#dc2626' },
    cartel: { label: 'Cartel', color: 'var(--color-gold)' },
  };
  const ROLE_BADGE: Record<SpecCard['role'], { color: string; bg: string }> = {
    lawyer:     { color: '#fcd34d', bg: 'rgba(212,168,67,0.18)' },
    accountant: { color: '#60a5fa', bg: 'rgba(96,165,250,0.18)' },
    informant:  { color: '#a78bfa', bg: 'rgba(167,139,250,0.18)' },
    detective:  { color: '#a78bfa', bg: 'rgba(167,139,250,0.18)' },
  };

  return (
    <div className="space-y-2">
      <h3 className="text-xs font-bold mb-2" style={{ color: 'var(--color-gold)' }}>
        {t('phone.contacts')} ({contacts.length + (medicAttachment ? 1 : 0) + specCards.length})
      </h3>
      {callMessage && (
        <div className="p-2 rounded-lg text-[10px]" style={{
          background: 'rgba(212,168,67,0.10)',
          border: '1px solid var(--border-gold)',
          color: 'var(--color-gold-light)',
        }}>
          {callMessage}
        </div>
      )}

      {/* Phase 17.2 (2026-05-05) — Cartes spécialistes attachés (avocat /
          comptable / indic / enquêteur) multi-scope (perso + gang + cartel).
          Format nom selon rôle : "Maître X", "Expert X", "Enquêteur X",
          ou nom complet pour indic. Badge scope (Perso/Gang/Cartel). */}
      {specCards.map((card) => {
        const scopeBadge = SCOPE_BADGE[card.scope];
        const roleBadge = ROLE_BADGE[card.role];
        const initial = card.displayName.split(' ').slice(-1)[0].charAt(0).toUpperCase();
        return (
          <div key={card.attachmentId} className="flex items-center gap-3 p-2 rounded-lg"
            style={{ background: 'rgba(255,255,255,0.02)', border: '1px solid var(--border-dark)' }}>
            <div className="w-9 h-9 rounded-full flex items-center justify-center text-xs font-bold"
              style={{ background: roleBadge.bg, color: roleBadge.color, border: `1px solid ${roleBadge.color}40` }}>
              {initial}
            </div>
            <div className="flex-1 min-w-0">
              <p className="text-xs flex items-center gap-1 flex-wrap" style={{ color: 'var(--text-primary)' }}>
                {card.displayName}
                <span className="text-[8px] uppercase tracking-[.08em] px-1.5 py-0.5 rounded"
                  style={{ background: scopeBadge.color === 'var(--color-gold)' ? 'rgba(212,168,67,0.18)' : `${scopeBadge.color}30`, color: scopeBadge.color }}>
                  {scopeBadge.label}
                </span>
              </p>
              <p className="text-[9px]" style={{ color: 'var(--text-muted)' }}>
                niv. {card.skill}/10 — voir détails dans Gestion {card.scope === 'player' ? 'perso' : card.scope}
              </p>
            </div>
          </div>
        );
      })}

      {/* Phase 17.1 (2026-05-05) — Médecin perso (si attachment actif).
          Card dédiée avec mini-form pour choisir nb PV + devise.
          Endpoint POST /api/specialists/medic/call livre 1 PV/min après débit. */}
      {medicAttachment && (
        <div className="rounded-lg p-2"
          style={{ border: '1px solid rgba(220,38,38,0.5)', background: 'rgba(220,38,38,0.04)' }}>
          <div className="flex items-center gap-3">
            <div className="w-9 h-9 rounded-full flex items-center justify-center"
              style={{ background: '#fff', border: '2px solid #dc2626' }}>
              <HeartPulse size={18} style={{ color: '#dc2626' }} />
            </div>
            <div className="flex-1 min-w-0">
              <p className="text-xs flex items-center gap-1" style={{ color: 'var(--text-primary)' }}>
                {medicAttachment.name || medicAttachment.specialist?.name || 'Docteur'}
                <span className="text-[8px] uppercase tracking-[.08em] px-1.5 py-0.5 rounded"
                  style={{ background: 'rgba(220,38,38,0.18)', color: '#fca5a5' }}>
                  Médecin perso
                </span>
              </p>
              <p className="text-[9px] italic mt-0.5" style={{ color: '#fca5a5' }}>
                Sur appel : 100 ∞/PV (shadow ou light), livraison 1 PV/min.
              </p>
            </div>
            <button type="button"
              onClick={() => setShowMedicCallForm((v) => !v)}
              className="text-[10px] px-2 py-1 rounded"
              style={{ background: 'rgba(220,38,38,0.18)', border: '1px solid rgba(220,38,38,0.5)', color: '#fca5a5' }}>
              {showMedicCallForm ? 'Annuler' : 'Appeler'}
            </button>
          </div>
          {showMedicCallForm && (
            <div className="mt-2 pt-2 space-y-2" style={{ borderTop: '1px solid rgba(255,255,255,0.06)' }}>
              <div>
                <label className="text-[9px]" style={{ color: 'var(--text-muted)' }}>
                  PV à acheter (1 → manquants)
                </label>
                <input type="number" min={1} max={100} value={medicPoints}
                  onChange={(e) => setMedicPoints(Math.max(1, Math.min(100, Number(e.target.value) || 1)))}
                  className="w-full mt-1 px-2 py-1 text-[11px] rounded"
                  style={{ background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.08)', color: 'var(--text-primary)' }} />
              </div>
              <div className="flex gap-1">
                <button type="button"
                  onClick={() => setMedicCurrency('shadow')}
                  className="flex-1 text-[10px] py-1 rounded"
                  style={{
                    background: medicCurrency === 'shadow' ? 'rgba(168,85,247,0.2)' : 'rgba(255,255,255,0.04)',
                    border: medicCurrency === 'shadow' ? '1px solid #a855f7' : '1px solid rgba(255,255,255,0.08)',
                    color: medicCurrency === 'shadow' ? '#c4a3ff' : 'var(--text-secondary)',
                  }}>
                  ∞ ombre
                </button>
                <button type="button"
                  onClick={() => setMedicCurrency('light')}
                  className="flex-1 text-[10px] py-1 rounded"
                  style={{
                    background: medicCurrency === 'light' ? 'rgba(212,168,67,0.2)' : 'rgba(255,255,255,0.04)',
                    border: medicCurrency === 'light' ? '1px solid var(--color-gold)' : '1px solid rgba(255,255,255,0.08)',
                    color: medicCurrency === 'light' ? 'var(--color-gold-light)' : 'var(--text-secondary)',
                  }}>
                  ∞ lumière
                </button>
              </div>
              <p className="text-[9px]" style={{ color: 'var(--text-muted)' }}>
                Coût : <b style={{ color: 'var(--text-primary)' }}>{(medicPoints * 100).toLocaleString('fr-FR')} ∞ {medicCurrency}</b>
              </p>
              <button type="button"
                disabled={calling === 'medic_perso'}
                onClick={handleMedicCall}
                className="w-full text-[10px] py-2 rounded font-bold"
                style={{
                  background: 'linear-gradient(135deg, rgba(220,38,38,0.25), rgba(0,0,0,0.6))',
                  border: '1px solid rgba(220,38,38,0.6)',
                  color: '#fca5a5',
                  opacity: calling === 'medic_perso' ? 0.5 : 1,
                }}>
                {calling === 'medic_perso' ? 'Appel en cours…' : `Confirmer (${medicPoints} PV à 1/min)`}
              </button>
            </div>
          )}
        </div>
      )}
      {contacts.map((c, i) => {
        const isHugues = c.player_id === 'npc:hugo_indic';
        const isNurseUrgentist = c.player_id === 'npc:nurse_urgentist';
        const isDoctorUrgentist = c.player_id === 'npc:doctor_urgentist';
        const isUrgentist = isNurseUrgentist || isDoctorUrgentist;
        const isClickable = isHugues || isUrgentist;

        const onClick = isHugues
          ? handleHuguesCall
          : isNurseUrgentist
            ? () => handleUrgentistCall('nurse')
            : isDoctorUrgentist
              ? () => handleUrgentistCall('doctor')
              : undefined;

        const urgentistHint = isUrgentist
          ? (isNurseUrgentist
              ? 'Cliquer : appel gratuit, soin progressif (1 PV/min, 100 min max). Cooldown 1×/sem.'
              : 'Cliquer : appel 500 ∞, soin progressif (1 PV/min, 100 min max). Cooldown 1×/mois.')
          : undefined;
        const isCallingThis = calling === c.player_id;
        const tooltipBase = isHugues ? t('phone.hugues_action_hint') : urgentistHint;

        const borderColor = isHugues
          ? 'var(--border-gold)'
          : isUrgentist
            ? 'rgba(220,38,38,0.5)'
            : undefined;

        return (
          <div
            key={i}
            onClick={onClick}
            className={`flex items-center gap-3 p-2 rounded-lg ${isClickable ? 'cursor-pointer' : ''} hover:bg-white/5`}
            title={tooltipBase}
            style={borderColor ? { border: `1px solid ${borderColor}` } : undefined}
          >
            <div
              className="w-9 h-9 rounded-full flex items-center justify-center text-xs font-bold"
              style={{
                background: isUrgentist
                  ? '#ffffff'
                  : c.is_npc
                    ? 'var(--color-gold-dark)'
                    : 'var(--bg-tertiary)',
                color: isUrgentist
                  ? '#dc2626'
                  : c.is_npc
                    ? 'var(--color-black)'
                    : 'var(--text-primary)',
                border: isUrgentist ? '2px solid #dc2626' : undefined,
              }}
            >
              {isUrgentist ? (
                /* Croix rouge SVG inline pour matcher le POI sur la map */
                <svg viewBox="0 0 24 24" width="20" height="20" fill="#dc2626" aria-hidden>
                  <rect x="10" y="3" width="4" height="18" rx="0.5" />
                  <rect x="3" y="10" width="18" height="4" rx="0.5" />
                </svg>
              ) : (
                c.name.charAt(0).toUpperCase()
              )}
            </div>
            <div className="flex-1 min-w-0">
              <p className="text-xs flex items-center gap-1" style={{ color: 'var(--text-primary)' }}>
                {c.name}
                {isHugues && (
                  <span className="text-[8px] uppercase tracking-[.08em] px-1.5 py-0.5 rounded"
                    style={{ background: 'rgba(212,168,67,0.18)', color: 'var(--color-gold-light)' }}>
                    {t('phone.hugues_role_label')}
                  </span>
                )}
                {isUrgentist && (
                  <span className="text-[8px] uppercase tracking-[.08em] px-1.5 py-0.5 rounded"
                    style={{ background: 'rgba(220,38,38,0.18)', color: '#fca5a5' }}>
                    Soin
                  </span>
                )}
              </p>
              <p className="text-[9px]" style={{ color: 'var(--text-muted)' }}>{c.phone_number}</p>
              {isHugues && (
                <p className="text-[9px] italic mt-0.5" style={{ color: 'var(--color-gold-light)' }}>
                  {calling === 'npc:hugo_indic' ? t('phone.hugues_calling') : t('phone.hugues_action_hint')}
                </p>
              )}
              {isUrgentist && (
                <p className="text-[9px] italic mt-0.5" style={{ color: '#fca5a5' }}>
                  {isCallingThis ? 'Appel en cours…' : urgentistHint}
                </p>
              )}
            </div>
          </div>
        );
      })}
    </div>
  );
}

/* ─── Messages Screen ─── */

function MessagesScreen({ playerId }: { playerId?: string }) {
  const [messages, setMessages] = useState<Message[]>([]);
  const [loading, setLoading] = useState(true);
  const [selected, setSelected] = useState<Message | null>(null);

  useEffect(() => {
    if (!playerId) return;
    apiFetch<Message[]>(`/api/player/${playerId}/messages`)
      .then((res) => setMessages(Array.isArray(res) ? res : []))
      .catch(() => setMessages([]))
      .finally(() => setLoading(false));
  }, [playerId]);

  if (loading) return <p className="text-xs text-center py-4" style={{ color: 'var(--text-muted)' }}>{t('common.loading')}</p>;

  if (selected) {
    return (
      <div>
        <button onClick={() => setSelected(null)} className="flex items-center gap-1 mb-3 text-[10px] hover:opacity-70" style={{ color: 'var(--color-gold)' }}>
          <ChevronLeft size={12} /> {t('common.back')}
        </button>
        <h3 className="text-xs font-bold mb-1" style={{ color: 'var(--text-primary)' }}>{selected.subject}</h3>
        <p className="text-[10px] mb-3" style={{ color: 'var(--text-muted)' }}>
          {selected.sender?.character_name || selected.sender?.username || t('phone.unknown_sender')}
          {' — '}
          {new Date(selected.created_at).toLocaleDateString()}
        </p>
        <p className="text-xs leading-relaxed" style={{ color: 'var(--text-secondary)' }}>{selected.content}</p>
      </div>
    );
  }

  if (messages.length === 0) {
    return (
      <div className="text-center py-8">
        <MessageSquare size={28} style={{ color: 'var(--text-muted)' }} className="mx-auto mb-2" />
        <p className="text-xs" style={{ color: 'var(--text-muted)' }}>{t('phone.no_messages')}</p>
      </div>
    );
  }

  return (
    <div className="space-y-1.5">
      <h3 className="text-xs font-bold mb-2" style={{ color: 'var(--color-gold)' }}>{t('phone.sms')} ({messages.length})</h3>
      {messages.map((msg) => (
        <button
          key={msg.id}
          onClick={() => {
            setSelected(msg);
            if (!msg.is_read && playerId) {
              apiFetch(`/api/player/${playerId}/messages/${msg.id}/read`, { method: 'PATCH' }).catch(() => {});
              msg.is_read = true;
            }
          }}
          className="w-full text-left p-2 rounded-lg hover:bg-white/5 transition-colors"
        >
          <div className="flex items-start gap-2">
            {!msg.is_read && <div className="w-2 h-2 rounded-full mt-1 shrink-0" style={{ background: 'var(--color-gold)' }} />}
            <div className="min-w-0 flex-1">
              <p className="text-[10px] font-bold truncate" style={{ color: 'var(--text-primary)' }}>
                {msg.sender?.character_name || msg.sender?.username || t('phone.unknown_sender')}
              </p>
              <p className="text-[10px] truncate" style={{ color: 'var(--text-muted)' }}>{msg.subject}</p>
            </div>
            <span className="text-[8px] shrink-0" style={{ color: 'var(--text-muted)' }}>
              {new Date(msg.created_at).toLocaleDateString()}
            </span>
          </div>
        </button>
      ))}
    </div>
  );
}

/* ─── Jobs Screen ─── */

function JobsScreen({ playerId }: { playerId?: string }) {
  const [myJobs, setMyJobs] = useState<any[]>([]);
  const [catalog, setCatalog] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [applying, setApplying] = useState<string | null>(null);
  const [msg, setMsg] = useState<string | null>(null);

  const reload = () => {
    if (!playerId) return;
    setLoading(true);
    Promise.all([
      apiFetch<any[]>('/api/employment/my-jobs').catch(() => []),
      apiFetch<any[]>('/api/employment/catalog').catch(() => []),
    ]).then(([jobs, cat]) => {
      setMyJobs(Array.isArray(jobs) ? jobs : []);
      setCatalog(Array.isArray(cat) ? cat : []);
    }).finally(() => setLoading(false));
  };

  useEffect(() => { reload(); }, [playerId]);

  const handleApply = async (jobType: string) => {
    setApplying(jobType);
    setMsg(null);
    try {
      await apiFetch('/api/employment/apply', {
        method: 'POST',
        body: JSON.stringify({ type: jobType }),
        headers: { 'Content-Type': 'application/json' },
      });
      setMsg('Embauche reussie !');
      reload();
    } catch (err: any) {
      setMsg(err.message || 'Refusee');
    } finally {
      setApplying(null);
    }
  };

  if (loading) return <p className="text-xs text-center py-4" style={{ color: 'var(--text-muted)' }}>{t('common.loading')}</p>;

  return (
    <div>
      {msg && <p className="text-[10px] mb-2 px-2 py-1 rounded" style={{ color: msg.includes('reussie') ? '#22c55e' : '#ef4444', background: msg.includes('reussie') ? 'rgba(34,197,94,0.1)' : 'rgba(239,68,68,0.1)' }}>{msg}</p>}

      {/* Mes emplois */}
      {myJobs.length > 0 && (
        <>
          <h3 className="text-xs font-bold mb-2" style={{ color: '#22c55e' }}>Mes emplois</h3>
          {myJobs.map((job: any) => (
            <div key={job.id} className="mb-2 p-2 rounded-lg" style={{ background: 'rgba(34,197,94,0.1)', border: '1px solid rgba(34,197,94,0.2)' }}>
              <p className="text-[10px] font-bold" style={{ color: 'var(--text-primary)' }}>{job.employer_name}</p>
              <p className="text-[9px]" style={{ color: 'var(--text-muted)' }}>{job.hourly_rate}∞/h — {job.min_hours}-{job.max_hours}h</p>
              {job.is_working && <p className="text-[9px] font-bold" style={{ color: '#22c55e' }}>Au travail</p>}
            </div>
          ))}
        </>
      )}

      {/* Annonces */}
      <h3 className="text-xs font-bold mb-2 mt-3" style={{ color: 'var(--color-gold)' }}>{t('phone.available_jobs')}</h3>
      {catalog.length === 0 ? (
        <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>{t('phone.no_jobs')}</p>
      ) : (
        <div className="space-y-1.5">
          {catalog.map((job: any, i: number) => (
            <div key={i} className="p-2 rounded-lg" style={{ border: '1px solid rgba(255,255,255,0.05)' }}>
              <div className="flex justify-between items-start">
                <div className="min-w-0">
                  <p className="text-[10px] font-bold" style={{ color: 'var(--text-primary)' }}>{job.name}</p>
                  <p className="text-[9px]" style={{ color: 'var(--text-muted)' }}>{job.hourly_rate}∞/h — {job.min_hours}-{job.max_hours}h</p>
                </div>
                <button
                  onClick={() => handleApply(job.type)}
                  disabled={applying === job.type}
                  className="text-[8px] font-bold px-2 py-1 rounded shrink-0"
                  style={{ background: 'var(--color-gold)', color: '#000', opacity: applying === job.type ? 0.5 : 1 }}
                >
                  {applying === job.type ? '...' : 'Postuler'}
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

/* ─── Finances Screen ─── */

function FinancesScreen() {
  const { balances } = useGameStore();

  return (
    <div>
      <h3 className="text-xs font-bold mb-3" style={{ color: 'var(--color-gold)' }}>{t('phone.finances')}</h3>
      <div className="space-y-2">
        {[
          { label: '∞ Light', value: balances?.infinite_light ?? 0 },
          { label: '∞ Shadow', value: balances?.infinite_shadow ?? 0, color: 'var(--color-red)' },
          { label: 'ᛞ Dagaz', value: balances?.dagaz ?? 0, color: 'var(--color-gold)' },
          { label: '⚵ Quintessence', value: balances?.quintessence ?? 0, color: '#8b5cf6' },
        ].map((b) => (
          <div key={b.label} className="flex justify-between items-center p-2 rounded-lg" style={{ background: 'rgba(255,255,255,0.03)' }}>
            <span className="text-[10px]" style={{ color: 'var(--text-secondary)' }}>{b.label}</span>
            <span className="text-xs font-mono font-bold" style={{ color: b.color || 'var(--text-primary)' }}>
              {Number(b.value).toLocaleString()}
            </span>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ─── Marketplace Screen ─── */

interface Listing {
  id: string;
  title: string;
  category: string;
  market_type: string;
  suggested_value: number;
  status: string;
  seller: { id: string; username: string } | null;
}

function MarketplaceScreen({ onOpenListing }: { onOpenListing: (l: Listing) => void }) {
  const [listings, setListings] = useState<Listing[]>([]);
  const [loading, setLoading] = useState(true);
  const [filter, setFilter] = useState<'all' | 'white' | 'black'>('all');

  useEffect(() => {
    setLoading(true);
    const filters: Record<string, string> = {};
    if (filter !== 'all') filters.market = filter;
    apiFetch<Listing[]>(`/api/marketplace/listings${filter !== 'all' ? `?market=${filter}` : ''}`)
      .then((res) => setListings(Array.isArray(res) ? res : []))
      .catch(() => setListings([]))
      .finally(() => setLoading(false));
  }, [filter]);

  return (
    <div>
      <h3 className="text-xs font-bold mb-2" style={{ color: 'var(--color-gold)' }}>{t('phone.marketplace')}</h3>

      {/* Filter tabs */}
      <div className="flex gap-1 mb-3">
        {(['all', 'white', 'black'] as const).map((f) => (
          <button
            key={f}
            onClick={() => setFilter(f)}
            className="flex-1 text-[9px] py-1.5 rounded-lg font-medium transition-colors"
            style={{
              background: filter === f
                ? (f === 'black' ? '#000' : f === 'white' ? '#fff' : 'var(--color-gold)')
                : 'rgba(255,255,255,0.05)',
              color: filter === f
                ? (f === 'black' ? '#fff' : f === 'white' ? '#000' : '#000')
                : 'var(--text-muted)',
              border: filter === f ? 'none' : '1px solid rgba(255,255,255,0.1)',
            }}
          >
            {f === 'all' ? t('phone.market_all') : f === 'white' ? t('phone.market_white') : t('phone.market_black')}
          </button>
        ))}
      </div>

      {loading ? (
        <p className="text-xs text-center py-4" style={{ color: 'var(--text-muted)' }}>{t('common.loading')}</p>
      ) : listings.length === 0 ? (
        <div className="text-center py-6">
          <ShoppingBag size={24} style={{ color: 'var(--text-muted)' }} className="mx-auto mb-2" />
          <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>{t('phone.no_listings')}</p>
        </div>
      ) : (
        <div className="space-y-1.5">
          {listings.slice(0, 15).map((l) => (
            <div
              key={l.id}
              className="p-2.5 rounded-lg relative"
              style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)' }}
              onClick={() => onOpenListing(l)}
            >
              {l.market_type === 'black' && (
                <span className="absolute top-1 right-1 text-[7px] px-1 rounded font-bold"
                  style={{ background: 'var(--color-red-dark)', color: 'white' }}>
                  NOIR
                </span>
              )}
              {l.status === 'reserved' && (
                <span className="absolute top-1 right-1 text-[7px] px-1 rounded font-bold"
                  style={{ background: 'var(--color-gold)', color: '#000' }}>
                  {t('phone.reserved')}
                </span>
              )}
              <p className="text-[10px] font-bold pr-8 truncate" style={{ color: 'var(--text-primary)' }}>{l.title}</p>
              <div className="flex justify-between items-center mt-1">
                <span className="text-[9px]" style={{ color: 'var(--text-muted)' }}>
                  {l.seller?.username || t('phone.unknown_sender')}
                </span>
                <span className="text-[10px] font-bold" style={{ color: 'var(--color-gold)' }}>
                  ∞ {l.suggested_value.toLocaleString()}
                </span>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function ListingDealPanel({ listing, onClose }: { listing: Listing; onClose: () => void }) {
  const [creating, setCreating] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const sellerId = listing.seller?.id || null;

  const createDeal = async () => {
    if (!sellerId) return;
    setCreating(true);
    setError(null);
    try {
      await api.marketplace.createDeal({
        owner_id: sellerId,
        items: [{
          item_type: 'listing',
          listing_id: listing.id,
          item_data: { title: listing.title, category: listing.category },
          suggested_value: listing.suggested_value,
          direction: 'owner_to_initiator',
        }],
        note: `Discussion ouverte pour 1 élément`,
      });
      onClose();
    } catch (err: any) {
      setError(err?.message || 'Erreur');
    } finally {
      setCreating(false);
    }
  };

  return (
    <div className="p-4 space-y-3">
      <div className="p-3 rounded-xl" 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)' }}>{listing.title}</p>
        <div className="flex justify-between mt-1">
          <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>{listing.seller?.username || t('phone.unknown_sender')}</p>
          <p className="text-xs font-bold" style={{ color: 'var(--color-gold)' }}>∞ {listing.suggested_value.toLocaleString()}</p>
        </div>
      </div>

      {error && (
        <p className="text-[10px]" style={{ color: 'var(--color-red)' }}>{error}</p>
      )}

      <button
        type="button"
        disabled={!sellerId || creating}
        onClick={createDeal}
        className="w-full py-2 rounded-xl text-xs font-bold disabled:opacity-50"
        style={{ background: 'var(--color-gold)', color: '#000' }}
      >
        {creating ? t('phone.creating') : t('phone.open_deal')}
      </button>

      <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>{t('phone.deal_hint')}</p>
    </div>
  );
}

function BlackMarketPanel() {
  const [drugs, setDrugs] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [qtyById, setQtyById] = useState<Record<string, number>>({});
  const [buying, setBuying] = useState<string | null>(null);

  useEffect(() => {
    setLoading(true);
    api.player.getBlackmarketDrugs()
      .then((res: any) => setDrugs(Array.isArray(res) ? res : []))
      .catch(() => setDrugs([]))
      .finally(() => setLoading(false));
  }, []);

  const buy = async (drugId: string) => {
    const qty = Math.max(1, Number(qtyById[drugId] || 1));
    setBuying(drugId);
    try {
      await api.player.buyDrug(drugId, qty);
    } finally {
      setBuying(null);
    }
  };

  if (loading) {
    return <p className="text-xs text-center py-4" style={{ color: 'var(--text-muted)' }}>{t('common.loading')}</p>;
  }

  if (drugs.length === 0) {
    return <p className="text-xs text-center py-6" style={{ color: 'var(--text-muted)' }}>{t('phone.no_blackmarket')}</p>;
  }

  return (
    <div className="p-4 space-y-2">
      {drugs.slice(0, 20).map((d: any) => (
        <div key={d.id} className="p-3 rounded-xl" style={{ background: 'rgba(255,255,255,0.03)', border: '1px solid rgba(255,255,255,0.06)' }}>
          <div className="flex justify-between items-center">
            <p className="text-xs font-bold" style={{ color: 'var(--text-primary)' }}>{d.name}</p>
            <p className="text-xs font-bold" style={{ color: 'var(--color-red-light)' }}>∞ {Number(d.retail_price).toLocaleString()}</p>
          </div>
          <div className="flex items-center gap-2 mt-2">
            <input
              type="number"
              min={1}
              value={qtyById[d.id] ?? 1}
              onChange={(e) => setQtyById((prev) => ({ ...prev, [d.id]: Number(e.target.value) }))}
              className="w-16 px-2 py-1 rounded text-xs outline-none"
              style={{ background: 'rgba(255,255,255,0.04)', border: '1px solid rgba(255,255,255,0.10)', color: 'var(--text-primary)' }}
            />
            <button
              type="button"
              onClick={() => buy(d.id)}
              disabled={buying === d.id}
              className="flex-1 py-1.5 rounded-lg text-[10px] font-bold disabled:opacity-50"
              style={{ background: 'rgba(239,68,68,0.2)', border: '1px solid rgba(239,68,68,0.35)', color: '#fff' }}
            >
              {buying === d.id ? t('phone.processing') : t('phone.buy')}
            </button>
          </div>
        </div>
      ))}
    </div>
  );
}

/* ─── Phone Missions Screen ─── */
function PhoneMissionsScreen() {
  const [missions, setMissions] = useState<Array<{ id: string; title: string; category: string; difficulty?: string; duration_minutes?: number; status?: string }>>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    apiFetch<any>('/api/mission/available')
      .then((res) => {
        const data = Array.isArray(res) ? res : res?.missions ?? [];
        setMissions(data.slice(0, 15));
      })
      .catch(() => setMissions([]))
      .finally(() => setLoading(false));
  }, []);

  if (loading) return <p className="text-xs text-center py-4" style={{ color: 'var(--text-muted)' }}>{t('common.loading')}</p>;

  const categoryColors: Record<string, string> = {
    story_common: 'var(--color-gold)', story_crime: '#ef4444', story_politics: '#3b82f6',
    story_redemption: '#22c55e', autonomous: '#8b5cf6', prison: '#6b7280',
  };

  return (
    <div>
      <h3 className="text-xs font-bold mb-2" style={{ color: 'var(--color-gold)' }}>{t('phone.missions')}</h3>
      {missions.length === 0 ? (
        <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>Aucune mission disponible</p>
      ) : (
        <div className="space-y-1.5">
          {missions.map((m) => (
            <div key={m.id} className="p-2 rounded-lg" style={{ border: '1px solid rgba(255,255,255,0.05)' }}>
              <div className="flex items-center gap-1.5">
                <div className="w-1.5 h-1.5 rounded-full shrink-0" style={{ background: categoryColors[m.category] || 'var(--text-muted)' }} />
                <p className="text-[10px] font-bold truncate" style={{ color: 'var(--text-primary)' }}>{m.title}</p>
              </div>
              <p className="text-[9px] mt-0.5 pl-3" style={{ color: 'var(--text-muted)' }}>
                {m.difficulty || 'medium'} {m.duration_minutes ? `- ${m.duration_minutes}min` : ''}
              </p>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

function PlaceholderScreen({ title, icon: Icon }: { title: string; icon: React.ComponentType<{ size: number; style: React.CSSProperties; className?: string }> }) {
  return (
    <div className="text-center py-8">
      <Icon size={28} style={{ color: 'var(--text-muted)' }} className="mx-auto mb-2" />
      <p className="text-xs" style={{ color: 'var(--text-muted)' }}>{title}</p>
      <p className="text-[10px] mt-1" style={{ color: 'var(--text-muted)' }}>{t('phone.coming_soon')}</p>
    </div>
  );
}

// ─── Phase 17 Phase 5 (2026-05-04) — Apps Gestion Gang / Cartel ────────
// Wrapper minimal qui charge le scope du joueur (gang_id ou cartel_id) et
// monte GangManagementTabs avec ce scope. Affiche un message si pas de
// gang/cartel.

function GangManagementScreen({ taulard = false }: { taulard?: boolean }) {
  const [gangId, setGangId] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  useEffect(() => {
    let cancel = false;
    api.gang.getMy().then((g: any) => {
      if (cancel) return;
      setGangId(g?.id ?? null);
      setLoading(false);
    }).catch(() => {
      if (!cancel) { setGangId(null); setLoading(false); }
    });
    return () => { cancel = true; };
  }, []);
  if (loading) return <p className="text-[10px] text-center py-4" style={{ color: 'var(--text-muted)' }}>Chargement…</p>;
  if (!gangId) {
    return <PlaceholderScreen title="Pas de gang" icon={Briefcase} />;
  }
  return (
    <div className="h-full">
      <GangManagementTabs scope={{ type: 'gang', id: gangId }} taulard={taulard} />
    </div>
  );
}

function CartelManagementScreen({ taulard = false }: { taulard?: boolean }) {
  const [cartelId, setCartelId] = useState<string | null>(null);
  const [loading, setLoading] = useState(true);
  useEffect(() => {
    let cancel = false;
    api.cartel.getMine().then((c: any) => {
      if (cancel) return;
      setCartelId(c?.id ?? null);
      setLoading(false);
    }).catch(() => {
      if (!cancel) { setCartelId(null); setLoading(false); }
    });
    return () => { cancel = true; };
  }, []);
  if (loading) return <p className="text-[10px] text-center py-4" style={{ color: 'var(--text-muted)' }}>Chargement…</p>;
  if (!cartelId) {
    return <PlaceholderScreen title="Pas de cartel" icon={Scale} />;
  }
  return (
    <div className="h-full">
      <GangManagementTabs scope={{ type: 'cartel', id: cartelId }} taulard={taulard} />
    </div>
  );
}
