'use client';
/**
 * CartelPaneV2 — Tab Gestion Cartel (Phase 14, 19-04-2026).
 *
 * Remplace l'ancien CartelPane (`Footer.tsx` lignes 601-707) en supprimant les
 * liens `/account#cartel` interdits. Tout se passe inline dans le footer.
 *
 * Modes :
 *  - idle : boutons "Monter un Cartel" (gold) + "Rejoindre un Cartel" (rouge)
 *  - create : formulaire inline (nom, description, gouvernance, origin lat/lng)
 *  - join : liste des cartels actifs par proximité + bouton Rejoindre
 *  - member : dashboard (stats, trésorerie, membres, territoires, actions)
 *  - admin : + actions admin (dissoudre, assigner territoire, spécialistes, reduce-heat)
 */
import { useState, useEffect, useCallback } from 'react';
import { api } from '@/lib/api';
import {
  DiplomatLightbox,
  TerritoryLostLightbox,
  CartelCreationIntroLightbox,
  PrisonOverlayLightbox,
} from './CartelLightboxes';
import { GangManagementTabs } from '../gang/GangManagementTabs';
import { useMapPick, MapPickButton } from '../map/useMapPick';
import { AlliancesLightbox } from './AlliancesLightbox';

type Mode = 'idle' | 'create' | 'join' | 'member';

export function CartelPaneV2() {
  const [myCartel, setMyCartel] = useState<any>(null);
  const [allCartels, setAllCartels] = useState<any[]>([]);
  const [invitations, setInvitations] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [mode, setMode] = useState<Mode>('idle');
  const [joinSent, setJoinSent] = useState<string | null>(null);

  const refresh = useCallback(() => {
    setLoading(true);
    Promise.all([
      api.cartel.getMine().catch(() => null),
      api.cartel.listActive().catch(() => []),
      api.cartel.getMyInvitations().catch(() => []),
    ]).then(([mine, list, invs]) => {
      setMyCartel(mine || null);
      setAllCartels(Array.isArray(list) ? list as any[] : []);
      setInvitations(Array.isArray(invs) ? invs as any[] : []);
      setMode(mine ? 'member' : 'idle');
      setLoading(false);
    });
  }, []);

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

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

  // ── Membre : dashboard ──
  if (myCartel && mode === 'member') {
    return <MemberDashboard cartel={myCartel} onRefresh={refresh} />;
  }

  // ── Création ──
  if (mode === 'create') {
    return (
      <CreateCartelInline
        onCancel={() => setMode('idle')}
        onCreated={() => { setMode('idle'); refresh(); }}
      />
    );
  }

  // ── Rejoindre ──
  if (mode === 'join') {
    return (
      <JoinCartelList
        cartels={allCartels}
        onCancel={() => setMode('idle')}
        onApplied={(id) => setJoinSent(id)}
        joinSent={joinSent}
      />
    );
  }

  // ── Idle : deux boutons + invitations si présentes ──
  return (
    <div className="flex-1 min-h-0 overflow-y-auto space-y-2">
      {invitations.length > 0 && (
        <InvitationsBlock
          invitations={invitations}
          onAccept={async (id) => { await api.cartel.acceptInvitation(id); refresh(); }}
          onDecline={async (id) => { await api.cartel.declineInvitation(id); refresh(); }}
        />
      )}
      <div className="flex gap-2">
        <button type="button" className="new-order flex-1" onClick={() => setMode('create')}>
          ＋ Monter un Cartel
        </button>
        <button type="button" className="new-order is-red flex-1" onClick={() => setMode('join')}>
          Rejoindre un Cartel
        </button>
      </div>
      <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
        Le cartel regroupe plusieurs gangs sous une bannière commune.
      </p>
    </div>
  );
}

// ───────────────────────────────────────────────────────────
// Invitations reçues
// ───────────────────────────────────────────────────────────

function InvitationsBlock({ invitations, onAccept, onDecline }: {
  invitations: any[]; onAccept: (id: string) => void; onDecline: (id: string) => void;
}) {
  return (
    <div className="space-y-2" style={{ padding: 6, border: '1px solid var(--border-gold)', borderRadius: 8, background: 'rgba(212,168,67,0.04)' }}>
      <p className="text-[10px] font-bold" style={{ color: 'var(--color-gold-light)', letterSpacing: '.15em', fontFamily: 'var(--font-subtitle)' }}>
        INVITATIONS CARTEL
      </p>
      {invitations.map(inv => (
        <div key={inv.id} className="flex items-center gap-2 text-[11px]">
          <div className="flex-1 min-w-0 truncate">
            <span style={{ color: 'var(--text-primary)' }}>Cartel {inv.cartel_id.slice(0, 6)}…</span>
            {inv.message && <div className="text-[10px] truncate" style={{ color: 'var(--text-muted)' }}>{inv.message}</div>}
          </div>
          <button className="new-order" style={{ width: 60, padding: 4, fontSize: 10 }} onClick={() => onAccept(inv.id)}>OK</button>
          <button className="new-order is-red" style={{ width: 60, padding: 4, fontSize: 10 }} onClick={() => onDecline(inv.id)}>✕</button>
        </div>
      ))}
    </div>
  );
}

// ───────────────────────────────────────────────────────────
// Formulaire création cartel inline
// ───────────────────────────────────────────────────────────

function CreateCartelInline({ onCancel, onCreated }: {
  onCancel: () => void; onCreated: () => void;
}) {
  const [showIntro, setShowIntro] = useState(true);
  const [name, setName] = useState('');
  const [description, setDescription] = useState('');
  const [governance, setGovernance] = useState<'leader_decides' | 'majority_vote'>('leader_decides');
  const [rulesText, setRulesText] = useState('');
  // Phase 15 Commit 2 (20-04-2026) — map-pick obligatoire (hook partagé)
  const { pickedLat, pickedLng, startPick, pickBanner } = useMapPick({
    label: 'Création cartel · cliquez sur la carte pour placer le point d\'origine',
    scope: 'cartel',
    orderKey: 'create-cartel',
  });
  const [creating, setCreating] = useState(false);
  const [err, setErr] = useState<string | null>(null);
  const COST = 250000;

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

  // Mode map-pick : le hook rend le bandeau bas en portail ; on retourne
  // juste ce bandeau et on cache le formulaire pendant le clic.
  if (pickBanner) return pickBanner;

  return (
    <>
      <CartelCreationIntroLightbox
        open={showIntro}
        onClose={() => { setShowIntro(false); onCancel(); }}
        onProceed={() => setShowIntro(false)}
        cost={COST}
      />
      {!showIntro && (
        <div className="flex-1 min-h-0 overflow-y-auto space-y-2">
          <p className="text-[10px] font-bold" style={{ color: 'var(--color-gold)', letterSpacing: '.15em', fontFamily: 'var(--font-subtitle)' }}>
            CRÉER UN CARTEL
          </p>
          <input
            type="text"
            value={name}
            onChange={(e) => setName(e.target.value)}
            placeholder="Nom du cartel"
            maxLength={100}
            className="w-full px-3 py-2 rounded-lg text-xs"
            style={{ background: 'var(--bg-tertiary)', border: '1px solid var(--border-dark)', color: 'var(--text-primary)' }}
          />
          <textarea
            value={description}
            onChange={(e) => setDescription(e.target.value)}
            placeholder="Description (optionnel)"
            rows={2}
            className="w-full px-3 py-2 rounded-lg text-xs"
            style={{ background: 'var(--bg-tertiary)', border: '1px solid var(--border-dark)', color: 'var(--text-primary)', resize: 'vertical' }}
          />
          <textarea
            value={rulesText}
            onChange={(e) => setRulesText(e.target.value)}
            placeholder="Règles du cartel (affichées aux candidats)"
            rows={2}
            className="w-full px-3 py-2 rounded-lg text-xs"
            style={{ background: 'var(--bg-tertiary)', border: '1px solid var(--border-dark)', color: 'var(--text-primary)', resize: 'vertical' }}
          />
          <select
            value={governance}
            onChange={(e) => setGovernance(e.target.value as any)}
            className="w-full px-3 py-2 rounded-lg text-xs"
            style={{ background: 'var(--bg-tertiary)', border: '1px solid var(--border-dark)', color: 'var(--text-primary)' }}
          >
            <option value="leader_decides">Le leader décide</option>
            <option value="majority_vote">Vote majoritaire</option>
          </select>
          {/* Map-pick obligatoire — remplace les anciens inputs lat/lng + géoloc */}
          <MapPickButton
            pickedLat={pickedLat} pickedLng={pickedLng} onClick={startPick}
            idleLabel="Choisir le point d'origine sur la carte"
          />
          {err && <p className="text-[10px]" style={{ color: 'var(--color-red)' }}>{err}</p>}
          <div className="flex gap-2">
            <button type="button" className="new-order is-red flex-1" onClick={onCancel}>Annuler</button>
            <button
              type="button"
              className="new-order flex-1"
              disabled={creating || pickedLat === null}
              onClick={handleCreate}
              title={pickedLat === null ? 'Choisissez d\'abord un point sur la carte' : undefined}
            >
              {creating ? '…' : `Créer (${COST.toLocaleString('fr-FR')} ∞)`}
            </button>
          </div>
          <p className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
            Les fonds sont transférés à la trésorerie du cartel (non consommés).
          </p>
        </div>
      )}
    </>
  );
}

// ───────────────────────────────────────────────────────────
// Liste des cartels à rejoindre (triés par proximité)
// ───────────────────────────────────────────────────────────

function JoinCartelList({ cartels, onCancel, onApplied, joinSent }: {
  cartels: any[]; onCancel: () => void; onApplied: (id: string) => void; joinSent: string | null;
}) {
  return (
    <div className="flex-1 min-h-0 overflow-y-auto space-y-2">
      <div className="flex justify-between items-center">
        <p className="text-[10px] font-bold" style={{ color: 'var(--color-red-light)', letterSpacing: '.15em', fontFamily: 'var(--font-subtitle)' }}>
          REJOINDRE UN CARTEL
        </p>
        <button type="button" className="text-[10px] underline" style={{ color: 'var(--text-muted)' }} onClick={onCancel}>Fermer</button>
      </div>
      <div className="cartel-join">
        <div className="cartel-join-head">
          <span>Nom</span><span>XP</span><span>M.</span><span /><span />
        </div>
        {cartels.length === 0 ? (
          <p className="text-[10px] py-2" style={{ color: 'var(--text-muted)' }}>Aucun cartel ouvert.</p>
        ) : cartels.map((c: any) => (
          <div key={c.id} className="cartel-row">
            <span className="c-name" title={c.name}>{c.name}</span>
            <span className="c-xp">{c.xp ?? 0}</span>
            <span className="c-mem">{c.member_count ?? 0}</span>
            <span style={{ fontSize: 9, color: 'var(--text-muted)' }}>
              {c.distance_m != null ? `${(c.distance_m / 1000).toFixed(1)}km` : ''}
            </span>
            <button
              type="button"
              className="c-join"
              disabled={joinSent === c.id}
              onClick={async () => {
                try {
                  await api.cartel.apply(c.id, {});
                  onApplied(c.id);
                } catch {/* silent */}
              }}
            >
              {joinSent === c.id ? 'Envoyé' : 'Rejoindre'}
            </button>
          </div>
        ))}
      </div>
    </div>
  );
}

// ───────────────────────────────────────────────────────────
// Dashboard membre d'un cartel
// ───────────────────────────────────────────────────────────

function MemberDashboard({ cartel, onRefresh }: { cartel: any; onRefresh: () => void }) {
  const [showDiplomat, setShowDiplomat] = useState(false);
  const [showTerritoryLost, setShowTerritoryLost] = useState(false);
  const [showAlliances, setShowAlliances] = useState(false);
  const [diplomatLoading, setDiplomatLoading] = useState(false);
  const [assigningTerritory, setAssigningTerritory] = useState(false);
  const heat = Number(cartel.heat_current) || 0;
  const custodyActive = cartel.custody_until && new Date(cartel.custody_until) > new Date();
  const territoryLost = cartel.territory_lost_at && (!cartel.territories || cartel.territories.length === 0);
  const isAdmin = cartel.members?.some((m: any) => m.is_admin);

  useEffect(() => { if (territoryLost) setShowTerritoryLost(true); }, [territoryLost]);

  // Phase 15 Commit 7 (20-04-2026) — diplomate 3 paliers hebdo
  const [diplomatStatus, setDiplomatStatus] = useState<any>(null);
  useEffect(() => {
    if (!showDiplomat) return;
    api.cartel.getDiplomatStatus(cartel.id).then(setDiplomatStatus).catch(() => setDiplomatStatus(null));
  }, [showDiplomat, cartel.id]);

  const handleDiplomat = async (tier: 1 | 2 | 3) => {
    setDiplomatLoading(true);
    try {
      const res: any = await api.cartel.reduceHeat(cartel.id, tier);
      if (res?.success === false) {
        alert(res.message || 'Impossible');
        return;
      }
      // Refresh status pour maj des compteurs hebdo affichés
      api.cartel.getDiplomatStatus(cartel.id).then(setDiplomatStatus).catch(() => {});
      setShowDiplomat(false);
      onRefresh();
    } catch (e: any) {
      alert(e?.message || 'Erreur');
    } finally { setDiplomatLoading(false); }
  };

  const handleAssignTerritory = async () => {
    if (!navigator.geolocation) return;
    setAssigningTerritory(true);
    navigator.geolocation.getCurrentPosition(async (pos) => {
      try {
        await api.cartel.assignTerritory(cartel.id, pos.coords.latitude, pos.coords.longitude);
        setShowTerritoryLost(false);
        onRefresh();
      } finally { setAssigningTerritory(false); }
    }, () => setAssigningTerritory(false));
  };

  return (
    <div className="flex-1 min-h-0 overflow-y-auto space-y-2 relative">
      {custodyActive && (
        <PrisonOverlayLightbox
          onTakeControl={() => {
            // Phase 15 (20-04-2026) — Prise de contrôle pendant admin en
            // custody : dispatch wizard attack sur le point d'origine du
            // cartel. En cas de victoire, attack() post-processe via
            // CartelTakeoverService.takeover() côté backend.
            const origin = cartel.territories?.find((t: any) => t.is_origin) ?? cartel.territories?.[0];
            if (!origin) {
              alert('Aucun point de territoire cartel à attaquer — le cartel a déjà tout perdu.');
              return;
            }
            window.dispatchEvent(new CustomEvent('order-wizard-open', {
              detail: {
                scope: 'gang',
                key: 'attack',
                target: { poi_type: 'cartel_territory', poi_id: origin.id },
              },
            }));
          }}
          onDefend={() => {
            // Défendre = assigner guards sur le point d'origine — le cartel
            // reste actuel (overlay se lèvera à la fin de la custody admin).
            const origin = cartel.territories?.find((t: any) => t.is_origin) ?? cartel.territories?.[0];
            if (!origin) {
              alert('Aucun point de territoire à défendre.');
              return;
            }
            window.dispatchEvent(new CustomEvent('order-wizard-open', {
              detail: {
                scope: 'gang',
                key: 'guard',
                target: { poi_type: 'cartel_territory', poi_id: origin.id },
              },
            }));
          }}
        />
      )}
      <DiplomatLightbox
        open={showDiplomat}
        onClose={() => setShowDiplomat(false)}
        onConfirm={handleDiplomat}
        loading={diplomatLoading}
        status={diplomatStatus}
      />
      <TerritoryLostLightbox open={showTerritoryLost} onClose={() => setShowTerritoryLost(false)} onAssign={handleAssignTerritory} />

      <div className="empire-head">
        <span className="gang-name">{cartel.name}</span>
        <span className="availability">XP {cartel.xp ?? 0} · {cartel.member_count ?? 0} gangs</span>
      </div>

      <div>
        <div className="flex items-center justify-between mb-1">
          <span className="heat-bar-label">CHALEUR {heat.toFixed(0)}/100</span>
          <button type="button" className="text-[9px] underline" style={{ color: 'var(--color-gold-light)' }} onClick={() => setShowDiplomat(true)}>
            Baisser Chaleur
          </button>
        </div>
        <div className="heat-bar"><div className="heat-fill" style={{ width: `${heat}%` }} /></div>
      </div>

      <div className="text-[11px] grid grid-cols-2 gap-1" style={{ color: 'var(--text-secondary)' }}>
        <div>Influence totale : <b>{cartel.stats?.influence_total ?? 0}</b></div>
        <div>Respect moyen : <b>{cartel.stats?.respect_average ?? 0}</b></div>
        <div>Trésor lumière : <b>{(cartel.stats?.treasury_light ?? 0).toLocaleString('fr-FR')}</b></div>
        <div>Trésor ombre : <b>{(cartel.stats?.treasury_shadow ?? 0).toLocaleString('fr-FR')}</b></div>
      </div>

      {cartel.territories?.length > 0 && (
        <div className="text-[10px]" style={{ color: 'var(--text-muted)' }}>
          Points : {cartel.territories.length} · HP {cartel.territories.reduce((s: number, t: any) => s + Number(t.hp), 0)}
        </div>
      )}

      {/* Phase 17.2 finition Gap 1 (2026-05-06) — Widget Alliances proéminent
          visible par tous les membres. Ouvre AlliancesLightbox. */}
      <AlliancesWidget cartelId={cartel.id} onOpen={() => setShowAlliances(true)} />

      {isAdmin && (
        <div className="flex gap-2">
          <button type="button" className="new-order flex-1" style={{ fontSize: 10 }} onClick={handleAssignTerritory} disabled={assigningTerritory}>
            {assigningTerritory ? '…' : 'Assigner Territoire'}
          </button>
          <button type="button" className="new-order flex-1" style={{ fontSize: 10 }} onClick={() => setShowAlliances(true)}>
            Gérer Alliances
          </button>
        </div>
      )}

      {showAlliances && (
        <AlliancesLightbox ownCartelId={cartel.id} onClose={() => setShowAlliances(false)} />
      )}

      {cartel.rules_text && (
        <p className="text-[11px]" style={{ color: 'var(--text-secondary)', lineHeight: 1.45 }}>
          {cartel.rules_text}
        </p>
      )}

      {/* Tabs Personnel / Armurerie / Véhicules (Phase 15, 19-04-2026) */}
      <GangManagementTabs scope={{ type: 'cartel', id: cartel.id }} />
    </div>
  );
}

// ───────────────────────────────────────────────────────────
// Phase 17.2 finition Gap 1 + 2 (2026-05-06) — Widget Alliances proéminent
// + Banner inline Accept/Reject pour les propositions reçues.
// ───────────────────────────────────────────────────────────
type IncomingRow = {
  id: string;
  requester_cartel_id: string;
  requested_by_player_id: string;
  requested_at: string;
};

function AlliancesWidget({ cartelId, onOpen }: { cartelId: string; onOpen: () => void }) {
  const [stats, setStats] = useState({ active: 0, incoming: 0, outgoing: 0 });
  const [incomings, setIncomings] = useState<IncomingRow[]>([]);
  const [loading, setLoading] = useState(true);
  const [expanded, setExpanded] = useState(false);
  const [busyId, setBusyId] = useState<string | null>(null);
  const [requesterNames, setRequesterNames] = useState<Map<string, string>>(new Map());

  const refresh = useCallback(async () => {
    try {
      const [active, incoming, outgoing] = await Promise.all([
        api.cartelAlliance.active().catch(() => []),
        api.cartelAlliance.incoming().catch(() => []),
        api.cartelAlliance.outgoing().catch(() => []),
      ]);
      const incomingArr = (Array.isArray(incoming) ? incoming : []) as IncomingRow[];
      setStats({
        active: Array.isArray(active) ? active.length : 0,
        incoming: incomingArr.length,
        outgoing: Array.isArray(outgoing) ? outgoing.length : 0,
      });
      setIncomings(incomingArr);

      // Résolution des noms cartel proposants (parallèle)
      if (incomingArr.length > 0) {
        const entries = await Promise.all(incomingArr.map(async (row) => {
          try {
            const c = await api.cartel.getDetails(row.requester_cartel_id) as { name?: string };
            return [row.requester_cartel_id, c?.name || '(cartel inconnu)'] as const;
          } catch {
            return [row.requester_cartel_id, '(cartel inconnu)'] as const;
          }
        }));
        setRequesterNames(new Map(entries));
      } else {
        setRequesterNames(new Map());
      }
    } finally {
      setLoading(false);
    }
  }, []);

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

  // Don't pollute UI when nothing to show & not loading
  if (loading) return null;
  const hasIncoming = stats.incoming > 0;
  const totalDiplomatic = stats.active + stats.incoming + stats.outgoing;
  if (totalDiplomatic === 0) return null;

  const handleAccept = async (id: string) => {
    setBusyId(id);
    try {
      await api.cartelAlliance.accept(id);
      await refresh();
    } catch (e: unknown) {
      alert(e instanceof Error ? e.message : 'Échec');
    } finally { setBusyId(null); }
  };
  const handleReject = async (id: string) => {
    setBusyId(id);
    try {
      await api.cartelAlliance.reject(id);
      await refresh();
    } catch (e: unknown) {
      alert(e instanceof Error ? e.message : 'Échec');
    } finally { setBusyId(null); }
  };

  return (
    <div
      className="w-full rounded-lg overflow-hidden"
      style={{
        background: hasIncoming ? 'rgba(251,191,36,0.10)' : 'rgba(34,197,94,0.06)',
        border: `1px solid ${hasIncoming ? 'rgba(251,191,36,0.4)' : 'rgba(34,197,94,0.25)'}`,
      }}
    >
      <div className="flex items-center gap-2 p-2">
        <span style={{ fontSize: 14 }}>{hasIncoming ? '🤝' : '🟢'}</span>
        <span className="text-[10px] flex-1" style={{ color: 'var(--text-secondary)' }}>
          <b style={{ color: stats.active > 0 ? '#22c55e' : 'var(--text-muted)' }}>
            {stats.active} allié{stats.active > 1 ? 's' : ''}
          </b>
          {stats.incoming > 0 && (
            <>
              {' · '}
              <b style={{ color: '#fbbf24' }}>⏳ {stats.incoming} reçue{stats.incoming > 1 ? 's' : ''}</b>
            </>
          )}
          {stats.outgoing > 0 && (
            <>
              {' · '}
              <span style={{ color: 'var(--text-muted)' }}>
                {stats.outgoing} envoyée{stats.outgoing > 1 ? 's' : ''}
              </span>
            </>
          )}
        </span>
        {hasIncoming && (
          <button
            type="button"
            onClick={() => setExpanded((v) => !v)}
            className="text-[9px] px-2 py-1 rounded"
            style={{ background: 'transparent', border: '1px solid rgba(251,191,36,0.4)', color: '#fbbf24' }}
          >
            {expanded ? 'Réduire' : 'Voir'}
          </button>
        )}
        <button
          type="button"
          onClick={onOpen}
          className="text-[9px]"
          style={{ color: 'var(--text-muted)', background: 'transparent', border: 'none' }}
        >
          Diplomatie ▸
        </button>
      </div>

      {/* Phase 17.2 Gap 2 — Inline Accept/Reject pour chaque proposition reçue */}
      {expanded && hasIncoming && (
        <div className="px-2 pb-2 space-y-1.5" style={{ borderTop: '1px solid rgba(251,191,36,0.2)' }}>
          {incomings.map((row) => (
            <div
              key={row.id}
              className="flex items-center gap-2 p-2 rounded"
              style={{
                background: 'rgba(0,0,0,0.25)',
                border: '1px solid rgba(251,191,36,0.25)',
              }}
            >
              <div className="flex-1 min-w-0">
                <div className="text-[10px] font-bold truncate" style={{ color: 'var(--text-primary)' }}>
                  {requesterNames.get(row.requester_cartel_id) || '(cartel inconnu)'}
                </div>
                <div className="text-[9px]" style={{ color: 'var(--text-muted)' }}>
                  Proposé le {new Date(row.requested_at).toLocaleDateString('fr-FR')}
                </div>
              </div>
              <button
                type="button"
                disabled={busyId === row.id}
                onClick={() => handleAccept(row.id)}
                className="text-[9px] px-2 py-1 rounded"
                style={{
                  background: 'rgba(34,197,94,0.2)',
                  border: '1px solid rgba(34,197,94,0.5)',
                  color: '#22c55e',
                  opacity: busyId === row.id ? 0.5 : 1,
                }}
              >
                ✓ Accepter
              </button>
              <button
                type="button"
                disabled={busyId === row.id}
                onClick={() => handleReject(row.id)}
                className="text-[9px] px-2 py-1 rounded"
                style={{
                  background: 'rgba(239,68,68,0.15)',
                  border: '1px solid rgba(239,68,68,0.4)',
                  color: '#ef4444',
                  opacity: busyId === row.id ? 0.5 : 1,
                }}
              >
                ✕ Refuser
              </button>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}

