// Command palette — wired to the global actions registry
function CommandPalette({ open, onClose, onNav }) {
  const [q, setQ] = React.useState('');
  const [sel, setSel] = React.useState(0);
  const inputRef = React.useRef(null);
  React.useEffect(() => {
    if (open) setTimeout(() => inputRef.current?.focus(), 50);
    else setQ('');
  }, [open]);
  React.useEffect(() => { setSel(0); }, [q]);

  if (!open) return null;

  // ---------- knowledge graph for search ----------
  // Many synonyms route to the right place. "revenue" → analytics, "tiktok" → channels, etc.
  const NAV_ITEMS = [
    { icon: 'Home',      t: 'Command Center · Home',       hint: 'G H', keywords: 'dashboard home overview',                   action: () => onNav('dashboard') },
    { icon: 'Agent',     t: 'Agents · Operators',          hint: 'G A', keywords: 'agents operators atlas nyx calliope orpheus persona', action: () => onNav('agents') },
    { icon: 'Flow',      t: 'Workflows · Automations',     hint: 'G W', keywords: 'workflows automations flow pipelines',       action: () => onNav('workflows') },
    { icon: 'Funnel',    t: 'Funnels · Customer journey',  hint: 'G F', keywords: 'funnels journey conversion path',             action: () => onNav('funnels') },
    { icon: 'Megaphone', t: 'Campaigns',                    hint: 'G C', keywords: 'campaigns marketing promotions offers',      action: () => onNav('campaigns') },
    { icon: 'Inbox',     t: 'Inbox · Messages',             hint: 'G I', keywords: 'inbox messages threads dms replies email sms', action: () => onNav('inbox') },
    { icon: 'People',    t: 'Contacts · Customers · Leads', hint: '',    keywords: 'contacts customers leads people crm',         action: () => onNav('contacts') },
    { icon: 'Globe',     t: 'Channels · Social media',      hint: '',    keywords: 'channels social media tiktok instagram facebook linkedin whatsapp email broadcast', action: () => onNav('channels') },
    { icon: 'Calendar',  t: 'Calendar · Appointments',      hint: '',    keywords: 'calendar appointments bookings meetings schedule', action: () => onNav('calendar') },
    { icon: 'Chart',     t: 'Analytics · Revenue · ROAS',   hint: '',    keywords: 'analytics insights revenue money roas cac ltv reports', action: () => onNav('analytics') },
    { icon: 'Sparkles',  t: 'Persona Studio',                hint: '',    keywords: 'persona voice clone brand',                    action: () => onNav('persona') },
    { icon: 'Book',      t: 'Templates',                     hint: '',    keywords: 'templates library presets',                    action: () => onNav('templates') },
    { icon: 'Plug',      t: 'Integrations',                  hint: '',    keywords: 'integrations api connections plugs',           action: () => onNav('integrations') },
    { icon: 'Settings',  t: 'Settings · Billing · Team · API', hint: '', keywords: 'settings billing team api notifications voice plan invoice payment', action: () => onNav('settings') },
    { icon: 'Target',    t: 'Mission Control',               hint: '',    keywords: 'mission control telemetry operators',          action: () => onNav('mission') },
    { icon: 'Trophy',    t: 'Businesses',                    hint: '',    keywords: 'businesses brands clients agency portfolio',    action: () => onNav('businesses') },
  ];

  const CREATE_ITEMS = [
    { icon: 'Plus',      t: 'Launch a campaign…',          hint: 'C C', keywords: 'launch campaign new email sms ads',           action: () => window.runAction('launchCampaign') },
    { icon: 'Plus',      t: 'Create a funnel…',            hint: 'C F', keywords: 'create funnel new journey conversion',         action: () => window.runAction('createFunnel') },
    { icon: 'Plus',      t: 'Deploy a workflow…',          hint: 'C W', keywords: 'deploy workflow automation new',                action: () => window.runAction('deployWorkflow') },
    { icon: 'Plus',      t: 'Spin up an operator…',        hint: 'C A', keywords: 'spin up agent operator new deploy',             action: () => window.runAction('spinUpAgent') },
    { icon: 'Sparkles',  t: 'Post everywhere…',            hint: '',    keywords: 'post everywhere social distribution all',       action: () => window.runAction('postEverywhere') },
    { icon: 'Sparkles',  t: 'Create content (AI Studio)…', hint: '',    keywords: 'create content studio post carousel video email caption ad', action: () => window.runAction('createContent') },
    { icon: 'Mail',      t: 'Compose message…',            hint: '',    keywords: 'compose message email sms send write',          action: () => window.runAction('compose') },
  ];

  const INTEL_ITEMS = [
    { icon: 'Sparkles',  t: 'Run AI Audit',                hint: '',    keywords: 'audit ai scan analysis check',                  action: () => window.runAction('runAIAudit') },
    { icon: 'Chart',     t: 'Run deep analysis',            hint: '',    keywords: 'analysis deep intelligence',                    action: () => window.runAction('deepAnalysis') },
    { icon: 'Chart',     t: 'Generate a report',            hint: '',    keywords: 'report generate executive summary pdf',         action: () => window.runAction('generateReport') },
    { icon: 'Bolt',      t: 'Get more leads (recommendations)', hint: '', keywords: 'leads grow more recommendations',              action: () => window.runAction('leadGrowth') },
    { icon: 'Funnel',    t: 'Improve your funnel',          hint: '',    keywords: 'improve funnel optimize journey conversion',    action: () => window.runAction('improveFunnel') },
  ];

  // Natural-language ask intent matchers (when no nav match)
  const matchAsk = (s) => {
    const m = s.toLowerCase().trim();
    if (!m) return null;
    if (/^launch\b.*campaign|^new.*campaign/.test(m)) return { do: 'launchCampaign', label: 'Launch a campaign' };
    if (/^create\b.*post|^post.*everywhere|^new.*post|^create.*content/.test(m)) return { do: 'createContent', label: 'Create content' };
    if (/book.*leads?|book.*meeting|book.*appointment/.test(m)) return { do: 'seeAppointments', label: 'See appointments / book leads' };
    if (/why.*(leads?|conver|drop|funnel)/.test(m)) return { do: 'improveFunnel', label: 'Diagnose funnel drop-off' };
    if (/^run.*audit|^audit/.test(m)) return { do: 'runAIAudit', label: 'Run AI audit' };
    if (/^message|^reply|^email.*customer/.test(m)) return { do: 'messageCustomers', label: 'Open inbox · message customers' };
    if (/grow|more.*revenue|sell.*more|more.*leads/.test(m)) return { do: 'leadGrowth', label: 'Show growth recommendations' };
    return null;
  };

  const buildFiltered = () => {
    if (!q) {
      return [
        { group: 'NAVIGATE', items: NAV_ITEMS.slice(0, 7) },
        { group: 'CREATE',   items: CREATE_ITEMS },
        { group: 'INTELLIGENCE', items: INTEL_ITEMS },
      ];
    }
    const query = q.toLowerCase();
    const score = (it) => {
      const hay = (it.t + ' ' + (it.keywords || '')).toLowerCase();
      if (hay.startsWith(query)) return 3;
      if (hay.includes(query)) return 2;
      const words = query.split(/\s+/);
      if (words.every(w => hay.includes(w))) return 1;
      return 0;
    };
    const filt = (arr) => arr.map(i => ({ ...i, _score: score(i) })).filter(i => i._score > 0).sort((a, b) => b._score - a._score);
    const result = [
      { group: 'NAVIGATE',     items: filt(NAV_ITEMS) },
      { group: 'CREATE',       items: filt(CREATE_ITEMS) },
      { group: 'INTELLIGENCE', items: filt(INTEL_ITEMS) },
    ].filter(g => g.items.length > 0);

    // If no direct match, fall back to an "ask" interpretation
    if (result.length === 0) {
      const ask = matchAsk(query);
      const items = [];
      if (ask) {
        items.push({ icon: 'Sparkles', t: ask.label, hint: 'Demiurge', action: () => window.runAction(ask.do) });
      }
      items.push({ icon: 'Sparkles', t: `Ask Demiurge: "${q}"`, hint: 'Open AI', action: () => { window.demiurgeOpenAI?.(); } });
      return [{ group: 'ASK DEMIURGE', items }];
    }
    return result;
  };

  const filtered = buildFiltered();
  const flat = filtered.flatMap(g => g.items);

  const onKey = (e) => {
    if (e.key === 'ArrowDown') { e.preventDefault(); setSel(s => Math.min(flat.length - 1, s + 1)); }
    else if (e.key === 'ArrowUp') { e.preventDefault(); setSel(s => Math.max(0, s - 1)); }
    else if (e.key === 'Enter') {
      e.preventDefault();
      const item = flat[sel];
      if (item) { item.action?.(); onClose(); }
    } else if (e.key === 'Escape') onClose();
  };

  let runningIdx = -1;
  return (
    <div className="cmdk-backdrop" onClick={onClose}>
      <div className="cmdk" onClick={e => e.stopPropagation()}>
        <div className="cmdk-input">
          <span className="cmdk-prefix">DEM ›</span>
          <input ref={inputRef} placeholder="Search, navigate, or ask anything…" value={q} onChange={e => setQ(e.target.value)} onKeyDown={onKey}/>
          <span className="kbd">ESC</span>
        </div>
        <div className="cmdk-list">
          {filtered.map(g => (
            <div key={g.group}>
              <div className="cmdk-group-label">{g.group}</div>
              {g.items.map((i) => {
                runningIdx += 1;
                const I = Icon[i.icon] || Icon.Plus;
                const active = runningIdx === sel;
                return (
                  <div key={`${g.group}-${i.t}`} className={`cmdk-item ${active ? 'sel' : ''}`} onClick={() => { i.action?.(); onClose(); }} onMouseEnter={(() => { const captured = runningIdx; return () => setSel(captured); })()}>
                    <I className="icon" style={g.group === 'INTELLIGENCE' || g.group === 'ASK DEMIURGE' ? { color: 'var(--violet)' } : {}}/>
                    <span>{i.t}</span>
                    {i.hint && <span className="hint">{i.hint}</span>}
                  </div>
                );
              })}
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

// AI assistant floating panel — chips run real actions
function AIPanel({ open, onClose }) {
  const ACTION_KEY = {
    'Pause "Cold #2"':        () => window.toast('Calliope · "Cold #2" paused', 'warn', 'Drafts preserved · resume any time'),
    'Show diagnostics':       () => window.runAction('viewLogs', { source: 'calliope · cold-2' }),
    'Suggest replacement':    () => window.runAction('createContent'),
    'Launch campaign':        () => window.runAction('launchCampaign'),
    'Create post':            () => window.runAction('postEverywhere'),
    'Book leads':             () => window.runAction('seeAppointments'),
    'Run audit':              () => window.runAction('runAIAudit'),
    'Improve funnel':         () => window.runAction('improveFunnel'),
    'See revenue':            () => window.demiurgeNav?.('analytics'),
  };
  const NL_INTENT = [
    { rx: /(launch|start|new).*campaign/i,    key: 'Launch campaign' },
    { rx: /(post|publish|share).*(social|everywhere|content)/i, key: 'Create post' },
    { rx: /create.*post/i,                     key: 'Create post' },
    { rx: /book.*(leads?|meeting)/i,           key: 'Book leads' },
    { rx: /(run|do).*audit/i,                  key: 'Run audit' },
    { rx: /improve.*funnel|fix.*funnel/i,      key: 'Improve funnel' },
    { rx: /revenue|how much.*money/i,          key: 'See revenue' },
  ];

  const [msgs, setMsgs] = React.useState([
    { role: 'agent', t: 'Hi Reza. I\'m watching all 8 operators in real time. Want a status check?', actions: ['Launch campaign', 'Create post', 'Book leads', 'Run audit'] },
    { role: 'user', t: 'show me the worst-performing sequence' },
    { role: 'agent', t: 'Calliope · "Cold #2" has a spam score of 4.1 and -38% reply rate vs other sequences this week. It\'s likely hurting your domain reputation.', actions: ['Pause "Cold #2"', 'Show diagnostics', 'Suggest replacement'] },
  ]);
  const [input, setInput] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const scrollRef = React.useRef(null);

  React.useEffect(() => { scrollRef.current?.scrollTo({ top: 1e9, behavior: 'smooth' }); }, [msgs]);

  if (!open) return null;

  const sendIntent = (text) => {
    // Check intent map for action shortcuts before falling back to LLM
    for (const { rx, key } of NL_INTENT) {
      if (rx.test(text)) {
        setMsgs(m => [...m, { role: 'user', t: text }, { role: 'agent', t: `On it — opening ${key.toLowerCase()}…`, actions: [key] }]);
        return true;
      }
    }
    return false;
  };

  const send = async () => {
    const text = input.trim();
    if (!text) return;
    setInput('');
    if (sendIntent(text)) return;
    setMsgs(m => [...m, { role: 'user', t: text }]);
    setBusy(true);
    try {
      const reply = await window.claude.complete({
        messages: [{ role: 'user', content: `You are Demiurge, the operator-of-operators AI for a small business. Reply briefly (2-3 sentences, conversational) to: "${text}"` }]
      });
      setMsgs(m => [...m, { role: 'agent', t: reply }]);
    } catch {
      setMsgs(m => [...m, { role: 'agent', t: 'I caught that. Let me get back to you in a moment — meanwhile, you can use the quick actions above.' }]);
    }
    setBusy(false);
  };

  const runChip = (label) => {
    const fn = ACTION_KEY[label];
    if (fn) fn();
    else window.toast(label, 'info', 'Action queued');
  };

  return (
    <div className="ai-panel">
      <div style={{ padding: '14px 16px', borderBottom: '1px solid var(--border)', display: 'flex', alignItems: 'center', gap: 10 }}>
        <div style={{ width: 28, height: 28, borderRadius: '50%', background: 'var(--iridescent)', position: 'relative' }}>
          <div style={{ position: 'absolute', inset: -3, borderRadius: '50%', background: 'var(--iridescent)', opacity: 0.4, filter: 'blur(8px)', zIndex: -1 }}/>
        </div>
        <div style={{ flex: 1 }}>
          <div className="row" style={{ gap: 8 }}>
            <span className="serif" style={{ fontSize: 16, fontStyle: 'italic' }}>Demiurge</span>
            <span className="tag live">ONLINE</span>
          </div>
          <div className="mono faint" style={{ fontSize: 10 }}>watching 8 operators · last sync 4s ago</div>
        </div>
        <button className="icon-btn" onClick={onClose} data-handled="1"><Icon.X/></button>
      </div>
      <div ref={scrollRef} style={{ flex: 1, padding: 16, overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 12 }}>
        {msgs.map((m, i) => (
          <div key={i} style={{ alignSelf: m.role === 'user' ? 'flex-end' : 'flex-start', maxWidth: '85%' }}>
            <div style={{
              padding: '10px 14px',
              background: m.role === 'user' ? 'var(--iridescent)' : 'rgba(255, 255, 255, 0.04)',
              border: m.role === 'user' ? 'none' : '1px solid var(--border)',
              borderRadius: m.role === 'user' ? '14px 14px 4px 14px' : '14px 14px 14px 4px',
              fontSize: 13,
              lineHeight: 1.5,
              color: m.role === 'user' ? '#07091a' : 'var(--text)',
              fontWeight: m.role === 'user' ? 500 : 400,
              whiteSpace: 'pre-wrap',
            }}>
              {m.t}
            </div>
            {m.actions && (
              <div className="row" style={{ marginTop: 8, gap: 6, flexWrap: 'wrap' }}>
                {m.actions.map(a => <button key={a} className="btn sm" data-handled="1" onClick={() => runChip(a)}>{a}</button>)}
              </div>
            )}
          </div>
        ))}
        {busy && (
          <div style={{ alignSelf: 'flex-start', padding: '10px 14px', background: 'rgba(255, 255, 255, 0.04)', border: '1px solid var(--border)', borderRadius: '14px 14px 14px 4px', fontSize: 13 }}>
            <span className="dim">thinking</span><span className="caret" style={{ height: 12, marginLeft: 4 }}/>
          </div>
        )}
      </div>
      <div style={{ padding: 12, borderTop: '1px solid var(--border)' }}>
        <div className="row" style={{ background: 'rgba(0, 0, 0, 0.3)', border: '1px solid var(--border)', borderRadius: 'var(--radius)', padding: '8px 12px', gap: 8 }}>
          <input
            placeholder="Ask Demiurge…  (try: launch a campaign)"
            value={input}
            onChange={e => setInput(e.target.value)}
            onKeyDown={e => { if (e.key === 'Enter') send(); }}
            style={{ flex: 1, fontSize: 12 }}
          />
          <button onClick={send} data-handled="1" style={{ color: 'var(--cyan)' }}><Icon.Sparkles style={{ width: 14, height: 14 }}/></button>
        </div>
      </div>
    </div>
  );
}

window.CommandPalette = CommandPalette;
window.AIPanel = AIPanel;
