/* JARVIS extended — Agent console with streaming, tools, memory, briefing, listing analysis, descriptions, negotiation, incognito */

const TOOLS = [
  { id: "search_products",      desc: "Filtre + tri catalogue produits",          icon: "search",  usage: 142 },
  { id: "get_supplier_stats",   desc: "Stats détaillées d'un fournisseur",        icon: "users",   usage: 38 },
  { id: "compute_profit",       desc: "Simulation de marge avec hypothèses",       icon: "dollar",  usage: 67 },
  { id: "send_message",         desc: "Poste un message dans un canal",            icon: "mail",    usage: 12 },
  { id: "create_task",          desc: "Crée une tâche assignée à un membre",       icon: "plus",    usage: 24 },
  { id: "run_kpi_recalc",       desc: "Force le recalcul d'un KPI spécifique",     icon: "refresh", usage: 19 },
  { id: "analyze_listing",      desc: "Analyse une page produit Amazon",           icon: "eye",     usage: 8 },
  { id: "generate_description", desc: "Génère description produit multilingue",    icon: "book",    usage: 14 },
];

const JARVIS_AGENT_HISTORY = [
  { id: "ag-001", ts: "14:22", goal: "Préparer call Hangzhou BambooLine",
    steps: [
      { ok: true,  text: "Recherche fournisseur · 12 datapoints récupérés" },
      { ok: true,  text: "Calcul marges si MOQ 150 vs 300 · sim 3 scénarios" },
      { ok: true,  text: "Pull historique 6 dernières commandes" },
      { ok: true,  text: "Génération argumentaire négociation (FR)" },
    ], status: "completed" },
  { id: "ag-002", ts: "12:18", goal: "Detect rupture stock 7j",
    steps: [
      { ok: true,  text: "Scan 18 produits actifs · velocité 30j" },
      { ok: true,  text: "Cross-ref ETAs PO en cours" },
      { ok: true,  text: "Couvre-volant cuir → rupture J+3 confirmée" },
      { ok: true,  text: "Alerte créée + Slack #ops notifié" },
    ], status: "completed" },
  { id: "ag-003", ts: "il y a 5min", goal: "Recalcul marge nette 30j",
    steps: [
      { ok: true,  text: "Pull payouts Amazon mai" },
      { ok: true,  text: "Aggregate COGS · 18 produits" },
      { ok: false, text: "Cache KV miss · refresh in progress…" },
    ], status: "running" },
];

const JarvisExtended = () => {
  const toast = useToastX();
  const [currentUser] = (window.useCurrentUser || (() => ["clarens"]))();
  const userInfo = ({
    clarens: { name: "Clarens", role: "CFO", focus: "finance, marges, trésorerie" },
    kevin:   { name: "Kevin",   role: "COO", focus: "fournisseurs, MOQ, délais" },
    carly:   { name: "Carly",   role: "CPO", focus: "produits, BSR, opportunités" },
  })[currentUser] || { name: "Clarens", role: "CFO", focus: "finance" };

  const [tab, setTab] = useState("chat");
  const [incognito, setIncognito] = useState(false);
  const [streaming, setStreaming] = useState(false);
  const [streamText, setStreamText] = useState("");
  const [messages, setMessages] = useState([
    { role: "assistant", content: `Bonjour ${userInfo.name}. Console JARVIS étendue · 8 tools disponibles · mode agent armé. Que voulez-vous accomplir ?`, t: "14:32" }
  ]);
  const [input, setInput] = useState("");
  const LS_JARVIS_MEM = "kcc:jarvis-memory";
  const MEM_SEED = [
    { k: "Préfère réponses concises sans intro", set: "il y a 3 sem." },
    { k: "Cible marge minimum 25% (override 22% défaut)", set: "il y a 2 mois" },
    { k: "Devise affichée : CAD (équivalent toujours)", set: "il y a 4 mois" },
    { k: "Focus principal : finance & trésorerie", set: "il y a 4 mois" },
    { k: "Notifications critiques uniquement via SMS", set: "il y a 6 sem." },
  ];
  const [memory, _setMemory] = useState(() => { try { const s = localStorage.getItem(LS_JARVIS_MEM); return s ? JSON.parse(s) : MEM_SEED; } catch { return MEM_SEED; } });
  const setMemory = (next) => { const v = typeof next === "function" ? next(memory) : next; _setMemory(v); try { localStorage.setItem(LS_JARVIS_MEM, JSON.stringify(v)); } catch {} };
  const addMemory = () => { const k = (prompt("Nouveau fait à mémoriser pour JARVIS :") || "").trim(); if (!k) return; setMemory([{ k, set: "à l'instant" }, ...memory]); toast?.push?.({ tone: "good", title: "Mémorisé" }); };
  const removeMemory = (i) => setMemory(memory.filter((_, j) => j !== i));
  const speakBriefing = () => {
    try {
      const txt = document.getElementById("jarvis-briefing-text")?.textContent || "";
      if (!("speechSynthesis" in window) || !txt) { toast?.push?.({ tone: "warn", title: "TTS indisponible" }); return; }
      window.speechSynthesis.cancel();
      const u = new SpeechSynthesisUtterance(txt);
      u.lang = "fr-CA"; u.rate = 1.05;
      window.speechSynthesis.speak(u);
      toast?.push?.({ tone: "good", title: "Lecture du briefing", body: "~2 min" });
    } catch (e) { toast?.push?.({ tone: "danger", title: "Erreur TTS" }); }
  };
  const copyText = async (text, label) => {
    try { await navigator.clipboard.writeText(text); toast?.push?.({ tone: "good", title: (label || "Copié") + " ✓" }); }
    catch { toast?.push?.({ tone: "danger", title: "Copie échouée" }); }
  };

  const simStream = async (text) => {
    setStreaming(true);
    setStreamText("");
    const words = text.split(" ");
    for (let i = 0; i < words.length; i++) {
      await new Promise((r) => setTimeout(r, 40 + Math.random() * 30));
      setStreamText((s) => s + (i ? " " : "") + words[i]);
    }
    setMessages((m) => [...m, { role: "assistant", content: text, t: new Date().toLocaleTimeString("fr-CA", { hour: "2-digit", minute: "2-digit" }) }]);
    setStreaming(false);
    setStreamText("");
  };

  const ask = async () => {
    if (!input.trim()) return;
    const q = input.trim();
    const now = new Date().toLocaleTimeString("fr-CA", { hour: "2-digit", minute: "2-digit" });
    setMessages((m) => [...m, { role: "user", content: q, t: now }]);
    setInput("");
    try {
      const sys = `Tu es JARVIS, opérateur du portail KCC Holdings. Tu parles avec ${userInfo.name} (${userInfo.role}, focus ${userInfo.focus}). Réponse courte, française, factuelle.`;
      const reply = await window.claude.complete({ messages: [{ role: "user", content: q }], system: sys });
      await simStream(reply);
    } catch (e) {
      simStream("⚠️ Erreur de connexion.");
    }
  };

  const TABS = [
    { id: "chat",      label: "Chat",           icon: "bot" },
    { id: "agent",     label: "Mode agent",     icon: "zap",     badge: "BETA" },
    { id: "tools",     label: "Tools",          icon: "wrench" },
    { id: "memory",    label: "Mémoire",        icon: "book" },
    { id: "briefing",  label: "Daily briefing", icon: "calendar" },
    { id: "listing",   label: "Analyse listing",icon: "eye" },
    { id: "describe",  label: "Descriptions",   icon: "edit" },
    { id: "negotiate", label: "Négociation",    icon: "users" },
  ];

  return (
    <div className="page" style={{ maxWidth: 1400 }}>
      <div className="page-head">
        <div>
          <div className="row" style={{ gap: 12 }}>
            <JarvisLogo size={32} pulse/>
            <div>
              <div className="page-title">Console JARVIS</div>
              <div className="page-sub">Opérateur complet · streaming · tools · mémoire long terme · mode agent</div>
            </div>
          </div>
        </div>
        <div className="row">
          <button onClick={() => setIncognito(!incognito)} className="btn" data-size="sm" data-variant={incognito ? "primary" : "ghost"} title="Conversation non-loggée">
            <Icon name="eye" size={12}/> Incognito {incognito ? "ON" : "OFF"}
          </button>
        </div>
      </div>

      <div className="card" style={{ padding: 0 }}>
        <div style={{ display: "flex", borderBottom: "1px solid var(--border-subtle)", padding: "0 14px", overflowX: "auto" }}>
          {TABS.map((tt) => (
            <button key={tt.id} onClick={() => setTab(tt.id)} style={{
              display: "flex", alignItems: "center", gap: 6,
              padding: "10px 12px", fontSize: 12.5,
              background: "transparent", border: "none", cursor: "pointer",
              color: tab === tt.id ? "var(--text)" : "var(--text-dim)",
              fontWeight: tab === tt.id ? 600 : 450,
              borderBottom: tab === tt.id ? "2px solid var(--accent)" : "2px solid transparent",
              marginBottom: -1, whiteSpace: "nowrap",
            }}>
              <Icon name={tt.icon} size={12}/>
              {tt.label}
              {tt.badge && <span className="nav-tag" data-tone="accent">{tt.badge}</span>}
            </button>
          ))}
        </div>

        <div style={{ padding: 18 }}>
          {tab === "chat" && (
            <div>
              <div style={{ maxHeight: 360, overflow: "auto", padding: "0 4px 16px" }}>
                {messages.map((m, i) => (
                  <div key={i} style={{ display: "flex", gap: 10, marginBottom: 14 }}>
                    {m.role === "assistant" ? <JarvisLogo size={22} glow={false}/> : <Avatar user={currentUser} size="sm"/>}
                    <div>
                      <div className="row" style={{ gap: 8, marginBottom: 3 }}>
                        <span style={{ fontSize: 12, fontWeight: 600 }}>{m.role === "assistant" ? "JARVIS" : userInfo.name}</span>
                        <span className="mono" style={{ fontSize: 10.5, color: "var(--text-faint)" }}>{m.t}</span>
                      </div>
                      <div style={{ fontSize: 13, lineHeight: 1.55 }}>{m.content}</div>
                    </div>
                  </div>
                ))}
                {streaming && (
                  <div style={{ display: "flex", gap: 10 }}>
                    <JarvisLogo size={22} glow={false} pulse/>
                    <div>
                      <div className="row" style={{ gap: 8, marginBottom: 3 }}>
                        <span style={{ fontSize: 12, fontWeight: 600 }}>JARVIS</span>
                        <span className="mono" style={{ fontSize: 10.5, color: "var(--accent)" }}>streaming…</span>
                      </div>
                      <div style={{ fontSize: 13, lineHeight: 1.55 }}>{streamText}<span style={{ opacity: 0.6 }}>▍</span></div>
                    </div>
                  </div>
                )}
              </div>
              <div style={{ display: "flex", gap: 8, alignItems: "flex-end", background: "var(--bg-2)", border: "1px solid var(--border)", borderRadius: 12, padding: "8px 8px 8px 14px" }}>
                <textarea value={input} onChange={(e) => setInput(e.target.value)} onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); ask(); } }} rows={1} placeholder="Demandez à JARVIS… (réponse en streaming)" style={{ flex: 1, resize: "none", background: "transparent", border: "none", outline: "none", color: "var(--text)", fontSize: 13, lineHeight: 1.5, fontFamily: "inherit", maxHeight: 100, padding: "6px 0" }}/>
                <button className="btn" data-variant="primary" data-size="sm" onClick={ask} disabled={!input.trim() || streaming}><Icon name="zap" size={12}/> Envoyer</button>
              </div>
              {incognito && <div className="mono" style={{ marginTop: 10, fontSize: 10.5, color: "var(--amber)", textAlign: "center" }}>🕶 Mode incognito · cette conversation ne sera pas sauvegardée</div>}
            </div>
          )}

          {tab === "agent" && (
            <div>
              <div className="card" style={{ padding: 16, marginBottom: 14, background: "color-mix(in oklch, var(--accent) 8%, var(--bg-1))", border: "1px solid color-mix(in oklch, var(--accent) 30%, var(--border))" }}>
                <div className="row" style={{ gap: 10, marginBottom: 8 }}>
                  <Icon name="zap" size={14} style={{ color: "var(--accent)" }}/>
                  <span style={{ fontSize: 13, fontWeight: 600 }}>Mode agent supervisé</span>
                  <Badge tone="blue">BETA</Badge>
                </div>
                <div style={{ fontSize: 12, color: "var(--text-muted)", lineHeight: 1.5 }}>JARVIS propose un plan multi-étapes, vous approuvez, JARVIS exécute en utilisant les tools. Vous pouvez interrompre à tout moment.</div>
                <input className="input" id="jarvis-agent-goal" placeholder="Décrivez l'objectif… ex. « négocier MOQ avec BambooLine et créer la tâche pour Kevin »" style={{ marginTop: 12 }}/>
                <button onClick={() => {
                  const goal = document.getElementById("jarvis-agent-goal")?.value?.trim();
                  if (!goal) { toast?.push?.({ tone: "warn", title: "Objectif requis", body: "Décrivez ce que JARVIS doit accomplir." }); return; }
                  setTab("chat");
                  setInput(goal);
                  toast?.push?.({ tone: "good", title: "Plan transféré au chat", body: "Envoyez pour lancer l'exécution agent." });
                }} className="btn" data-variant="primary" style={{ marginTop: 10 }}><Icon name="zap" size={13}/> Lancer plan</button>
              </div>

              <div style={{ fontSize: 11, color: "var(--text-dim)", textTransform: "uppercase", letterSpacing: ".08em", marginBottom: 10 }}>Exécutions récentes</div>
              {JARVIS_AGENT_HISTORY.map((h) => (
                <div key={h.id} style={{ border: "1px solid var(--border-subtle)", borderRadius: 10, padding: 14, marginBottom: 10, background: "var(--bg-1)" }}>
                  <div className="row" style={{ gap: 8, marginBottom: 10 }}>
                    <span className="mono" style={{ fontSize: 10.5, color: "var(--text-faint)" }}>{h.ts}</span>
                    <span style={{ fontSize: 12.5, fontWeight: 600 }}>{h.goal}</span>
                    <Badge tone={h.status === "completed" ? "green" : "amber"} dot>{h.status === "completed" ? "terminé" : "en cours"}</Badge>
                  </div>
                  {h.steps.map((s, i) => (
                    <div key={i} style={{ display: "flex", gap: 8, padding: "5px 0 5px 8px", fontSize: 12, color: s.ok ? "var(--text-muted)" : "var(--amber)" }}>
                      <span style={{ width: 14 }}>{s.ok ? "✓" : "⋯"}</span>
                      <span>{s.text}</span>
                    </div>
                  ))}
                </div>
              ))}
            </div>
          )}

          {tab === "tools" && (
            <div className="grid" style={{ gridTemplateColumns: "1fr 1fr", gap: 10 }}>
              {TOOLS.map((tl) => (
                <div key={tl.id} style={{ padding: 14, background: "var(--bg-2)", border: "1px solid var(--border-subtle)", borderRadius: 10 }}>
                  <div className="row" style={{ gap: 8 }}>
                    <Icon name={tl.icon} size={14} style={{ color: "var(--accent)" }}/>
                    <span className="mono" style={{ fontSize: 12, fontWeight: 600 }}>{tl.id}</span>
                    <span className="mono" style={{ marginLeft: "auto", fontSize: 10, color: "var(--text-faint)" }}>{tl.usage}× utilisé</span>
                  </div>
                  <div style={{ fontSize: 11.5, color: "var(--text-muted)", marginTop: 5 }}>{tl.desc}</div>
                </div>
              ))}
            </div>
          )}

          {tab === "memory" && (
            <div>
              <div className="row" style={{ marginBottom: 12, gap: 8 }}>
                <Icon name="book" size={14} style={{ color: "var(--accent)" }}/>
                <span style={{ fontSize: 12.5, fontWeight: 600 }}>{memory.length} faits mémorisés pour {userInfo.name}</span>
                <button onClick={addMemory} className="btn" data-size="sm" data-variant="ghost" style={{ marginLeft: "auto" }}><Icon name="plus" size={11}/> Ajouter</button>
              </div>
              {memory.map((m, i) => (
                <div key={i} style={{ display: "flex", gap: 10, padding: "10px 0", borderTop: i ? "1px solid var(--border-subtle)" : "none" }}>
                  <Icon name="check" size={12} style={{ color: "var(--green)", marginTop: 3 }}/>
                  <div style={{ flex: 1, fontSize: 12.5 }}>{m.k}</div>
                  <span className="mono" style={{ fontSize: 10.5, color: "var(--text-faint)" }}>{m.set}</span>
                  <button onClick={() => removeMemory(i)} className="icon-btn" style={{ width: 22, height: 22 }}><Icon name="x" size={11}/></button>
                </div>
              ))}
            </div>
          )}

          {tab === "briefing" && (
            <div>
              <div className="card" style={{ padding: 16, background: "linear-gradient(135deg, color-mix(in oklch, var(--accent) 14%, var(--bg-1)), var(--bg-1) 70%)", border: "1px solid color-mix(in oklch, var(--accent) 30%, var(--border))", marginBottom: 14 }}>
                <div className="row" style={{ gap: 10 }}>
                  <div style={{ width: 36, height: 36, borderRadius: 8, background: "var(--accent)", display: "grid", placeItems: "center", color: "white" }}>
                    <Icon name="zap" size={16}/>
                  </div>
                  <div>
                    <div style={{ fontSize: 13, fontWeight: 600 }}>Daily Briefing audio · 07:00 ET</div>
                    <div style={{ fontSize: 11.5, color: "var(--text-dim)" }}>~2 min · TTS + email + push notif</div>
                  </div>
                  <button onClick={speakBriefing} className="btn" data-variant="primary" style={{ marginLeft: "auto" }}><Icon name="zap" size={13}/> Écouter maintenant</button>
                </div>
                {/* fake waveform */}
                <div style={{ display: "flex", alignItems: "center", gap: 2, marginTop: 14, height: 40 }}>
                  {Array.from({ length: 80 }, (_, i) => {
                    const h = 10 + Math.abs(Math.sin(i * 0.3)) * 28 + Math.random() * 4;
                    return <div key={i} style={{ flex: 1, height: h, background: i < 22 ? "var(--accent)" : "var(--bg-3)", borderRadius: 1 }}/>;
                  })}
                </div>
                <div className="row" style={{ marginTop: 8, fontSize: 11, color: "var(--text-dim)" }}>
                  <span className="mono">0:32</span>
                  <span style={{ marginLeft: "auto" }} className="mono">2:14</span>
                </div>
              </div>
              <div className="card" style={{ padding: 14 }}>
                <div style={{ fontSize: 11, color: "var(--text-dim)", textTransform: "uppercase", letterSpacing: ".08em", marginBottom: 8 }}>Transcription du jour</div>
                <div id="jarvis-briefing-text" style={{ fontSize: 13, lineHeight: 1.65, color: "var(--text-muted)" }}>
                  Bonjour {userInfo.name}. Mai s'annonce à <strong style={{ color: "var(--text)" }}>+6.4 %</strong> sur le revenu 30 jours. Deux alertes critiques requièrent votre attention : le Couvre-volant cuir avec une rupture prévue dans 3 jours, et le Tapis souris XL dont l'ACOS dépasse votre seuil de 24 %. Côté trésorerie, le buffer reste sain à 4.2 mois. Trois nouvelles opportunités détectées par OpportunityFinder avec marge supérieure à 30 %. Excellente journée.
                </div>
              </div>
            </div>
          )}

          {tab === "listing" && (
            <div>
              <input className="input" placeholder="Coller URL Amazon ou ASIN…" defaultValue="B0CWZQTGZX" style={{ marginBottom: 14 }}/>
              <div className="grid" style={{ gridTemplateColumns: "1fr 1fr", gap: 14 }}>
                <div className="card" style={{ padding: 14 }}>
                  <div style={{ fontSize: 11, color: "var(--text-dim)", textTransform: "uppercase", letterSpacing: ".08em", marginBottom: 8 }}>Score listing</div>
                  <div className="num" style={{ fontSize: 36, fontWeight: 600, color: "var(--amber)" }}>72<span style={{ fontSize: 16, color: "var(--text-dim)" }}>/100</span></div>
                  <div style={{ fontSize: 11.5, color: "var(--text-dim)", marginTop: 4 }}>Bon, mais 4 axes d'amélioration identifiés</div>
                </div>
                <div className="card" style={{ padding: 14 }}>
                  <div style={{ fontSize: 11, color: "var(--text-dim)", textTransform: "uppercase", letterSpacing: ".08em", marginBottom: 8 }}>Détail</div>
                  {[["Titre", 84], ["Bullets", 68], ["Images", 90], ["A+ Content", 45]].map(([k, v]) => (
                    <div key={k} className="between" style={{ padding: "4px 0", fontSize: 12 }}>
                      <span>{k}</span>
                      <span className="num" style={{ color: v >= 80 ? "var(--green)" : v >= 60 ? "var(--amber)" : "var(--red)", fontWeight: 600 }}>{v}/100</span>
                    </div>
                  ))}
                </div>
              </div>
              <div className="card" style={{ padding: 14, marginTop: 14 }}>
                <div style={{ fontSize: 11, color: "var(--text-dim)", textTransform: "uppercase", letterSpacing: ".08em", marginBottom: 10 }}>Suggestions concrètes</div>
                {[
                  { sev: "red",   t: "A+ Content manquant",      d: "Page produit sans modules graphiques · perte CTR estimée 18%" },
                  { sev: "amber", t: "Bullet 3 trop dense",       d: "47 mots → réduire à 25 max, mettre bénéfice en premier" },
                  { sev: "amber", t: "Image 5 manquante",         d: "Vous avez 4/7 images recommandées · ajouter lifestyle + scale" },
                  { sev: "blue",  t: "Titre keyword sous-utilisé", d: "Ajouter \"silencieux\" et \"500ml\" (volumes >12k/mois)" },
                ].map((s, i) => (
                  <div key={i} className="row" style={{ gap: 10, padding: "8px 0", borderTop: i ? "1px solid var(--border-subtle)" : "none" }}>
                    <span style={{ width: 6, height: 6, borderRadius: 999, background: `var(--${s.sev})`, marginTop: 5, flexShrink: 0 }}/>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 12.5, fontWeight: 550 }}>{s.t}</div>
                      <div style={{ fontSize: 11, color: "var(--text-dim)", marginTop: 2 }}>{s.d}</div>
                    </div>
                    <button onClick={() => toast?.push?.({ tone: "good", title: "Suggestion appliquée", body: s.t })} className="btn" data-size="sm">Appliquer</button>
                  </div>
                ))}
              </div>
            </div>
          )}

          {tab === "describe" && (
            <div>
              <div className="row" style={{ gap: 8, marginBottom: 12 }}>
                <input className="input" placeholder="ASIN ou nom du produit" defaultValue="Diffuseur huiles essentielles 500ml" style={{ flex: 1 }}/>
                <select className="input" defaultValue="fr" style={{ width: 100 }}>
                  <option value="fr">Français</option>
                  <option value="en">Anglais</option>
                  <option value="es">Espagnol</option>
                </select>
                <select className="input" defaultValue="amazon" style={{ width: 140 }}>
                  <option value="amazon">Amazon listing</option>
                  <option value="shopify">Shopify</option>
                  <option value="brief">Brief 280 car.</option>
                </select>
                <button onClick={() => toast?.push?.({ tone: "good", title: "Description régénérée", body: "Voir la sortie ci-dessous." })} className="btn" data-variant="primary"><Icon name="zap" size={13}/> Générer</button>
              </div>
              <div className="card" style={{ padding: 16 }}>
                <div style={{ fontSize: 11, color: "var(--text-dim)", textTransform: "uppercase", letterSpacing: ".08em", marginBottom: 10 }}>Sortie générée · Amazon · français</div>
                <div id="jarvis-describe-output" style={{ fontSize: 13, lineHeight: 1.7, color: "var(--text)" }}>
                  <strong>Diffuseur d'huiles essentielles 500ml ultrasonique silencieux · 7 couleurs LED · auto-arrêt</strong>
                  <div style={{ marginTop: 12 }}>
                    • <strong>500ml capacité XL</strong> · jusqu'à 12h de diffusion continue<br/>
                    • <strong>Ultra silencieux</strong> &lt;25 dB · idéal chambre / bureau<br/>
                    • <strong>7 couleurs LED ajustables</strong> avec mode rotation automatique<br/>
                    • <strong>Auto-arrêt</strong> de sécurité quand le réservoir est vide<br/>
                    • <strong>Design ambré bois</strong> · s'intègre à tous les intérieurs
                  </div>
                </div>
                <div className="row" style={{ marginTop: 14, gap: 8 }}>
                  <button onClick={() => copyText(document.getElementById("jarvis-describe-output")?.innerText || "", "Description copiée")} className="btn" data-size="sm"><Icon name="copy" size={11}/> Copier</button>
                  <button onClick={() => toast?.push?.({ tone: "good", title: "Régénération lancée" })} className="btn" data-size="sm"><Icon name="refresh" size={11}/> Régénérer</button>
                  <button onClick={() => toast?.push?.({ tone: "warn", title: "Push Amazon", body: "Connexion SP-API requise (non configurée)." })} className="btn" data-size="sm" data-variant="primary" style={{ marginLeft: "auto" }}><Icon name="upload" size={11}/> Pousser vers Amazon</button>
                </div>
              </div>
            </div>
          )}

          {tab === "negotiate" && (
            <div>
              <div className="row" style={{ gap: 8, marginBottom: 14 }}>
                <select className="input" defaultValue="sup-007" style={{ width: 280 }}>
                  {SUPPLIERS.map((s) => <option key={s.id} value={s.id}>{s.name}</option>)}
                </select>
                <input className="input" placeholder="Objectif · ex. MOQ 150, prix -5%, Net 45…" defaultValue="MOQ 300 → 150, prix unitaire -7%" style={{ flex: 1 }}/>
                <button onClick={() => toast?.push?.({ tone: "good", title: "Argumentaire préparé", body: "Leviers + script ci-dessous." })} className="btn" data-variant="primary"><Icon name="zap" size={13}/> Préparer argumentaire</button>
              </div>

              <div className="grid" style={{ gridTemplateColumns: "1fr 1fr", gap: 14 }}>
                <div className="card" style={{ padding: 16 }}>
                  <div style={{ fontSize: 11, color: "var(--text-dim)", textTransform: "uppercase", letterSpacing: ".08em", marginBottom: 10 }}>Leviers à utiliser</div>
                  {[
                    "Volume commandes annuelles : $42k+ (récurrent)",
                    "Paiement 30% avance · jamais de retard sur 14 commandes",
                    "3 fournisseurs concurrents en short-list avec offres similaires",
                    "Engagement annuel Q3+Q4 possible si MOQ baisse",
                  ].map((t, i) => (
                    <div key={i} className="row" style={{ gap: 8, padding: "6px 0", fontSize: 12 }}>
                      <Icon name="check" size={11} style={{ color: "var(--green)" }}/>
                      <span>{t}</span>
                    </div>
                  ))}
                </div>
                <div className="card" style={{ padding: 16 }}>
                  <div style={{ fontSize: 11, color: "var(--text-dim)", textTransform: "uppercase", letterSpacing: ".08em", marginBottom: 10 }}>Pièges à éviter</div>
                  {[
                    "Ne pas mentionner le concurrent par nom",
                    "Garder la possibilité d'augmenter quantité en réserve",
                    "Refuser tout changement Incoterms (rester FOB Shenzhen)",
                    "Verrouiller prix sur 6 mois (anti-inflation matières)",
                  ].map((t, i) => (
                    <div key={i} className="row" style={{ gap: 8, padding: "6px 0", fontSize: 12 }}>
                      <Icon name="x" size={11} style={{ color: "var(--red)" }}/>
                      <span>{t}</span>
                    </div>
                  ))}
                </div>
              </div>

              <div className="card" style={{ padding: 16, marginTop: 14 }}>
                <div style={{ fontSize: 11, color: "var(--text-dim)", textTransform: "uppercase", letterSpacing: ".08em", marginBottom: 10 }}>Script proposé (FR · ton diplomatique)</div>
                <div style={{ fontSize: 12.5, lineHeight: 1.7, color: "var(--text-muted)", fontStyle: "italic" }}>
                  « Bonjour Lin Mei. Nous avons examiné nos prévisions Q3-Q4 et envisageons de doubler nos commandes annuelles, mais notre cashflow nous impose un MOQ plus flexible. Pouvez-vous nous proposer une grille avec MOQ 150 et un prix unitaire ajusté en contrepartie d'un engagement de 6 mois ? Nous sommes prêts à valider rapidement si les conditions tiennent. »
                </div>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

window.JarvisExtended = JarvisExtended;
