// Ask Himma — AI chat screen

function ChatScreen({ theme, accent }) {
  const [messages, setMessages] = React.useState([
    { who:'ai', text: `Assalamu alaikum, ${USER.firstName}. I've got a full view of your accounts. Ask me anything — from net worth to cash flow to tactical moves.` },
  ]);
  const [input, setInput] = React.useState('');
  const [typing, setTyping] = React.useState(false);
  const scrollRef = React.useRef();

  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages, typing]);

  const getResponse = (text) => {
    const lower = text.toLowerCase();
    if (lower.includes('net worth') || lower.includes('total') || lower.includes('everything')) return AI_SCRIPT.networth;
    if (lower.includes('crypto') || lower.includes('stock')) return AI_SCRIPT.crypto;
    if (lower.includes('liquid') || lower.includes('property') || lower.includes('mortgage') || lower.includes('down payment')) return AI_SCRIPT.liquid;
    if (lower.includes('spend') || lower.includes('spent') || lower.includes('overspend') || lower.includes('month')) return AI_SCRIPT.spend;
    return { text: `I'd need to think on that. Try asking about your net worth, crypto vs stocks, cash flow, or whether you're liquid enough for a property move.`, card: null };
  };

  const send = (text) => {
    if (!text.trim()) return;
    setMessages(m => [...m, { who:'user', text }]);
    setInput('');
    setTyping(true);
    setTimeout(() => {
      const r = getResponse(text);
      setTyping(false);
      setMessages(m => [...m, { who:'ai', text: r.text, card: r.card, follow: r.follow }]);
    }, 700);
  };

  return (
    <div style={{ height:'100%', display:'flex', flexDirection:'column' }}>
      {/* Header */}
      <div style={{ padding: '8px 22px 10px', display:'flex', alignItems:'center', gap: 10, borderBottom: `0.5px solid ${theme.line}` }}>
        <div style={{
          width: 36, height: 36, borderRadius: 18,
          background: `linear-gradient(135deg, ${accent}, ${accent}80)`,
          display:'flex', alignItems:'center', justifyContent:'center',
          color: theme.bg,
        }}><Ico.sparkles size={16} sw={1.8}/></div>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: FONTS.display, fontSize: 17, color: theme.text }}>Ask Himma</div>
          <div style={{ fontFamily: FONTS.mono, fontSize: 10, color: theme.positive, display:'flex', alignItems:'center', gap: 4 }}>
            <span style={{ width: 5, height: 5, borderRadius: 3, background: theme.positive }}/> Private · end-to-end
          </div>
        </div>
        <Ico.dots size={16} style={{ color: theme.textDim }}/>
      </div>

      {/* Messages */}
      <div ref={scrollRef} style={{ flex: 1, overflowY: 'auto', padding: '18px 16px 120px' }}>
        {messages.map((m, i) => (
          <Message key={i} m={m} theme={theme} accent={accent}/>
        ))}
        {typing && <TypingIndicator theme={theme} accent={accent}/>}

        {messages.length === 1 && (
          <div style={{ marginTop: 24 }}>
            <div style={{ fontFamily: FONTS.mono, fontSize: 10, color: theme.textMute, textTransform: 'uppercase', letterSpacing: 1.2, marginBottom: 10, paddingLeft: 4 }}>Try asking</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {CHAT_PROMPTS.map(p => (
                <button key={p} onClick={() => send(p)} style={{
                  background: theme.surface,
                  border: `0.5px solid ${theme.line2}`,
                  color: theme.text,
                  fontFamily: FONTS.ui,
                  fontSize: 13,
                  textAlign: 'left',
                  padding: '13px 16px',
                  borderRadius: 16, cursor: 'pointer',
                  display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                }}>
                  <span>{p}</span>
                  <Ico.arrowUR size={14} stroke={accent}/>
                </button>
              ))}
            </div>
          </div>
        )}
      </div>

      {/* Input */}
      <div style={{
        position: 'absolute', left: 0, right: 0, bottom: 100, padding: '0 16px',
      }}>
        <div style={{
          background: theme.surface2,
          border: `0.5px solid ${theme.line2}`,
          borderRadius: 22,
          padding: '8px 8px 8px 16px',
          display: 'flex', alignItems: 'center', gap: 8,
          boxShadow: `0 10px 30px ${theme.bg}80`,
        }}>
          <input
            value={input}
            onChange={e => setInput(e.target.value)}
            onKeyDown={e => e.key === 'Enter' && send(input)}
            placeholder="Ask Himma…"
            style={{
              flex: 1, background: 'transparent', border: 'none', outline: 'none',
              color: theme.text, fontSize: 14, fontFamily: FONTS.ui, padding: '8px 0',
            }}
          />
          <button onClick={() => send(input)} style={{
            width: 34, height: 34, borderRadius: 17,
            background: input.trim() ? accent : theme.surface3,
            border: 'none', cursor: 'pointer',
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: input.trim() ? theme.bg : theme.textMute,
            transition: 'all 120ms',
          }}>
            <Ico.send size={15} sw={1.8}/>
          </button>
        </div>
      </div>
    </div>
  );
}

function Message({ m, theme, accent }) {
  if (m.who === 'user') {
    return (
      <div style={{ display: 'flex', justifyContent:'flex-end', marginBottom: 12 }}>
        <div style={{
          background: accent, color: theme.bg,
          padding: '10px 14px', borderRadius: '18px 18px 4px 18px',
          maxWidth: '78%', fontSize: 13.5, fontFamily: FONTS.ui, lineHeight: 1.4,
        }}>{m.text}</div>
      </div>
    );
  }
  return (
    <div style={{ display: 'flex', gap: 8, marginBottom: 14 }}>
      <div style={{
        width: 26, height: 26, borderRadius: 13, flexShrink: 0,
        background: `${accent}20`, color: accent,
        display:'flex', alignItems:'center', justifyContent:'center',
        marginTop: 2,
      }}><Ico.sparkles size={12}/></div>
      <div style={{ flex: 1, maxWidth: 'calc(100% - 40px)' }}>
        <div style={{
          background: theme.surface,
          border: `0.5px solid ${theme.line}`,
          color: theme.text,
          padding: '12px 14px', borderRadius: '18px 18px 18px 4px',
          fontSize: 13.5, fontFamily: FONTS.ui, lineHeight: 1.5,
        }}>{dhText(m.text)}</div>

        {m.card && <ChatCard card={m.card} theme={theme} accent={accent}/>}

        {m.follow && (
          <div style={{
            background: theme.surface, border: `0.5px solid ${theme.line}`,
            color: theme.textDim, marginTop: 6,
            padding: '10px 14px', borderRadius: 18,
            fontSize: 12.5, fontFamily: FONTS.ui, lineHeight: 1.5, fontStyle: 'italic',
          }}>{dhText(m.follow)}</div>
        )}
      </div>
    </div>
  );
}

function ChatCard({ card, theme, accent }) {
  if (card.type === 'breakdown') {
    return (
      <div style={{ marginTop: 8, background: theme.surface2, border: `0.5px solid ${theme.line}`, borderRadius: 16, padding: 14 }}>
        <div style={{ display:'flex', gap: 12, alignItems:'center' }}>
          <Donut segments={ASSET_BREAKDOWN} size={80} stroke={9} theme={theme}/>
          <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 4 }}>
            {ASSET_BREAKDOWN.map(s => (
              <div key={s.key} style={{ display: 'flex', alignItems: 'center', gap: 7, fontSize: 11 }}>
                <div style={{ width: 6, height: 6, borderRadius: 1, background: s.color }}/>
                <div style={{ flex: 1, color: theme.textDim, fontFamily: FONTS.ui }}>{s.label}</div>
                <div style={{ fontFamily: FONTS.mono, color: theme.text }}>{(s.value/NET_WORTH*100).toFixed(0)}%</div>
              </div>
            ))}
          </div>
        </div>
      </div>
    );
  }
  if (card.type === 'compare') {
    return (
      <div style={{ marginTop: 8, background: theme.surface2, border: `0.5px solid ${theme.line}`, borderRadius: 16, overflow: 'hidden' }}>
        {card.rows.map((r, i) => (
          <div key={i} style={{
            padding: '12px 14px',
            borderBottom: i < card.rows.length - 1 ? `0.5px solid ${theme.line}` : 'none',
            display: 'flex', alignItems:'center', justifyContent:'space-between',
          }}>
            <div>
              <div style={{ fontSize: 13, color: theme.text, fontWeight: 500 }}>{r.label}</div>
              <div style={{ fontSize: 11, color: theme.textMute, fontFamily: FONTS.mono, marginTop: 2 }}>{dhText(r.sub)}</div>
            </div>
            <div style={{ fontFamily: FONTS.mono, fontSize: 15, color: r.tone==='pos' ? theme.positive : theme.negative }}>{r.value}</div>
          </div>
        ))}
      </div>
    );
  }
  if (card.type === 'liquidity') {
    const pct = card.ready / card.target * 100;
    return (
      <div style={{ marginTop: 8, background: theme.surface2, border: `0.5px solid ${theme.line}`, borderRadius: 16, padding: 14 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', marginBottom: 10 }}>
          <div>
            <div style={{ fontSize: 10, color: theme.textMute, textTransform:'uppercase', letterSpacing: 1, fontFamily: FONTS.mono }}>Down payment</div>
            <div style={{ fontFamily: FONTS.display, fontSize: 22, color: theme.text, marginTop: 2 }}><Dh/> {fmtAED(card.ready, {compact: true})} <span style={{ color: theme.textMute, fontSize: 14 }}>/ {fmtAED(card.target, {compact: true})}</span></div>
          </div>
          <Tag theme={theme} color={accent}>{card.eta}</Tag>
        </div>
        <div style={{ height: 8, borderRadius: 4, background: theme.surface3, overflow: 'hidden' }}>
          <div style={{ height: '100%', width: `${pct}%`, background: `linear-gradient(90deg, ${accent}, ${accent}cc)`, borderRadius: 4 }}/>
        </div>
        <div style={{ fontFamily: FONTS.mono, fontSize: 10, color: theme.textMute, marginTop: 6 }}>{pct.toFixed(0)}% of target</div>
      </div>
    );
  }
  if (card.type === 'spend') {
    const max = Math.max(...card.items.map(x => x.value));
    return (
      <div style={{ marginTop: 8, background: theme.surface2, border: `0.5px solid ${theme.line}`, borderRadius: 16, padding: 14, display: 'flex', flexDirection: 'column', gap: 10 }}>
        {card.items.map((it, i) => (
          <div key={i}>
            <div style={{ display:'flex', justifyContent:'space-between', fontSize: 11.5, marginBottom: 4 }}>
              <span style={{ color: theme.text }}>{it.label}</span>
              <span style={{ fontFamily: FONTS.mono, color: theme.text }}><Dh/> {fmtAED(it.value)} <span style={{ color: it.delta >= 0 ? theme.negative : theme.positive }}>{it.delta >= 0 ? '+' : ''}{fmtAED(it.delta)}</span></span>
            </div>
            <div style={{ height: 3, borderRadius: 2, background: theme.surface3 }}>
              <div style={{ height: '100%', width: `${it.value/max*100}%`, background: accent, borderRadius: 2 }}/>
            </div>
          </div>
        ))}
      </div>
    );
  }
  return null;
}

function TypingIndicator({ theme, accent }) {
  return (
    <div style={{ display: 'flex', gap: 8, marginBottom: 14 }}>
      <div style={{ width: 26, height: 26, borderRadius: 13, background: `${accent}20`, color: accent, display:'flex', alignItems:'center', justifyContent:'center' }}>
        <Ico.sparkles size={12}/>
      </div>
      <div style={{ padding: '14px 16px', borderRadius: 18, background: theme.surface, border: `0.5px solid ${theme.line}`, display: 'flex', gap: 4 }}>
        {[0,1,2].map(i => (
          <div key={i} style={{
            width: 6, height: 6, borderRadius: 3, background: theme.textDim,
            animation: `himma-dot 1.1s ${i*0.15}s infinite`,
          }}/>
        ))}
        <style>{`@keyframes himma-dot { 0%, 60%, 100% { opacity: 0.25 } 30% { opacity: 1 } }`}</style>
      </div>
    </div>
  );
}

Object.assign(window, { ChatScreen });
