// SCREEN: AI Assistant — Perplexity-style chat
const escHtml = (s) => s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');

const AIScreen = () => {
  const [messages, setMessages] = React.useState(MOCK.chat);
  const [input, setInput] = React.useState('');
  const [streaming, setStreaming] = React.useState(false);

  const send = async (text) => {
    if (streaming) return;
    if (!text.trim()) return;
    setMessages(m => [...m, { role: 'user', text }]);
    setInput('');
    setStreaming(true);
    try {
      const res = await arFetch('/v1/query/natural', {
        method: 'POST',
        body: JSON.stringify({ query: text }),
      });
      const d = res.data || {};
      const qtype = res.parsed_query && res.parsed_query.query_type;
      const isTrend = qtype === 'trend';
      const rawVal = d.value !== undefined ? d.value
        : (d.current_value !== undefined ? d.current_value
        : (d.total_events || d.total_actors || d.total_conversions || '—'));
      const stat = {
        value: String(rawVal) + (d.unit || ''),
        delta: d.percent_change !== undefined
          ? (d.percent_change >= 0 ? '+' : '') + d.percent_change + '%'
          : '',
        base: `${d.time_range_days || 30}d window`,
      };
      setMessages(m => [...m, {
        role: 'ai',
        kind: isTrend ? 'trend' : 'metric',
        ans: res.answer || 'Query executed successfully.',
        stat,
        meta: `parsed_as=${qtype || 'unknown'} · latency=${Math.round(res.execution_time_ms || 0)}ms · model=gpt-4o-mini`,
      }]);
    } catch (e) {
      setMessages(m => [...m, {
        role: 'ai', kind: 'metric',
        ans: `I couldn't reach the analytics API for **"${escHtml(text)}"**. ${escHtml(e.message || 'Check API URL in Tweaks.')}`,
        stat: { value: '—', delta: '', base: 'API unavailable' },
        meta: 'fallback=true · mock_mode=on',
      }]);
    } finally {
      setStreaming(false);
    }
  };

  // Prefill + auto-send when navigated from dashboard hero
  React.useEffect(() => {
    const handler = (e) => { if (e.detail) send(e.detail); };
    window.addEventListener('ar:prefill', handler);
    return () => window.removeEventListener('ar:prefill', handler);
  }, []);

  const chips = [
    "What's our conversion rate this week?",
    "Top 5 converting paths last 30 days",
    "Compare Meta vs Google performance",
    "Which actors converted today?",
    "Why did conversion drop this morning?",
  ];

  return (
    <div style={{display: 'flex', gap: 20, height: '100%'}}>
      <div style={{flex: 1, display: 'flex', flexDirection: 'column', minWidth: 0}}>
        <div style={{display: 'flex', alignItems: 'center', gap: 10, marginBottom: 20}}>
          <div className="ai-icon" style={{width: 26, height: 26}} />
          <div>
            <div style={{fontSize: 15, fontWeight: 600}}>AstraReach AI</div>
            <div className="mono" style={{fontSize: 10, color: 'var(--text-3)'}}>
              <span className="dot pulse" style={{marginRight: 6, width: 5, height: 5}} />
              connected · gpt-4o-mini + groq/llama-3.3-70b fallback
            </div>
          </div>
        </div>

        <div style={{flex: 1, overflow: 'auto', paddingRight: 8}}>
          <div className="chat-wrap">
            {messages.map((m, i) => m.role === 'user' ? (
              <div key={i} className="bubble-user">{m.text}</div>
            ) : (
              <div key={i} className="bubble-ai">
                <div className="ans" dangerouslySetInnerHTML={{__html: m.ans.replace(/\*\*(.+?)\*\*/g, '<strong style="color:#F4F6FB">$1</strong>')}} />

                {m.kind === 'metric' && m.stat && (
                  <div style={{display: 'inline-flex', alignItems: 'baseline', gap: 16, marginTop: 14, padding: '14px 18px', background: 'var(--bg-1)', border: '1px solid var(--border)', borderRadius: 10}}>
                    <div>
                      <div style={{fontSize: 28, fontWeight: 600, letterSpacing: '-0.02em', fontVariantNumeric: 'tabular-nums'}}>{m.stat.value}</div>
                      <div style={{fontSize: 11, color: 'var(--text-3)', marginTop: 2}}>{m.stat.base}</div>
                    </div>
                    <div>
                      <span className="badge green" style={{fontSize: 11, padding: '3px 8px'}}>
                        <Icon name="up" size={10} />{m.stat.delta}
                      </span>
                    </div>
                  </div>
                )}

                {m.kind === 'trend' && (
                  <div style={{marginTop: 14, padding: 16, background: 'var(--bg-1)', border: '1px solid var(--border)', borderRadius: 10}}>
                    <svg viewBox="0 0 640 140" width="100%" height="140">
                      {[0.2, 0.4, 0.6, 0.8].map(t => <line key={t} x1="20" x2="620" y1={20 + t*100} y2={20 + t*100} stroke="#232A3B" strokeDasharray="2 3" />)}
                      {(() => {
                        const pts = MOCK.spark(7, 0.6).map((v, i) => [20 + (i / 29) * 600, 120 - (v / 100) * 100]);
                        // Step up after apr 15 (i=15)
                        const adjusted = pts.map(([x,y], i) => [x, i >= 15 ? y - 18 : y]);
                        const d = adjusted.map((p, i) => (i===0?'M':'L') + p[0].toFixed(1) + ' ' + p[1].toFixed(1)).join(' ');
                        const area = d + ' L 620 120 L 20 120 Z';
                        return <g>
                          <path d={area} fill="#8B5CF6" fillOpacity="0.15" />
                          <path d={d} stroke="#8B5CF6" strokeWidth="2" fill="none" />
                          <line x1={adjusted[15][0]} x2={adjusted[15][0]} y1="20" y2="120" stroke="#F59E0B" strokeDasharray="3 3" opacity="0.6" />
                          <text x={adjusted[15][0]+4} y="30" fontSize="10" fill="#F59E0B" fontFamily="var(--mono)">Apr 15 · deploy</text>
                          <circle cx={adjusted[15][0]} cy={adjusted[15][1]} r="4" fill="#F59E0B" />
                        </g>;
                      })()}
                    </svg>
                    <div style={{display: 'flex', gap: 20, marginTop: 12, fontSize: 11, color: 'var(--text-2)'}}>
                      <div><span style={{color: 'var(--text-3)'}}>Pre-deploy avg</span> <strong style={{color: 'var(--text-1)'}}>3.4%</strong></div>
                      <div><span style={{color: 'var(--text-3)'}}>Post-deploy avg</span> <strong style={{color: '#6ee7b7'}}>4.2%</strong></div>
                      <div><span style={{color: 'var(--text-3)'}}>p-value</span> <strong className="mono" style={{color: 'var(--text-1)'}}>0.0034</strong></div>
                    </div>
                  </div>
                )}

                <div className="meta">{m.meta}</div>
              </div>
            ))}

            {streaming && (
              <div className="bubble-ai">
                <div style={{display: 'flex', gap: 8, alignItems: 'center', color: 'var(--text-3)', fontSize: 12}}>
                  <span className="dot pulse violet" />
                  Retrieving 3 semantic memories · Generating response<span className="typing" />
                </div>
              </div>
            )}
          </div>
        </div>

        <div className="chat-input">
          <textarea
            placeholder="Ask anything... e.g. 'What's our conversion rate this week?' or 'Compare events this month vs last month'"
            value={input}
            onChange={e => setInput(e.target.value)}
            onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey && !streaming) { e.preventDefault(); send(input); }}}
          />
          <div style={{display: 'flex', alignItems: 'center', gap: 6, marginTop: 6}}>
            <div className="chip-row" style={{flex: 1, margin: 0}}>
              <button className="chip" onClick={() => setInput('Show me key metrics for the last 30 days')}>📊 Metrics</button>
              <button className="chip" onClick={() => setInput('Show me conversion rate trends over time')}>📈 Trends</button>
              <button className="chip" onClick={() => setInput('Compare this week vs last week')}>⚖️ Compare</button>
              <button className="chip" onClick={() => setInput('What are the top 5 converting paths?')}>🔝 Top paths</button>
              <button className="chip" onClick={() => setInput('How many unique actors converted today?')}>👤 Actors</button>
            </div>
            <button className="btn ghost" title="Voice input (coming soon)" onClick={() => alert('Voice input coming soon')}><Icon name="mic" size={14} /></button>
            <button className="btn primary" disabled={streaming} onClick={() => send(input)}>
              <Icon name="send" size={12} /> Send
            </button>
          </div>
        </div>
      </div>

      <div style={{width: 260, flexShrink: 0, overflow: 'auto'}}>
        <div className="card-title" style={{marginBottom: 10, fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--text-3)'}}>Suggested</div>
        <div style={{display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 22}}>
          {chips.map((c, i) => (
            <button key={i} className="chip" style={{textAlign: 'left', padding: '8px 12px', opacity: streaming ? 0.5 : 1, pointerEvents: streaming ? 'none' : 'auto'}} onClick={() => send(c)}>{c}</button>
          ))}
        </div>

        <div className="card-title" style={{marginBottom: 10, fontSize: 10, textTransform: 'uppercase', letterSpacing: '0.08em', color: 'var(--text-3)'}}>Supported metrics</div>
        <div style={{display: 'flex', flexDirection: 'column', gap: 4}}>
          {['conversion_rate', 'event_volume', 'unique_actors', 'avg_journey_length', 'channel_distribution', 'top_paths', 'bottleneck_rate'].map(m => (
            <div key={m} className="mono" style={{fontSize: 11, color: 'var(--text-2)', padding: '4px 8px', borderRadius: 4}}>{m}</div>
          ))}
        </div>
      </div>
    </div>
  );
};

window.AIScreen = AIScreen;
