/* =============================================================
   Sentinel — Assistant (Command Center) component
   Adapted from the design handoff `cc-directions.jsx` so the
   conversational center mounts INSIDE the existing app shell
   (no own sidebar / no own topbar — those come from src/app.jsx).
   ============================================================= */

const { useState: ccUseState, useRef: ccUseRef, useEffect: ccUseEffect } = React;

// ---- Composer (the hero input) ----
function CCComposer({ value, onChange, onSend, placeholder, autoFocus }) {
  const taRef = ccUseRef(null);
  ccUseEffect(() => {
    const ta = taRef.current; if (!ta) return;
    ta.style.height = 'auto';
    ta.style.height = Math.min(ta.scrollHeight, 160) + 'px';
  }, [value]);
  const ready = value.trim().length > 0;
  return (
    <div className="cc-composer">
      <textarea
        ref={taRef}
        rows={1}
        value={value}
        autoFocus={autoFocus}
        placeholder={placeholder || 'Décrivez une intention… ex. « Audite mon parc et liste les agents à risque »'}
        onChange={e => onChange(e.target.value)}
        onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); onSend(); } }}
      />
      <div className="cc-composer-foot">
        <button className="cc-tool" type="button"><Icon name="upload" size={13} />Joindre</button>
        <button className="cc-tool" type="button"><Icon name="bot" size={13} />Périmètre · 142 agents</button>
        <button className="cc-tool scope" type="button"><Icon name="lock" size={13} />France · SecNumCloud</button>
        <button className={`cc-send ${ready ? 'ready' : ''}`} type="button" onClick={onSend} aria-label="Envoyer">
          <Icon name="arrowRight" size={18} />
        </button>
      </div>
    </div>
  );
}

// ---- Shortcut presets (cards) ----
function CCShortcuts({ onPick }) {
  return (
    <div className="cc-shortcuts">
      {CC_SHORTCUTS.map(s => (
        <button key={s.id} className="cc-shortcut" onClick={() => onPick(s)}>
          <span className="ic"><Icon name={s.icon} size={18} /></span>
          <span className="tx"><b>{s.title}</b><span>{s.sub}</span></span>
        </button>
      ))}
    </div>
  );
}

// ---- The Assistant component — slots inside the app shell ----
// Props:
//   initial: null = empty Accueil; or one of CC_SHORTCUTS ids = seeded conversation
//   onNavigate(screenKey): optional, called when an action proposes opening a module screen
function Assistant({ initial = null, onNavigate }) {
  const seed = initial
    ? (() => {
        const s = CC_SHORTCUTS.find(x => x.id === initial) || CC_SHORTCUTS[0];
        // Seed messages render at mount, so do NOT animate them (see README handoff note).
        return [{ role: 'user', text: s.prompt }, { role: 'assistant', intent: initial }];
      })()
    : [];

  const [messages, setMessages] = ccUseState(seed);
  const [input, setInput] = ccUseState('');
  const [thinking, setThinking] = ccUseState(false);
  const stageRef = ccUseRef(null);
  const inConversation = messages.length > 0;

  ccUseEffect(() => {
    const el = stageRef.current;
    if (el && inConversation) el.scrollTop = el.scrollHeight;
  }, [messages, thinking, inConversation]);

  const push = (m) => setMessages(prev => [...prev, m]);

  const sendIntent = (text, intent) => {
    const it = intent || ccResolveIntent(text);
    push({ role: 'user', text, _anim: true });
    setInput('');
    setThinking(true);
    setTimeout(() => { setThinking(false); push({ role: 'assistant', intent: it, _anim: true }); }, 950);
  };

  const onSend = () => { const t = input.trim(); if (t) sendIntent(t); };
  const onPick = (s) => sendIntent(s.prompt, s.id);

  const onAction = (key) => {
    // Proposed-action wiring — module-opening actions jump to the relevant screen,
    // everything else appends a confirmation message in-thread.
    const moduleJump = {
      'open-parc':     'ag1',
      'open-incident': 'se3',
      'open-registry': 'co1',
    };
    if (moduleJump[key] && onNavigate) { onNavigate(moduleJump[key]); return; }
    if (key === 'report') { sendIntent('Génère le rapport de conformité AI Act.', 'report'); return; }
    const notes = {
      'isolate':       'C’est fait — les 3 agents sont isolés et leurs jetons révoqués. Action tracée dans la piste d’audit (réf. AUD-7741).',
      'confirm-kill':  'Kill switch appliqué sur Recouvrement-RAG. Connecteurs figés, RSSI notifié. Vous pouvez réactiver l’agent depuis le module Pilotage.',
      'keep-isolated': 'Agent maintenu en quarantaine. Je rouvre l’incident SE-2406 pour suivi.',
      'export-pdf':    'Dossier AI Act exporté (PDF signé) et déposé dans le Coffre de preuves.',
      'export-deck':   'Synthèse COMEX exportée en 6 slides — prête à présenter.',
      'publish':       'Policy « Anti-exfiltration » publiée sur les 38 agents concernés.',
      'simulate':      'Simulation lancée sur les 38 agents — aucun faux positif détecté sur les 7 derniers jours.',
      'postmortem':    'Post-mortem rédigé et déposé dans le module Sécurité.',
      'renew-dpia':    'Les 2 DPIA expirées ont été pré-remplies — il reste à valider la partie analytique avec le DPO.',
      'edit-policy':   'Brouillon ouvert dans l’éditeur de policies.',
      'schedule':      'Envoi hebdo programmé chaque vendredi à 17 h — destinataires : COMEX.',
      'cancel':        'Annulé. Aucune action effectuée.',
    };
    if (notes[key]) push({ role: 'assistant', text: notes[key], _anim: true });
  };

  const greeting = (
    <>
      <div className="cc-eyebrow"><span className="mark-dot"><ProviderMarkHF name="Ascenzia" size={18} radius={999} /></span>Assistant Sentinel</div>
      <h1 className="cc-greeting">Bonjour Léa.<br />Que souhaitez-vous <span className="accent">piloter</span> ?</h1>
      <p className="cc-subgreeting">
        Décrivez une intention en langage naturel ou lancez une fonction. L’assistant agit sur vos
        142 agents, dans votre juridiction, et trace chaque action.
      </p>
    </>
  );

  // ----- WELCOME STATE -----
  if (!inConversation) {
    return (
      <div className="cc-page">
        <div className="cc-stage">
          <div className="cc-hero">
            <div className="cc-hero-inner">
              {greeting}
              <div className="cc-composer-wrap">
                <CCComposer value={input} onChange={setInput} onSend={onSend} autoFocus={true} />
              </div>
              <CCShortcuts onPick={onPick} />
              <div className="cc-suggest-label">Reprendre / suggestions</div>
              <div className="cc-suggest">
                {CC_SUGGESTIONS.map((s, i) => (
                  <button className="cc-suggest-row" key={i} onClick={() => sendIntent(s.text, s.intent)}>
                    <Icon name={s.icon} size={15} />{s.text}
                    <span className="arr"><Icon name="arrowRight" size={14} /></span>
                  </button>
                ))}
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }

  // ----- CONVERSATION STATE -----
  return (
    <div className="cc-page">
      <div className="cc-stage" ref={stageRef}>
        <div className="cc-thread">
          {messages.map((m, i) => (
            m.role === 'user' ? (
              <div className={`cc-msg user ${m._anim ? 'cc-anim' : ''}`} key={i}><div className="cc-bubble">{m.text}</div></div>
            ) : (
              <div className={`cc-msg assistant ${m._anim ? 'cc-anim' : ''}`} key={i}>
                <div className="cc-ava"><ProviderMarkHF name="Ascenzia" size={34} radius={999} /></div>
                <div className="cc-assistant-body">
                  <div className="cc-assistant-name">Assistant Sentinel</div>
                  {m.intent ? <AssistantResponse intent={m.intent} onAction={onAction} /> : <div className="cc-assistant-text">{m.text}</div>}
                </div>
              </div>
            )
          ))}
          {thinking && (
            <div className="cc-msg assistant">
              <div className="cc-ava"><ProviderMarkHF name="Ascenzia" size={34} radius={999} /></div>
              <div className="cc-assistant-body"><div className="cc-assistant-name">Assistant Sentinel</div><TypingDots /></div>
            </div>
          )}
        </div>
      </div>
      <div className="cc-dock">
        <div className="cc-composer-wrap">
          <CCComposer value={input} onChange={setInput} onSend={onSend} placeholder="Poursuivre la conversation…" />
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Assistant, CCComposer, CCShortcuts });
