const DSc = window.RallyAIBusiness_2d8789;
const { RallyFace: CFace, PixelIcon: CIcon, Chip: CChip, Button: CButton, Input: CInput } = DSc;

const QUICK = [
  ['Executive summary', 'Give me an executive summary of this view.'],
  ['Key trends', 'What are the top 3 trends or patterns in this data?'],
  ['Action plan', 'Draft a prioritized action plan — top 3 moves.'],
  ['What needs fixing?', 'Which journey touchpoints need fixing first, and why?'],
];

function ChatScreen({ scopeId, D, initialAsk }) {
  const [msgs, setMsgs] = React.useState([{ role: 'ai', text: `Looking at ${D.name}. Ask me anything — segments, journey, quests. I have the numbers.` }]);
  const [text, setText] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const boxRef = React.useRef(null);
  React.useEffect(() => { if (boxRef.current) boxRef.current.scrollTop = boxRef.current.scrollHeight; }, [msgs, busy]);
  React.useEffect(() => { setMsgs([{ role: 'ai', text: `Looking at ${D.name}. Ask me anything — segments, journey, quests. I have the numbers.` }]); }, [scopeId]);
  const askedRef = React.useRef(null);
  React.useEffect(() => { if (initialAsk && askedRef.current !== initialAsk) { askedRef.current = initialAsk; ask(initialAsk); } }, [initialAsk]);
  const ask = async (q) => {
    if (!q.trim() || busy) return;
    const history = [...msgs, { role: 'user', text: q }];
    setMsgs(history); setText(''); setBusy(true);
    try {
      const sys = `You are RALLY, the pixel-cat AI business consultant inside the Shiok Pun merchant app. Voice: direct, warm, second person, short lines. NO emoji. NO markdown symbols (#, *, **) — plain text only. Use '·' at line start for bullets. Keep answers under 90 words. Ground every claim in the data below; if something isn't in the data, say so plainly. Values marked (estimate) are estimates — flag them when you cite them.\n\n${RallyData.brief(scopeId)}`;
      const out = await window.claude.complete({ system: sys, max_tokens: 400, messages: history.slice(-10).map(m => ({ role: m.role === 'ai' ? 'assistant' : 'user', content: m.text })) });
      setMsgs(m => [...m, { role: 'ai', text: out }]);
    } catch (e) {
      setMsgs(m => [...m, { role: 'ai', text: 'I could not reach my brain just now. Try again in a moment.' }]);
    }
    setBusy(false);
  };
  return <div style={{ '--accent': 'var(--orange)', height: '100%', display: 'flex', flexDirection: 'column' }}>
    <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '14px 24px', borderBottom: '1px solid var(--ink)' }}>
      <CFace size={48} talking={busy} />
      <div><h1 style={{ fontSize: 'var(--text-title)' }}>Consultant</h1><div className="u-label" style={{ color: 'var(--text-muted)', marginTop: 2 }}>RALLY · online · {D.name}</div></div>
    </div>
    <div ref={boxRef} style={{ flex: 1, padding: '16px 24px', display: 'flex', flexDirection: 'column', gap: 14, overflowY: 'auto' }}>
      {msgs.map((m, i) => m.role === 'ai'
        ? <div key={i} style={{ maxWidth: '90%' }}><div className="u-pixel" style={{ marginBottom: 4 }}>RALLY</div><div style={{ fontSize: 16, fontWeight: 500, lineHeight: 1.4, whiteSpace: 'pre-wrap' }}>{m.text}</div></div>
        : <div key={i} style={{ alignSelf: 'flex-end', maxWidth: '80%', background: 'var(--ink)', color: 'var(--white)', padding: '10px 14px', fontSize: 15, lineHeight: 1.35 }}>{m.text}</div>)}
      {busy && <div className="u-pixel" style={{ color: 'var(--text-muted)' }}>RALLY IS THINKING…</div>}
      {!busy && <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 4 }}>
        {QUICK.map(([label, prompt]) => <span key={label} onClick={() => ask(prompt)} style={{ cursor: 'pointer' }}><CChip variant="outline">{label}</CChip></span>)}
      </div>}
    </div>
    <div style={{ display: 'flex', gap: 12, alignItems: 'flex-end', padding: '12px 24px 16px', borderTop: '1px solid var(--ink)' }}>
      <CInput placeholder="Ask about your customers" value={text} onChange={e => setText(e.target.value)} onKeyDown={e => e.key === 'Enter' && ask(text)} style={{ flex: 1 }} />
      <CButton variant="accent" size="sm" onClick={() => ask(text)} aria-label="send"><CIcon name="send" size={16} /></CButton>
    </div>
  </div>;
}

Object.assign(window, { ChatScreen });
