// mod_agent.jsx — écran « Conversations » : chat IA réel branché sur /api/chat.
// Multi-conversations + historique (D1). Remplace le mock LinkedIn ConversationsView
// sur la route 'conv'. Le mock (agent.jsx : AgentPanel/AgentFullscreen/CommandPalette)
// reste chargé et intact pour ne pas casser le reste de l'UI.
//
// Convention socle : composant exposé via window.AgentChat, abonné à Store.

const TOOL_LABELS = {
  list_opportunities: 'Opportunités',
  get_opportunity: 'Opportunité',
  list_contacts: 'Contacts',
  get_contact: 'Contact',
  list_commission_lines: 'Commissions',
  list_validation_queue: 'À valider',
};

const SUGGESTIONS = [
  "Prépare-moi une fiche de call pour mon prochain call prospect.",
  "Rédige un message de relance à un dev qui n'a pas répondu.",
  "Quelles opportunités sont en sourcing dev en ce moment ?",
  "Propose une réponse à un message LinkedIn entrant.",
];

function AgentChat() {
  const [, force] = React.useState(0);
  const [input, setInput] = React.useState('');
  const [editingId, setEditingId] = React.useState(null);
  const [editingTitle, setEditingTitle] = React.useState('');
  const scrollRef = React.useRef(null);
  const inputRef = React.useRef(null);
  const prevBusy = React.useRef(false);
  const prevCount = React.useRef(0);
  const prevConv = React.useRef(null);

  React.useEffect(() => {
    const unsub = Store.subscribe(() => force((n) => n + 1));
    const last = (typeof loadCurrentConv === 'function') ? loadCurrentConv() : null;
    if (last && Store.state.currentConvId !== last) Store.selectConversation(last);
    return unsub;
  }, []);

  // Auto-resize textarea (grandit jusqu'à 200px puis scrolle).
  React.useEffect(() => {
    const el = inputRef.current;
    if (!el) return;
    el.style.height = 'auto';
    el.style.height = Math.min(el.scrollHeight, 200) + 'px';
  }, [input]);

  // Scroll : nouveau message user → bas ; réponse IA arrivée → début de réponse ;
  // conversation chargée → bas.
  React.useEffect(() => {
    const sc = scrollRef.current;
    if (!sc) return;
    const msgs = Store.state.currentMessages;
    const last = msgs[msgs.length - 1];
    const wasBusy = prevBusy.current;
    const convChanged = prevConv.current !== Store.state.currentConvId;
    const newMsg = msgs.length > prevCount.current;
    prevBusy.current = Store.state.chatBusy;
    prevCount.current = msgs.length;
    prevConv.current = Store.state.currentConvId;

    if (convChanged && msgs.length > 0 && !Store.state.chatBusy) {
      requestAnimationFrame(() => { if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight; });
      return;
    }
    if (wasBusy && !Store.state.chatBusy && last && last.role !== 'user') {
      const aiMsgs = sc.querySelectorAll('.ag-msg.ai');
      const target = aiMsgs[aiMsgs.length - 1];
      if (target) sc.scrollTo({ top: Math.max(0, target.offsetTop - 12), behavior: 'smooth' });
    } else if (newMsg || Store.state.chatBusy) {
      sc.scrollTop = sc.scrollHeight;
    }
  }, [Store.state.currentMessages.length, Store.state.chatBusy, Store.state.currentConvId]);

  const send = (override) => {
    const t = (override != null ? override : input).trim();
    if (!t || Store.state.chatBusy) return;
    setInput('');
    Store.sendMessage(t);
  };

  const messages = Store.state.currentMessages;
  const conversations = Store.state.conversations;
  const currentId = Store.state.currentConvId;
  const busy = Store.state.chatBusy;

  return (
    <div className="ag-layout">
      <div className="ag-sidebar">
        <button className="ag-new" onClick={() => Store.newConversation()}>
          <window.Icon.plus size={14} /> Nouvelle conversation
        </button>
        <h4>Conversations</h4>
        {conversations.length === 0 && (
          <div className="ag-empty-conv">Aucune conversation pour l'instant.</div>
        )}
        {conversations.map((c) => (
          <div
            key={c.id}
            className={`ag-conv-item ${c.id === currentId ? 'active' : ''}`}
            onClick={() => editingId !== c.id && Store.selectConversation(c.id)}
          >
            {editingId === c.id ? (
              <input
                className="ag-conv-rename"
                value={editingTitle}
                autoFocus
                onChange={(e) => setEditingTitle(e.target.value)}
                onKeyDown={(e) => {
                  if (e.key === 'Enter') { Store.renameConversation(c.id, editingTitle.trim() || c.title || 'Sans titre'); setEditingId(null); }
                  else if (e.key === 'Escape') setEditingId(null);
                }}
                onBlur={() => { if (editingTitle.trim()) Store.renameConversation(c.id, editingTitle.trim()); setEditingId(null); }}
              />
            ) : (
              <span className="ag-conv-title" title={c.title || 'Sans titre'}>{c.title || 'Sans titre'}</span>
            )}
            <div className="ag-conv-actions">
              <button className="ag-conv-act" title="Renommer"
                onClick={(e) => { e.stopPropagation(); setEditingId(c.id); setEditingTitle(c.title || ''); }}>
                <window.Icon.edit size={12} />
              </button>
              <button className="ag-conv-act" title="Supprimer"
                onClick={(e) => { e.stopPropagation(); if (confirm(`Supprimer "${c.title || 'cette conversation'}" ?`)) Store.deleteConversation(c.id); }}>
                <window.Icon.trash size={12} />
              </button>
            </div>
          </div>
        ))}
      </div>

      <div className="ag-chat">
        <div className="ag-scroll" ref={scrollRef}>
          {messages.length === 0 && !busy && (
            <div className="ag-welcome">
              <div className="ag-welcome-icn"><window.Icon.sparkle size={26} /></div>
              <h2>Assistant Apportoo</h2>
              <p>
                Je rédige ton <b>logistique écrit</b> (relances, prises de RDV, intros, suivis),
                tes <b>fiches de call</b> (prospect ou dev) et des <b>suggestions de réponse</b> à l'inbound.
                J'ai accès en lecture à tes opportunités, contacts, commissions et à la file « À valider ».
              </p>
              <div className="ag-suggest">
                {SUGGESTIONS.map((s) => (
                  <button key={s} className="ag-chip" onClick={() => send(s)}>{s}</button>
                ))}
              </div>
            </div>
          )}
          {messages.map((m) => (
            <div key={m.id} className={`ag-msg ${m.role === 'user' ? 'user' : 'ai'}`}>
              <div className="ag-ava">{m.role === 'user' ? 'WM' : <window.Icon.sparkle size={15} />}</div>
              <div className="ag-bubble">
                <div className="ag-md" dangerouslySetInnerHTML={{ __html: renderAgentMarkdown(m.content) }} />
                {m.tools_used && m.tools_used.length > 0 && (
                  <div className="ag-tools">
                    {dedupeAgent(m.tools_used).map((t, i) => (
                      <span key={i} className="ag-tool-tag">{TOOL_LABELS[t] || t}</span>
                    ))}
                  </div>
                )}
              </div>
            </div>
          ))}
          {busy && (
            <div className="ag-msg ai">
              <div className="ag-ava"><window.Icon.sparkle size={15} /></div>
              <div className="ag-bubble">
                <div className="ag-typing"><span /><span /><span /></div>
              </div>
            </div>
          )}
        </div>

        <div className="ag-input-wrap">
          <div className="ag-input">
            <textarea
              ref={inputRef}
              rows={1}
              placeholder="Demande une fiche de call, une relance, une réponse à un message…"
              value={input}
              onChange={(e) => setInput(e.target.value)}
              onKeyDown={(e) => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }}
            />
            <button className="btn primary" disabled={!input.trim() || busy} onClick={() => send()}>
              <window.Icon.send size={14} />
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

function dedupeAgent(arr) {
  const seen = new Set();
  const out = [];
  for (const x of arr) { if (!seen.has(x)) { seen.add(x); out.push(x); } }
  return out;
}

// ─── Markdown renderer (tables, listes, gras/italique/code, paragraphes) ──────
function escapeHtmlAgent(s) {
  return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
function renderInlineAgent(s) {
  return s
    .replace(/\*\*(.+?)\*\*/g, '<b>$1</b>')
    .replace(/(^|[^*])\*([^*\n]+)\*/g, '$1<i>$2</i>')
    .replace(/`([^`]+)`/g, '<code>$1</code>')
    .replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g, '<a href="$2" target="_blank" rel="noopener">$1</a>');
}
function parseRowAgent(line) {
  return line.replace(/^\s*\|/, '').replace(/\|\s*$/, '').split('|').map((c) => c.trim());
}
function renderAgentMarkdown(text) {
  if (!text) return '';
  const lines = escapeHtmlAgent(text).split('\n');
  const out = [];
  let i = 0;
  while (i < lines.length) {
    const line = lines[i];
    if (/^\s*\|.*\|\s*$/.test(line) && i + 1 < lines.length && /^\s*\|?\s*:?-{2,}/.test(lines[i + 1])) {
      const header = parseRowAgent(line);
      i += 2;
      const rows = [];
      while (i < lines.length && /^\s*\|.*\|\s*$/.test(lines[i])) { rows.push(parseRowAgent(lines[i])); i++; }
      out.push('<table class="ag-table"><thead><tr>' +
        header.map((c) => `<th>${renderInlineAgent(c)}</th>`).join('') +
        '</tr></thead><tbody>' +
        rows.map((r) => '<tr>' + r.map((c) => `<td>${renderInlineAgent(c)}</td>`).join('') + '</tr>').join('') +
        '</tbody></table>');
      continue;
    }
    let m;
    if ((m = line.match(/^###\s+(.*)$/))) { out.push(`<h4>${renderInlineAgent(m[1])}</h4>`); i++; continue; }
    if ((m = line.match(/^##\s+(.*)$/)))  { out.push(`<h3>${renderInlineAgent(m[1])}</h3>`); i++; continue; }
    if ((m = line.match(/^#\s+(.*)$/)))   { out.push(`<h3>${renderInlineAgent(m[1])}</h3>`); i++; continue; }
    if (/^\s*[-*]\s+/.test(line)) {
      const items = [];
      while (i < lines.length && /^\s*[-*]\s+/.test(lines[i])) { items.push(lines[i].replace(/^\s*[-*]\s+/, '')); i++; }
      out.push('<ul>' + items.map((it) => `<li>${renderInlineAgent(it)}</li>`).join('') + '</ul>');
      continue;
    }
    if (/^\s*\d+\.\s+/.test(line)) {
      const items = [];
      while (i < lines.length && /^\s*\d+\.\s+/.test(lines[i])) { items.push(lines[i].replace(/^\s*\d+\.\s+/, '')); i++; }
      out.push('<ol>' + items.map((it) => `<li>${renderInlineAgent(it)}</li>`).join('') + '</ol>');
      continue;
    }
    if (/^\s*$/.test(line)) { i++; continue; }
    const para = [line];
    i++;
    while (i < lines.length && !/^\s*$/.test(lines[i]) && !/^\s*[-*]\s+/.test(lines[i]) &&
      !/^\s*\d+\.\s+/.test(lines[i]) && !/^#{1,3}\s+/.test(lines[i]) && !/^\s*\|.*\|\s*$/.test(lines[i])) {
      para.push(lines[i]); i++;
    }
    out.push(`<p>${renderInlineAgent(para.join('<br/>'))}</p>`);
  }
  return out.join('');
}

window.AgentChat = AgentChat;
window.renderAgentMarkdown = renderAgentMarkdown;
