'use client';

import { useState, useEffect } from 'react';
import { useGameStore } from '@/stores/gameStore';
import { t } from '@/lib/i18n';
import { api, apiFetch } from '@/lib/api';
import { VacationControl } from '@/components/ui/VacationControl';
import {
  User, Home, Briefcase, Package, Car, ChevronRight
} from 'lucide-react';

const TABS = [
  { id: 'profile',    icon: User,          labelKey: 'sidebar.profile',    visKey: null },
  { id: 'residence',  icon: Home,          labelKey: 'sidebar.residence',  visKey: 'residence' as const },
  { id: 'employment', icon: Briefcase,     labelKey: 'sidebar.employment', visKey: 'employment' as const },
  { id: 'inventory',  icon: Package,       labelKey: 'sidebar.inventory',  visKey: 'inventory' as const },
  { id: 'vehicle',    icon: Car,           labelKey: 'sidebar.vehicle',    visKey: 'vehicles' as const },
] as const;

/** Inline SVGs matching the vue-normale v2 tabs (lines 374-378). */
function SidebarTabIcon({ id }: { id: string }) {
  switch (id) {
    case 'profile':
      return (
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden>
          <circle cx="12" cy="8" r="4" />
          <path d="M4 21c0-4 4-7 8-7s8 3 8 7" />
        </svg>
      );
    case 'residence':
      return (
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinejoin="round" aria-hidden>
          <path d="M3 10 12 3l9 7v11H3z" />
        </svg>
      );
    case 'employment':
      return (
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden>
          <rect x="3" y="6" width="18" height="14" rx="2" />
          <path d="M9 6V4h6v2" />
        </svg>
      );
    case 'inventory':
      return (
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinejoin="round" aria-hidden>
          <path d="M21 8 12 3 3 8v8l9 5 9-5V8z" />
        </svg>
      );
    case 'vehicle':
      return (
        <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" aria-hidden>
          <path d="M5 17a2 2 0 1 0 4 0 2 2 0 0 0-4 0zM15 17a2 2 0 1 0 4 0 2 2 0 0 0-4 0zM3 17h2m4 0h6M17 4H7l-2 6h14z" />
        </svg>
      );
    default:
      return null;
  }
}

interface InventoryItem {
  id: string;
  item_type: string;
  item_subtype: string;
  quantity: number;
  weight_grams?: number;
  storage_condition?: string;
}

/** Active job from GET /employment/my-jobs */
interface MyJob {
  id: string;
  type: string;
  employer_name: string;
  hourly_rate: number;
  min_hours: number;
  max_hours: number;
  is_working: boolean;
  work_ends_at: string | null;
  total_payslips: number;
  is_cdi: boolean;
  hired_at: string | null;
}

interface Residence {
  id: string;
  name: string;
  type: string;
  rent_cost?: number;
}

interface Vehicle {
  id: string;
  name: string;
  type: string;
  model_name?: string;
  model?: string | null;
  speed?: number;
  armor?: number;
  storage_capacity?: number;
  condition?: number;
  seats?: number;
  fuel_consumption?: number;
  maintenance_per_day?: number;
  in_use?: boolean;
}

export function SidebarLeft() {
  const { activeSidebarLeftTab, setSidebarLeftTab, uiVisibility, player } = useGameStore();

  return (
    /* min-h-full + no inner overflow — the parent aside.panel-scroll is the
       scroll container, which lets `.sl-tabs` sticky-stay at top as content
       slides under it. */
    <div className="flex flex-col min-h-full">
      {/* Tab navigation — v2 mockup: inline SVG icons, rounded chips, gold active glow */}
      <nav className="sl-tabs" aria-label="Onglets profil">
        {TABS.map((tab) => {
          if (tab.visKey) {
            if (!uiVisibility[tab.visKey]) return null;
          }

          const isActive = activeSidebarLeftTab === tab.id;

          return (
            <button
              key={tab.id}
              onClick={() => setSidebarLeftTab(tab.id)}
              className={`sl-tab ${isActive ? 'sl-tab-active' : ''}`}
              title={t(tab.labelKey)}
              aria-current={isActive ? 'page' : undefined}
            >
              <SidebarTabIcon id={tab.id} />
              <span>{t(tab.labelKey)}</span>
            </button>
          );
        })}
      </nav>

      {/* Tab content */}
      <div className="flex-1">
        {activeSidebarLeftTab === 'profile' && <ProfileTab />}
        {activeSidebarLeftTab === 'residence' && <div className="p-3"><ResidenceTab /></div>}
        {activeSidebarLeftTab === 'employment' && <div className="p-3"><EmploymentTab /></div>}
        {activeSidebarLeftTab === 'inventory' && <div className="p-3"><InventoryTab /></div>}
        {activeSidebarLeftTab === 'vehicle' && <div className="p-3"><VehicleTab /></div>}
      </div>
    </div>
  );
}

/* ─── Profile Tab ─── */
function ProfileTab() {
  const { player, gauges } = useGameStore();
  if (!player) return null;

  const name = player.character_name || player.username;
  const initial = name.charAt(0).toUpperCase();
  const tierLabel = (() => {
    const xp = player.experience ?? 0;
    if (xp >= 40000) return 'TIER V';
    if (xp >= 20000) return 'TIER IV';
    if (xp >= 10000) return 'TIER III';
    if (xp >= 3000) return 'TIER II';
    return 'TIER I';
  })();

  return (
    <div className="space-y-3">
      <div
        className="text-center relative pb-4"
        style={{
          background: 'radial-gradient(ellipse at top, rgba(212,168,67,0.05), transparent 70%)',
          borderBottom: '1px solid var(--border-dark)',
          paddingTop: 10,
        }}
      >
        <div className="profile-avatar-wrap" aria-hidden>
          <div className="profile-avatar">
            <span className="profile-avatar-letter">{initial}</span>
            <span className="profile-avatar-tier">{tierLabel}</span>
          </div>
        </div>
        <p
          className="mt-4"
          style={{
            fontFamily: 'var(--font-subtitle)',
            fontSize: 22,
            letterSpacing: '.16em',
            color: 'var(--color-gold-light)',
            textShadow: '0 0 20px rgba(212,168,67,0.3)',
          }}
        >
          {name.toUpperCase()}
        </p>
        <p className="text-[11px] mt-1" style={{ color: 'var(--text-muted)', letterSpacing: '.06em' }}>
          XP {player.experience?.toLocaleString('fr-FR')} · {player.city || 'Sans ville'}
        </p>
      </div>

      {/* Attributs — v2 mockup: label left, value right, full-width bar below */}
      {gauges && (
        <div className="sl-section">
          <h4 className="sl-section-title">Attributs</h4>
          {([
            { key: 'pouvoir', tone: 'gold' as const },
            { key: 'respect', tone: 'gold' as const },
            { key: 'influence', tone: 'gold' as const },
            { key: 'chaleur', tone: 'hot' as const },
            { key: 'conscience', tone: 'cool' as const },
          ] as const).map((g) => (
            <SidebarGauge
              key={g.key}
              label={t(`gauges.${g.key}`)}
              value={Number(gauges[g.key]) || 0}
              max={100}
              tone={g.tone}
            />
          ))}
        </div>
      )}

      {/* Progression — 3 tier cards (crime / politique / rédemption) */}
      <div className="sl-section">
        <h4 className="sl-section-title">Progression</h4>
        <TierCard label={t('sidebar_left.crime')}       tier={player.criminal_tier ?? 0} variant="crime" />
        <TierCard label={t('sidebar_left.politique')}   tier={player.political_tier ?? 0} variant="pol" />
        <TierCard label={t('sidebar_left.redemption')}  tier={(player.legal_tier ?? 0) + (player.ecology_tier ?? 0)} variant="red" />
      </div>

      {/* Dossier pénal — mockup parity */}
      <CasierSection playerId={player.id} isAuthed />

      {/* Phase 15 Iter 7.5 (19-04-2026) — Historique Gang/Cartel */}
      <HistorySection playerId={player.id} />

      {/* Phase 16 (2026-04-21) — Bouton Vacances 72h tout en bas du panel */}
      <div className="pt-2" style={{ borderTop: '1px solid var(--border-dark)' }}>
        <VacationControl />
      </div>
    </div>
  );
}

/** Sidebar gauge — horizontal row (label + value) with full-width bar below. */
function SidebarGauge({
  label, value, max, tone,
}: {
  label: string;
  value: number;
  max: number;
  tone: 'gold' | 'hot' | 'cool';
}) {
  const pct = Math.min(100, Math.max(0, (value / max) * 100));
  return (
    <div className={`sl-gauge sl-gauge-${tone}`}>
      <div className="sl-gauge-head">
        <span className="sl-gauge-label">{label}</span>
        <span className="sl-gauge-val">{Math.round(value)}</span>
      </div>
      <div className="sl-gauge-bar">
        <div className="sl-gauge-fill" style={{ width: `${pct}%` }} />
      </div>
    </div>
  );
}

/** Progression tier card with colored badge. */
function TierCard({ label, tier, variant }: { label: string; tier: number; variant: 'crime' | 'pol' | 'red' }) {
  return (
    <div className="sl-progression">
      <span className="sl-progression-name">{label}</span>
      <span className={`sl-p-tier sl-p-tier-${variant}`}>Tier {tier}</span>
    </div>
  );
}

/** Casier / Dossier pénal — fetches arrests and jail count, renders the
 *  mockup rows with the green LIBRE tag or red badge depending on state. */
function CasierSection({ playerId, isAuthed }: { playerId: string; isAuthed: boolean }) {
  // WS-fed police file (live updates on arrest/conviction/release via useMapSocket).
  // Initial fetch populates it before the first WS event fires.
  const policeFile = useGameStore((s) => s.policeFile);
  const setPoliceFile = useGameStore((s) => s.setPoliceFile);

  useEffect(() => {
    if (!isAuthed || !playerId) return;
    apiFetch<any>(`/api/player/${playerId}/police-file`)
      .then((r) => setPoliceFile({
        arrest_count: r?.arrest_count ?? 0,
        incarceration_count: r?.incarceration_count ?? 0,
        judicial_status: r?.judicial_status ?? 'citoyen',
        degree: r?.degree ?? 0,
        total_crimes: r?.total_crimes ?? 0,
        imprisoned_until: null,
      }))
      .catch(() => setPoliceFile(null));
  }, [playerId, isAuthed, setPoliceFile]);

  const arrests = policeFile?.arrest_count ?? 0;
  const jails = policeFile?.incarceration_count ?? 0;
  const isDetained = (policeFile?.judicial_status ?? 'citoyen') === 'detenu';

  return (
    <div className="sl-section">
      <h4 className="sl-section-title">Dossier pénal</h4>
      <div className="sl-casier">
        <div className="sl-casier-row">
          <span className="k">Arrestations</span>
          <span className="v">{arrests}</span>
        </div>
        <div className="sl-casier-row">
          <span className="k">Incarcérations</span>
          <span className="v">{jails}</span>
        </div>
        <div className="sl-casier-row">
          <span className="k">Statut</span>
          {isDetained
            ? <span className="tag-jail">DÉTENU</span>
            : <span className="tag-free">LIBRE</span>}
        </div>
      </div>
    </div>
  );
}

/** Phase 15 Iter 7.5 (19-04-2026) — Historique Gang/Cartel du joueur. */
function HistorySection({ playerId }: { playerId: string }) {
  const [gangs, setGangs] = useState<any[]>([]);
  const [cartels, setCartels] = useState<any[]>([]);
  const [expanded, setExpanded] = useState(false);

  useEffect(() => {
    if (!playerId) return;
    Promise.all([
      api.player.getGangHistory(playerId).catch(() => []),
      api.player.getCartelHistory(playerId).catch(() => []),
    ]).then(([g, c]) => {
      setGangs(Array.isArray(g) ? g : []);
      setCartels(Array.isArray(c) ? c : []);
    });
  }, [playerId]);

  const total = gangs.length + cartels.length;
  if (total === 0) return null;

  return (
    <div className="sl-section">
      <h4 className="sl-section-title">
        <button type="button" onClick={() => setExpanded(e => !e)}
          style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', width: '100%', background: 'transparent', border: 'none', color: 'inherit', cursor: 'pointer', padding: 0, fontFamily: 'inherit', letterSpacing: 'inherit', fontSize: 'inherit' }}>
          <span>Historique</span>
          <span style={{ color: 'var(--text-muted)', fontSize: 10 }}>
            {total} · {expanded ? '−' : '+'}
          </span>
        </button>
      </h4>
      {expanded && (
        <div className="space-y-2 text-[10px]">
          {gangs.length > 0 && (
            <div>
              <p className="mb-0.5" style={{ color: 'var(--color-gold-light)' }}>Gangs ({gangs.length})</p>
              <ul className="space-y-0.5" style={{ color: 'var(--text-secondary)' }}>
                {gangs.map((h: any) => (
                  <li key={h.id}>
                    <b style={{ color: 'var(--text-primary)' }}>{h.gang_name}</b>
                    {' · '}
                    {new Date(h.joined_at).toLocaleDateString('fr-FR')}
                    {h.left_at ? ` → ${new Date(h.left_at).toLocaleDateString('fr-FR')}` : ' → actuel'}
                    {h.leave_reason && (
                      <span className="ml-1 italic" style={{ color: 'var(--text-muted)' }}>({h.leave_reason})</span>
                    )}
                  </li>
                ))}
              </ul>
            </div>
          )}
          {cartels.length > 0 && (
            <div>
              <p className="mb-0.5" style={{ color: 'var(--color-gold-light)' }}>Cartels ({cartels.length})</p>
              <ul className="space-y-0.5" style={{ color: 'var(--text-secondary)' }}>
                {cartels.map((h: any) => (
                  <li key={h.id}>
                    <b style={{ color: 'var(--text-primary)' }}>{h.cartel_name}</b>
                    {h.was_admin && <span className="ml-1 text-[9px]" style={{ color: 'var(--color-gold-light)' }}>[admin]</span>}
                    {' · '}
                    {new Date(h.joined_at).toLocaleDateString('fr-FR')}
                    {h.left_at ? ` → ${new Date(h.left_at).toLocaleDateString('fr-FR')}` : ' → actuel'}
                    {h.leave_reason && (
                      <span className="ml-1 italic" style={{ color: 'var(--text-muted)' }}>({h.leave_reason})</span>
                    )}
                  </li>
                ))}
              </ul>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

/* ─── Residence Tab ─── */
function ResidenceTab() {
  const { player } = useGameStore();
  const [residences, setResidences] = useState<Residence[]>([]);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!player?.id) return;
    apiFetch<Residence[]>(`/api/property/residences`)
      .then((res) => setResidences(Array.isArray(res) ? res : []))
      .catch(() => setResidences([]))
      .finally(() => setLoading(false));
  }, [player?.id]);

  if (loading) return <LoadingState />;
  if (residences.length === 0) return <EmptyState icon={Home} text={t('sidebar_left.no_residence')} />;

  return (
    <div className="space-y-2">
      <h3 className="font-impact text-xs" style={{ color: 'var(--color-gold)' }}>Residences ({residences.length})</h3>
      {residences.map((r) => (
        <div key={r.id} className="p-2 rounded" style={{ background: 'var(--bg-tertiary)', border: '1px solid var(--border-dark)' }}>
          <p className="text-xs font-bold" style={{ color: 'var(--text-primary)' }}>{r.name}</p>
          <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>{r.type}</p>
          {r.rent_cost != null && <p className="text-[10px]" style={{ color: 'var(--color-red)' }}>-{r.rent_cost}∞/jour</p>}
        </div>
      ))}
    </div>
  );
}

/* ─── Employment Tab — MES EMPLOIS uniquement (annonces dans Journal/Phone) ─── */
function EmploymentTab() {
  const { player } = useGameStore();
  const [myJobs, setMyJobs] = useState<MyJob[]>([]);
  const [loading, setLoading] = useState(true);
  const [workHoursMap, setWorkHoursMap] = useState<Record<string, number>>({});
  const [starting, setStarting] = useState<string | null>(null);
  const [message, setMessage] = useState<{ type: 'ok' | 'err'; text: string } | null>(null);

  const reload = () => {
    if (!player?.id) return;
    setLoading(true);
    apiFetch<MyJob[]>('/api/employment/my-jobs')
      .then((jobs) => {
        const list = Array.isArray(jobs) ? jobs : [];
        setMyJobs(list);
        const hours: Record<string, number> = {};
        for (const j of list) hours[j.id] = j.min_hours;
        setWorkHoursMap(hours);
      })
      .catch(() => setMyJobs([]))
      .finally(() => setLoading(false));
  };

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

  const handleStartWork = async (jobId: string) => {
    setStarting(jobId);
    setMessage(null);
    try {
      const hours = workHoursMap[jobId] || 4;
      await apiFetch('/api/employment/start-work', {
        method: 'POST',
        body: JSON.stringify({ job_id: jobId, duration_hours: hours }),
        headers: { 'Content-Type': 'application/json' },
      });
      setMessage({ type: 'ok', text: `Parti au travail pour ${hours}h` });
      reload();
    } catch (err: any) {
      setMessage({ type: 'err', text: err.message || 'Erreur' });
    } finally {
      setStarting(null);
    }
  };

  const handleQuit = async (jobId: string) => {
    try {
      await apiFetch('/api/employment/quit', {
        method: 'POST',
        body: JSON.stringify({ job_id: jobId }),
        headers: { 'Content-Type': 'application/json' },
      });
      setMessage({ type: 'ok', text: 'Vous avez demissionne' });
      reload();
    } catch (err: any) {
      setMessage({ type: 'err', text: err.message });
    }
  };

  if (loading) return <LoadingState />;

  return (
    <div className="space-y-3">
      <h3 className="font-impact text-xs" style={{ color: 'var(--color-gold)' }}>Mes Emplois</h3>

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

      {myJobs.length === 0 ? (
        <div className="space-y-2">
          <EmptyState icon={Briefcase} text="Aucun emploi" />
          <p className="text-[9px] text-center" style={{ color: 'var(--text-muted)' }}>
            Consultez les annonces dans le Journal ou l'app Emploi du telephone.
          </p>
        </div>
      ) : (
        myJobs.map((job) => {
          const hoursOptions = [];
          for (let h = job.min_hours; h <= job.max_hours; h++) hoursOptions.push(h);

          return (
            <div key={job.id} className="p-2 rounded" style={{ background: 'var(--bg-tertiary)', border: '1px solid var(--color-gold-dark)' }}>
              <p className="text-xs font-bold" style={{ color: 'var(--text-primary)' }}>{job.employer_name}</p>
              <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>{job.type} — {job.hourly_rate}∞/h</p>
              <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
                Fiches: {job.total_payslips} | {job.is_cdi ? 'CDI' : 'CDD'} | {job.min_hours}-{job.max_hours}h
              </p>

              {job.is_working ? (
                <p className="text-[10px] mt-1 font-bold" style={{ color: '#22c55e' }}>
                  Au travail...{job.work_ends_at && ` (fin ${new Date(job.work_ends_at).toLocaleTimeString('fr-FR', { hour: '2-digit', minute: '2-digit' })})`}
                </p>
              ) : (
                <div className="mt-2 flex items-center gap-1.5">
                  <select
                    value={workHoursMap[job.id] || job.min_hours}
                    onChange={e => setWorkHoursMap(prev => ({ ...prev, [job.id]: Number(e.target.value) }))}
                    className="text-[10px] px-1.5 py-1 rounded"
                    style={{ background: 'var(--bg-primary)', color: 'var(--text-primary)', border: '1px solid var(--border-dark)' }}
                  >
                    {hoursOptions.map(h => <option key={h} value={h}>{h}h</option>)}
                  </select>
                  <button
                    onClick={() => handleStartWork(job.id)}
                    disabled={starting === job.id}
                    className="flex-1 text-[10px] font-bold px-2 py-1 rounded"
                    style={{ background: 'var(--color-gold)', color: '#000', opacity: starting === job.id ? 0.5 : 1 }}
                  >
                    Aller au travail
                  </button>
                </div>
              )}

              <button
                onClick={() => handleQuit(job.id)}
                className="mt-1.5 text-[9px] w-full py-1 rounded hover:opacity-80"
                style={{ background: 'rgba(239,68,68,0.1)', color: '#ef4444', border: '1px solid rgba(239,68,68,0.2)' }}
              >
                Demissionner
              </button>
            </div>
          );
        })
      )}
    </div>
  );
}

/* ─── Inventory Tab ─── */
function InventoryTab() {
  const { player } = useGameStore();
  const setGauges = useGameStore((s) => s.setGauges);
  const setHealth = useGameStore((s) => s.setHealth);
  const [items, setItems] = useState<InventoryItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [usingId, setUsingId] = useState<string | null>(null);

  useEffect(() => {
    if (!player?.id) return;
    setLoading(true);
    apiFetch<InventoryItem[]>(`/api/player/${player.id}/inventory`)
      .then((res) => setItems(Array.isArray(res) ? res : []))
      .catch(() => setItems([]))
      .finally(() => setLoading(false));
  }, [player?.id]);

  if (loading) return <LoadingState />;
  if (items.length === 0) return <EmptyState icon={Package} text={t('sidebar.inventory_empty')} />;

  // Weight calculation: sum weight_grams of items on_person
  const onPersonItems = items.filter((i) => !i.storage_condition || i.storage_condition === 'on_person');
  const carriedGrams = onPersonItems.reduce((sum, i) => sum + (Number(i.weight_grams) || 0) * i.quantity, 0);
  const carriedKg = carriedGrams / 1000;
  const maxKg = 15; // Default without backpack
  const weightPct = maxKg > 0 ? (carriedKg / maxKg) * 100 : 0;

  return (
    <div className="space-y-2">
      <h3 className="font-impact text-xs" style={{ color: 'var(--color-gold)' }}>
        {t('sidebar.inventory')} ({items.length})
      </h3>

      {/* Weight bar */}
      <div>
        <div className="flex justify-between text-[10px] mb-1">
          <span style={{ color: 'var(--text-muted)' }}>{t('sidebar.weight')}</span>
          <span style={{ color: weightPct > 100 ? 'var(--color-red)' : weightPct > 70 ? '#f59e0b' : 'var(--text-muted)' }}>
            {carriedKg.toFixed(1)} / {maxKg} kg
          </span>
        </div>
        <div className="h-1.5 rounded-full overflow-hidden" style={{ background: 'var(--bg-tertiary)' }}>
          <div
            className="h-full rounded-full transition-all"
            style={{
              width: `${Math.min(weightPct, 100)}%`,
              background: weightPct > 100 ? '#ef4444' : weightPct > 70 ? '#f59e0b' : '#22c55e',
            }}
          />
        </div>
      </div>

      {items.map((item) => {
        const isOnPerson = !item.storage_condition || item.storage_condition === 'on_person';
        const isConsumable = isOnPerson && ['food', 'dish', 'meal'].includes(String(item.item_type || '').toLowerCase());

        const useItem = async () => {
          if (!player?.id || usingId) return;
          setUsingId(item.id);
          try {
            await api.player.useInventoryItem(player.id, item.id);
            const next = await apiFetch<InventoryItem[]>(`/api/player/${player.id}/inventory`).catch(() => []);
            setItems(Array.isArray(next) ? next : []);
            // Phase 8 v2 (2026-05-01) — refresh gauges + health après usage
            // d'item (food consommé peut affecter physical_health).
            const [gauges, health] = await Promise.all([
              api.player.getGauges(player.id).catch(() => null),
              api.player.getHealth(player.id).catch(() => null),
            ]);
            if (gauges) setGauges(gauges as any);
            if (health) setHealth(health as any);
          } finally {
            setUsingId(null);
          }
        };

        return (
          <div key={item.id} className="flex items-center justify-between gap-2 p-2 rounded" style={{ background: 'var(--bg-tertiary)' }}>
            <div className="min-w-0">
              <span className="text-xs truncate block" style={{ color: 'var(--text-primary)' }}>{item.item_subtype || item.item_type}</span>
              {!isOnPerson && (
                <span className="text-[9px]" style={{ color: 'var(--text-muted)' }}>{item.storage_condition}</span>
              )}
            </div>
            <div className="flex items-center gap-2">
              <span className="text-xs font-mono" style={{ color: 'var(--color-gold)' }}>x{item.quantity}</span>
              {isConsumable && (
                <button
                  type="button"
                  onClick={useItem}
                  disabled={usingId === item.id}
                  className="px-2 py-1 rounded text-[10px] font-bold disabled:opacity-50"
                  style={{ background: 'rgba(34,197,94,0.15)', border: '1px solid rgba(34,197,94,0.35)', color: '#22c55e' }}
                >
                  {usingId === item.id ? '…' : 'Manger'}
                </button>
              )}
            </div>
          </div>
        );
      })}
    </div>
  );
}

/* ─── Vehicle Tab ─── */
function VehicleTab() {
  const { player, updatePlayer } = useGameStore();
  const [vehicles, setVehicles] = useState<Vehicle[]>([]);
  const [loading, setLoading] = useState(true);
  const [selectedId, setSelectedId] = useState<string>('none');
  const [saving, setSaving] = useState(false);

  useEffect(() => {
    if (!player?.id) return;
    apiFetch<Vehicle[]>(`/api/property/vehicles`)
      .then((res) => {
        const list = Array.isArray(res) ? res : [];
        setVehicles(list);
        setSelectedId(player.active_vehicle_id || 'none');
      })
      .catch(() => setVehicles([]))
      .finally(() => setLoading(false));
  }, [player?.id, player?.active_vehicle_id]);

  const handleAssign = async () => {
    if (!player?.id) return;
    setSaving(true);
    try {
      const body = { vehicle_id: selectedId === 'none' ? null : selectedId };
      const result = await apiFetch<any>(`/api/player/${player.id}/vehicle/assign`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(body),
      });
      updatePlayer({ active_vehicle_id: result.active_vehicle_id ?? null });
    } catch {
      // silent
    } finally {
      setSaving(false);
    }
  };

  if (loading) return <LoadingState />;
  if (vehicles.length === 0) return <EmptyState icon={Car} text={t('sidebar_left.no_vehicle')} />;

  const activeVehicle = vehicles.find((v) => v.id === selectedId);
  const needsSave = selectedId !== (player?.active_vehicle_id || 'none');

  return (
    <div className="space-y-2">
      <h3 className="font-impact text-xs" style={{ color: 'var(--color-gold)' }}>
        Véhicule actif
      </h3>

      {/* Dropdown sélection */}
      <select
        value={selectedId}
        onChange={(e) => setSelectedId(e.target.value)}
        className="w-full text-xs p-1.5 rounded"
        style={{
          background: 'var(--bg-tertiary)',
          border: '1px solid var(--border-dark)',
          color: 'var(--text-primary)',
        }}
      >
        <option value="none">Aucun véhicule assigné</option>
        {vehicles.map((v) => (
          <option key={v.id} value={v.id}>
            {v.name || v.model_name || v.model || v.type}
          </option>
        ))}
      </select>

      {/* Bouton Valider */}
      {needsSave && (
        <button
          onClick={handleAssign}
          disabled={saving}
          className="w-full text-xs py-1 rounded font-bold"
          style={{
            background: 'rgba(234,179,8,0.2)',
            border: '1px solid rgba(234,179,8,0.5)',
            color: '#eab308',
            opacity: saving ? 0.5 : 1,
          }}
        >
          {saving ? '...' : 'Valider'}
        </button>
      )}

      {/* Caractéristiques du véhicule sélectionné */}
      {activeVehicle && (
        <div
          className="p-2 rounded space-y-1"
          style={{ background: 'var(--bg-tertiary)', border: '1px solid var(--border-dark)' }}
        >
          <p className="text-xs font-bold" style={{ color: 'var(--text-primary)' }}>
            {activeVehicle.name || activeVehicle.model_name || activeVehicle.model}
          </p>
          <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
            {activeVehicle.type}
          </p>
          <div className="grid grid-cols-2 gap-x-2 gap-y-0.5 mt-1">
            {activeVehicle.speed != null && (
              <>
                <span className="text-[10px]" style={{ color: 'var(--text-secondary)' }}>Vitesse</span>
                <span className="text-[10px] font-mono text-right" style={{ color: 'var(--color-gold)' }}>{activeVehicle.speed} km/h</span>
              </>
            )}
            {activeVehicle.armor != null && (
              <>
                <span className="text-[10px]" style={{ color: 'var(--text-secondary)' }}>Blindage</span>
                <span className="text-[10px] font-mono text-right" style={{ color: 'var(--color-gold)' }}>{activeVehicle.armor}</span>
              </>
            )}
            {activeVehicle.seats != null && (
              <>
                <span className="text-[10px]" style={{ color: 'var(--text-secondary)' }}>Places</span>
                <span className="text-[10px] font-mono text-right" style={{ color: 'var(--color-gold)' }}>{activeVehicle.seats}</span>
              </>
            )}
            {activeVehicle.storage_capacity != null && (
              <>
                <span className="text-[10px]" style={{ color: 'var(--text-secondary)' }}>Stockage</span>
                <span className="text-[10px] font-mono text-right" style={{ color: 'var(--color-gold)' }}>{activeVehicle.storage_capacity} kg</span>
              </>
            )}
            {activeVehicle.condition != null && (
              <>
                <span className="text-[10px]" style={{ color: 'var(--text-secondary)' }}>État</span>
                <span className="text-[10px] font-mono text-right" style={{ color: 'var(--color-gold)' }}>{activeVehicle.condition}%</span>
              </>
            )}
            {activeVehicle.fuel_consumption != null && (
              <>
                <span className="text-[10px]" style={{ color: 'var(--text-secondary)' }}>Conso.</span>
                <span className="text-[10px] font-mono text-right" style={{ color: 'var(--color-gold)' }}>{activeVehicle.fuel_consumption} L/100</span>
              </>
            )}
            {activeVehicle.maintenance_per_day != null && (
              <>
                <span className="text-[10px]" style={{ color: 'var(--text-secondary)' }}>Entretien</span>
                <span className="text-[10px] font-mono text-right" style={{ color: 'var(--color-gold)' }}>{activeVehicle.maintenance_per_day} ∞/j</span>
              </>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

/* ─── Shared Components ─── */
function GaugeBar({ label, value, max }: { label: string; value: number; max: number }) {
  const pct = Math.min(100, (value / max) * 100);
  return (
    <div>
      <div className="flex justify-between text-[10px] mb-0.5">
        <span style={{ color: 'var(--text-secondary)' }}>{label}</span>
        <span className="font-mono" style={{ color: 'var(--color-gold)' }}>{value}</span>
      </div>
      <div className="h-1 rounded" style={{ background: 'var(--bg-tertiary)' }}>
        <div className="h-1 rounded" style={{ width: `${pct}%`, background: 'var(--color-gold)' }} />
      </div>
    </div>
  );
}

function ProgressRow({ label, value, color }: { label: string; value: number; color: string }) {
  return (
    <div className="flex justify-between text-[10px]">
      <span style={{ color: 'var(--text-secondary)' }}>{label}</span>
      <span className="font-mono font-bold" style={{ color }}>Tier {value}</span>
    </div>
  );
}

function LoadingState() {
  return (
    <div className="text-center py-8">
      <div className="w-5 h-5 border-2 border-t-transparent rounded-full animate-spin mx-auto mb-2" style={{ borderColor: 'var(--color-gold)', borderTopColor: 'transparent' }} />
      <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>Chargement...</p>
    </div>
  );
}

function EmptyState({ icon: Icon, text }: { icon: React.ComponentType<{ size: number; style: React.CSSProperties; className?: string }>; text: 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)' }}>{text}</p>
    </div>
  );
}

function PlaceholderTab({ icon: Icon, label }: { icon: React.ComponentType<{ size: number; style: React.CSSProperties; className?: string }>; label: 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)' }}>{label}</p>
      <p className="text-[10px] mt-1" style={{ color: 'var(--text-muted)' }}>Bientot disponible</p>
    </div>
  );
}
