// agent.jsx — AI agent side panel, FAB supervisor, command palette, settings

// ============================================================
// Agent side panel (mode 2: contextualized to a lead)
// ============================================================
function AgentPanel({ open, lead, supervisor, onClose, onExpand }) {
  const [input, setInput] = React.useState('');
  const [thread, setThread] = React.useState([]);
  React.useEffect(() => {
    if (!open) return;
    setThread(initialThread(lead, supervisor));
    setInput('');
  }, [open, lead?.id, supervisor]);

  const ask = (q) => {
    const next = [...thread, { from: 'me', body: q }];
    setThread(next);
    setInput('');
    setTimeout(() => {
      setThread([...next, { from: 'ai', body: fakeAnswer(q, lead, supervisor), thinking: true }]);
      setTimeout(() => setThread(t => t.map(m => ({ ...m, thinking: false }))), 350);
    }, 250);
  };

  const suggestions = lead ? [
    "Ce presta vaut le coup ?",
    "Que lui répondre ?",
    "Compare-le aux autres prestas Python",
    "Quels clients sont compatibles ?",
  ] : [
    "Qui sont mes meilleurs prestas Python dispo ?",
    "Combien de leads chauds cette semaine ?",
    "Quelles missions en attente de profil ?",
    "Quels clients ne m'ont pas répondu depuis 5 jours ?",
  ];

  return (
    <div className={`agent-side ${open ? 'is-open' : ''}`}>
      <div className="head">
        <div style={{ width: 30, height: 30, background: 'var(--brown)', borderRadius: 8, display: 'grid', placeItems: 'center', color: '#fff' }}>
          <window.Icon.sparkle size={16} />
        </div>
        <div style={{ flex: 1 }}>
          <h3>{supervisor ? 'Agent Superviseur' : 'Agent Lead'}</h3>
          <div className="tiny muted">
            {supervisor ? 'Vision globale du pipeline' : 'Contexte du lead'}
          </div>
        </div>
        {lead && <span className="ctx">{lead.name}</span>}
        <button className="btn ghost" onClick={onExpand} title="Plein écran">
          <window.Icon.expand size={14} />
        </button>
        <button className="btn ghost" onClick={onClose} title="Fermer">
          <window.Icon.x size={14} />
        </button>
      </div>

      <div className="scroll">
        {thread.map((m, i) => (
          <AgentMessage key={i} m={m} />
        ))}
      </div>

      <div className="input">
        {thread.length <= 1 && (
          <div className="suggest-pills">
            {suggestions.map(s => (
              <span key={s} className="chip" onClick={() => ask(s)}>{s}</span>
            ))}
          </div>
        )}
        <textarea
          placeholder={lead ? `Demande à l'agent à propos de ${lead.name}…` : "Pose une question transverse…"}
          value={input}
          onChange={(e) => setInput(e.target.value)}
          onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey && input.trim()) { e.preventDefault(); ask(input.trim()); } }}
        />
        <div className="input-actions">
          <span className="chip"><window.Icon.paperclip size={11} /> Joindre</span>
          <span className="chip"><window.Icon.sparkle size={11} /> Suggérer</span>
          <div className="grow" />
          <button className="btn primary" onClick={() => input.trim() && ask(input.trim())}>
            <window.Icon.send size={13} /> Envoyer
          </button>
        </div>
      </div>
    </div>
  );
}

function AgentMessage({ m }) {
  if (m.from === 'me') {
    return (
      <div className="bubble me">
        <div>
          <div className="body">{m.body}</div>
        </div>
      </div>
    );
  }
  return (
    <div style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
      <div style={{ width: 28, height: 28, background: 'var(--brown)', borderRadius: 8, display: 'grid', placeItems: 'center', color: '#fff', flexShrink: 0, marginTop: 2 }}>
        <window.Icon.sparkle size={14} />
      </div>
      <div style={{ background: 'var(--brown-soft)', color: 'var(--brown)', padding: '10px 14px', borderRadius: 12, borderTopLeftRadius: 4, maxWidth: '85%', lineHeight: 1.5, fontSize: 13.5 }}>
        {m.thinking ? <span className="muted tiny">Analyse en cours…</span> : <div dangerouslySetInnerHTML={{ __html: m.body }} />}
      </div>
    </div>
  );
}

function initialThread(lead, supervisor) {
  if (supervisor) {
    return [{ from: 'ai', body: `Bonjour François. Ce matin j'ai détecté <b>3 nouveaux leads</b> non qualifiés, dont <b>2 prestas confirmés</b> par profil LinkedIn. Tu as <b>5 conversations Hot</b> qui attendent une réponse — la plus urgente est <b>Pauline (BNP)</b>, qui a relancé deux fois en 48h.<br/><br/>Sur quoi je commence ?` }];
  }
  if (!lead) return [];
  if (lead.type === 'presta') {
    return [{ from: 'ai', body: `<b>${lead.name}</b> ouvert. Score <b>${lead.score.toFixed(1)}/10</b> (${lead.statusLabel}). Stack très alignée avec <b>2 missions actives</b> (BNP CIB · Carrefour). Il y a une <b>action urgente</b> : envoyer la présentation au client BNP avant fin de journée. Je peux la pré-rédiger ?` }];
  }
  return [{ from: 'ai', body: `<b>${lead.name}</b> (${lead.company}). Recherche <b>${lead.mission}</b>, budget ${lead.budget}. J'ai <b>${(window.APPORTOO.MATCHES[lead.id] || []).length} prestas compatibles</b> dans le pipe, dont <b>Aïssa Diallo</b> à 9.6/10. Tu veux que je prépare une shortlist ?` }];
}

function fakeAnswer(q, lead, supervisor) {
  const l = q.toLowerCase();
  if (l.includes('vaut le coup') || l.includes('compare')) {
    return `Top 30% de ton vivier sur la stack Python/Spark. Plus cher que la moyenne (+10%) mais ratio expérience/qualité élevé. <b>Verdict : oui, à pousser sur les comptes premium</b> (BNP, Carrefour). Pas pour les ESN bas de gamme.`;
  }
  if (l.includes('répondre') || l.includes('repondre')) {
    return `Je suggère :<br/><br/><i>« Top, je note ta dispo début janvier. Du coup la mission Lille démarre fin mai, je vais regarder si je trouve un pont d'ici là — sinon je te garde sur les Q1 26. Tu veux qu'on reste en contact mensuel ? »</i><br/><br/>Clique <b>Affiner</b> pour ajuster le ton.`;
  }
  if (l.includes('meilleurs') || l.includes('python')) {
    return `Top 3 prestas Python dispo cette semaine :<br/>• <b>Yacine Berrada</b> — 9.1/10 — 650€ — dispo janvier<br/>• <b>Wei Chen</b> — 9.0/10 — 850€ — dispo immédiate<br/>• <b>Aïssa Diallo</b> — 9.4/10 — 780€ — dispo fin mai`;
  }
  if (l.includes('chaud') || l.includes('hot') || l.includes('semaine')) {
    return `Cette semaine : <b>5 leads Hot actifs</b> (3 prestas, 2 clients). Conversion estimée : ~2 placements potentiels. Le bottleneck est sur ta réponse à Pauline (BNP) qui débloquerait 2 missions d'un coup.`;
  }
  if (l.includes('attente') || l.includes('5 jours')) {
    return `<b>2 clients</b> sans réponse depuis 5+ jours : <b>Jean-Baptiste Roux</b> (Scaleflow) — 8j et <b>Cédric Henneveux</b> — 14j. Pour JBR je suggère une relance soft aujourd'hui ; Cédric reste froid (phase de cadrage interne).`;
  }
  return `Je peux affiner avec plus de contexte ? (Quel critère t'intéresse le plus : matching, prix, dispo, fit relationnel…)`;
}

window.AgentPanel = AgentPanel;

// ============================================================
// AgentFullscreen — Mode 3: long working session
// ============================================================
function AgentFullscreen({ open, onClose, onOpenLead, allLeads, initialQuery }) {
  const [activeSession, setActiveSession] = React.useState('s1');
  const [input, setInput] = React.useState('');
  const [thread, setThread] = React.useState([]);
  const inputRef = React.useRef(null);

  const sessions = [
    { id: 's1', title: 'Briefing du matin', when: 'Auj. · 09:14', preview: '5 leads Hot, 2 matches détectés…', active: true },
    { id: 's2', title: 'Match Aïssa × BNP CIB', when: 'Hier · 16:30', preview: 'Score 9.6, à pousser cette semaine…' },
    { id: 's3', title: 'Analyse pipeline Q2', when: '10 mai', preview: 'TJM moyen +12%, conversion 24%…' },
    { id: 's4', title: 'Stratégie de réponse Pauline', when: '8 mai', preview: 'Voir relance soft + offre adaptée…' },
    { id: 's5', title: 'Plan de prospection ESN', when: '4 mai', preview: '8 ESN ciblées, scoring + script…' },
  ];

  // Initial thread for the active session
  React.useEffect(() => {
    if (!open) return;
    setThread([
      { from: 'ai', body: `Bonjour François. Voici ton <b>briefing du matin</b> consolidé. J'ai analysé tes <b>${allLeads.length} leads</b>, tes <b>4 missions actives</b>, et les <b>5 nouveaux contacts</b> capturés cette nuit.`, sources: [] },
      { from: 'ai', body: `<p>Trois choses prioritaires :</p><ul><li><b>Pauline (BNP)</b> a relancé 2× en 48h — risque de churn client, à traiter avant midi.</li><li>Match parfait détecté entre <b>Aïssa Diallo</b> et la mission <b>BNP Lead Data Eng</b> (9.6/10). Pousser maintenant, le client a confirmé le TJM hier.</li><li><b>Carrefour</b> arrive à 5 jours sans retour. Je propose une relance soft cet après-midi.</li></ul>`, sources: ['c1', 'p4', 'c3'] },
      { from: 'ai', body: `<p>Tu veux qu'on attaque par quoi ? Je peux pré-rédiger l'email à Pauline ou monter le dossier de présentation Aïssa → BNP.</p>`, sources: [] },
    ]);
    if (initialQuery) setInput(initialQuery);
    setTimeout(() => inputRef.current?.focus(), 50);
  }, [open, activeSession, initialQuery, allLeads.length]);

  const ask = () => {
    if (!input.trim()) return;
    const q = input;
    setThread(t => [...t, { from: 'me', body: q }]);
    setInput('');
    setTimeout(() => {
      setThread(t => [...t, {
        from: 'ai',
        body: `<p>OK, je m'en occupe. Voici mon plan :</p><ul><li>Rédiger un brouillon d'email à Pauline en mettant en avant la dispo d'Aïssa Diallo et le fit Scala/Spark.</li><li>Préparer le slide récap avec son CV, ses 3 références BFSI, et son TJM négocié à 750€.</li><li>Te suggérer un créneau ce vendredi pour le call à 3.</li></ul><p>Je t'envoie tout ça dans <b>2 minutes</b>. OK ?</p>`,
        sources: ['c1', 'p4'],
      }]);
    }, 600);
  };

  React.useEffect(() => {
    if (!open) return;
    const h = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, [open, onClose]);

  if (!open) return null;

  // Context: which leads are currently "loaded" by the agent
  const ctxLeads = ['c1', 'p4', 'c3'].map(id => window.APPORTOO.byId(id)).filter(Boolean);

  return (
    <div className="agent-fs-back" onClick={onClose}>
      <div className="agent-fs" onClick={e => e.stopPropagation()}>
        <div className="agent-fs-head">
          <div style={{ width: 38, height: 38, background: 'var(--brown)', borderRadius: 10, display: 'grid', placeItems: 'center', color: '#fff' }}>
            <window.Icon.sparkle size={18} />
          </div>
          <div style={{ flex: 1 }}>
            <h2>Agent · Chef d'orchestre</h2>
            <div className="sub">Session de travail · accès complet au pipeline, calendrier et dossier</div>
          </div>
          <span className="chip turq dot" style={{ fontSize: 11 }}>Actif</span>
          <button className="btn" title="Nouvelle session">
            <window.Icon.plus size={13} /> Nouvelle session
          </button>
          <button className="btn ghost icon" onClick={onClose} title="Fermer (esc)">
            <window.Icon.x size={14} />
          </button>
        </div>

        <div className="agent-fs-body">
          {/* Left rail — session history */}
          <div className="agent-fs-rail">
            <div className="rail-head">
              <h3>Sessions</h3>
              <button className="btn ghost icon" title="Filtrer">
                <window.Icon.search size={13} />
              </button>
            </div>
            <div className="sessions">
              {sessions.map(s => (
                <div key={s.id}
                     className={`agent-fs-session ${activeSession === s.id ? 'active' : ''}`}
                     onClick={() => setActiveSession(s.id)}>
                  <div className="st">
                    {s.id === 's1' && <span className="ping" />}
                    {s.title}
                  </div>
                  <div className="sw">{s.when}</div>
                  <div className="sp">{s.preview}</div>
                </div>
              ))}
            </div>
          </div>

          {/* Center — chat thread + composer */}
          <div className="agent-fs-chat">
            <div className="agent-fs-thread">
              {thread.map((m, i) => (
                <div key={i} className={`fs-msg ${m.from === 'me' ? 'me' : ''}`}>
                  <div className={`fs-av ${m.from === 'ai' ? 'fs-av-agent' : ''}`}>
                    {m.from === 'ai' ? <window.Icon.sparkle size={16} /> : 'FB'}
                  </div>
                  <div className="fs-body">
                    <div dangerouslySetInnerHTML={{ __html: m.body }} />
                    {m.sources && m.sources.length > 0 && (
                      <div style={{ marginTop: 8 }}>
                        {m.sources.map(id => {
                          const l = window.APPORTOO.byId(id);
                          if (!l) return null;
                          return (
                            <span key={id} className="fs-source" onClick={() => onOpenLead(id)}>
                              <window.Icon.link size={11} />
                              {l.name}
                            </span>
                          );
                        })}
                      </div>
                    )}
                  </div>
                </div>
              ))}
            </div>

            <div className="agent-fs-composer">
              <div className="agent-fs-composer-inner">
                <div className="composer-row">
                  <window.Icon.sparkle size={16} style={{ color: 'var(--brown)' }} />
                  <textarea
                    ref={inputRef}
                    rows={1}
                    placeholder="Demande à l'agent — il a accès à tout ton pipeline, ton calendrier, ton dossier…"
                    value={input}
                    onChange={(e) => setInput(e.target.value)}
                    onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); ask(); } }}
                  />
                  <button className="btn primary" onClick={ask} disabled={!input.trim()}>
                    <window.Icon.send size={13} /> Envoyer
                    <span className="kbd">↵</span>
                  </button>
                </div>
                <div className="composer-tools">
                  <span className="chip"><window.Icon.paperclip size={11} /> Joindre</span>
                  <span className="chip"><window.Icon.link size={11} /> Lead</span>
                  <span className="chip"><window.Icon.calendar size={11} /> Calendrier</span>
                  <span className="chip"><window.Icon.file size={11} /> Dossier</span>
                  <div className="spacer" />
                  <span>Shift + ↵ pour saut de ligne</span>
                </div>
              </div>
            </div>
          </div>

          {/* Right rail — context */}
          <div className="agent-fs-ctx">
            <div>
              <h3>Contexte chargé</h3>
              <div className="tiny muted" style={{ marginTop: 4 }}>
                L'agent référence ces leads dans cette session.
              </div>
            </div>
            <div className="vstack" style={{ gap: 2 }}>
              {ctxLeads.map(l => (
                <div key={l.id} className="agent-fs-ctx-lead" onClick={() => onOpenLead(l.id)}>
                  <window.Avatar name={l.name} status={l.statusKey} size="xs" />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div className="l">{l.name}</div>
                    <div className="h">{l.type === 'presta' ? 'Presta' : 'Client'} · {l.statusLabel}</div>
                  </div>
                  <span className="x" title="Retirer du contexte">×</span>
                </div>
              ))}
              <button className="btn ghost" style={{ marginTop: 6, fontSize: 12 }}>
                <window.Icon.plus size={11} /> Ajouter un lead
              </button>
            </div>

            <div className="agent-fs-ctx-block">
              <b>Sources actives</b>
              <div className="vstack tiny" style={{ gap: 4, marginTop: 6, color: 'var(--ink-3)' }}>
                <div className="hstack" style={{ gap: 6 }}>
                  <window.Icon.conv size={11} /> 23 messages LinkedIn
                </div>
                <div className="hstack" style={{ gap: 6 }}>
                  <window.Icon.calendar size={11} /> 12 events cette semaine
                </div>
                <div className="hstack" style={{ gap: 6 }}>
                  <window.Icon.file size={11} /> Dossier compétences v3
                </div>
                <div className="hstack" style={{ gap: 6 }}>
                  <window.Icon.star size={11} /> Grille de scoring v2
                </div>
              </div>
            </div>

            <div className="agent-fs-ctx-block">
              <b>Actions rapides</b>
              <div className="vstack" style={{ gap: 4, marginTop: 8 }}>
                <button className="btn ghost" style={{ justifyContent: 'flex-start' }}>
                  <window.Icon.send size={11} /> Rédiger email Pauline
                </button>
                <button className="btn ghost" style={{ justifyContent: 'flex-start' }}>
                  <window.Icon.file size={11} /> Préparer dossier Aïssa
                </button>
                <button className="btn ghost" style={{ justifyContent: 'flex-start' }}>
                  <window.Icon.calendar size={11} /> Trouver créneau ven.
                </button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

window.AgentFullscreen = AgentFullscreen;

// ============================================================
// Agent FAB
// ============================================================
function AgentFAB({ onClick }) {
  return (
    <button className="agent-fab" onClick={onClick} title="Agent superviseur (⌘J)">
      <window.Icon.sparkle size={22} />
      <span className="sparkle" />
    </button>
  );
}
window.AgentFAB = AgentFAB;

// ============================================================
// Command palette (⌘K)
// ============================================================
function CommandPalette({ open, onClose, onRoute, onOpenLead, allLeads }) {
  const [q, setQ] = React.useState('');
  const [active, setActive] = React.useState(0);
  const inputRef = React.useRef(null);

  React.useEffect(() => {
    if (open) { setQ(''); setActive(0); setTimeout(() => inputRef.current?.focus(), 30); }
  }, [open]);

  const nav = [
    { id: 'home', label: 'Accueil', icon: 'home', shortcut: 'G H', route: 'home' },
    { id: 'me', label: 'Mes missions', icon: 'briefcase', shortcut: 'G E', route: 'me' },
    { id: 'presta', label: 'Prestataires', icon: 'presta', shortcut: 'G P', route: 'presta' },
    { id: 'client', label: 'Clients', icon: 'client', shortcut: 'G C', route: 'client' },
    { id: 'match', label: 'Mise en relation', icon: 'match', shortcut: 'G M', route: 'match' },
    { id: 'conv', label: 'Conversations', icon: 'conv', shortcut: 'G I', route: 'conv' },
    { id: 'calendar', label: 'Calendrier', icon: 'calendar', shortcut: 'G A', route: 'calendar' },
    { id: 'settings', label: 'Réglages', icon: 'settings', shortcut: 'G S', route: 'settings' },
  ];

  const leadResults = allLeads
    .filter(l => !q || `${l.name} ${l.headline}`.toLowerCase().includes(q.toLowerCase()))
    .slice(0, 5);

  const filtNav = nav.filter(n => !q || n.label.toLowerCase().includes(q.toLowerCase()));

  const items = [
    ...filtNav.map(n => ({ kind: 'nav', ...n })),
    ...leadResults.map(l => ({ kind: 'lead', ...l })),
  ];

  React.useEffect(() => {
    if (!open) return;
    const h = (e) => {
      if (e.key === 'Escape') onClose();
      else if (e.key === 'ArrowDown') { e.preventDefault(); setActive(a => Math.min(items.length - 1, a + 1)); }
      else if (e.key === 'ArrowUp') { e.preventDefault(); setActive(a => Math.max(0, a - 1)); }
      else if (e.key === 'Enter') { e.preventDefault(); const it = items[active]; if (it) handle(it); }
    };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, [open, active, items]);

  const handle = (it) => {
    if (it.kind === 'nav') onRoute(it.route);
    else if (it.kind === 'lead') onOpenLead(it.id);
    onClose();
  };

  if (!open) return null;
  return (
    <div className="cmdk-back" onClick={onClose}>
      <div className="cmdk" onClick={(e) => e.stopPropagation()}>
        <div className="inp">
          <window.Icon.search size={16} style={{ color: 'var(--ink-3)' }} />
          <input ref={inputRef} placeholder="Aller à, chercher un lead, lancer une action…"
                 value={q} onChange={e => { setQ(e.target.value); setActive(0); }} />
          <span className="kbd" style={{ fontFamily: 'var(--font-mono)', fontSize: 10.5, background: 'var(--bg-1)', color: 'var(--ink-4)', padding: '1px 6px', borderRadius: 4 }}>ESC</span>
        </div>
        {filtNav.length > 0 && (
          <div className="grp">
            <div className="grp-h">Navigation</div>
            {filtNav.map((n, i) => {
              const Ico = window.Icon[n.icon];
              const idx = i;
              return (
                <div key={n.id} className={`cmdk-item ${active === idx ? 'active' : ''}`} onClick={() => handle({ kind: 'nav', ...n })}>
                  <Ico size={15} className="icn" />
                  <span className="grow">{n.label}</span>
                  <span className="shortcut">{n.shortcut}</span>
                </div>
              );
            })}
          </div>
        )}
        {leadResults.length > 0 && (
          <div className="grp">
            <div className="grp-h">Leads</div>
            {leadResults.map((l, i) => {
              const idx = filtNav.length + i;
              return (
                <div key={l.id} className={`cmdk-item ${active === idx ? 'active' : ''}`} onClick={() => handle({ kind: 'lead', ...l })}>
                  <window.Avatar name={l.name} size="xs" />
                  <span className="grow">{l.name} <span className="muted tiny" style={{ marginLeft: 6 }}>{l.headline}</span></span>
                  <span className={`chip sm ${l.statusKey}`} style={{ fontSize: 10 }}>{l.statusLabel}</span>
                </div>
              );
            })}
          </div>
        )}
        {items.length === 0 && (
          <div className="empty" style={{ padding: 30 }}>Aucun résultat pour « {q} »</div>
        )}
      </div>
    </div>
  );
}

window.CommandPalette = CommandPalette;
