/* global React */
function AgentPage({ go, onBuy }) {
  const [messages, setMessages] = React.useState([
  { role: 'bot', text: "Welcome 👋 I'm the EFF AI Agent — I know every EA in the catalog, can tune parameters to your account, and answer setup questions. Bilingual (Arabic / English).\n\nأهلاً! اسألني أي شيء عن الإكسبرتات، حجم اللوت، أو إعداد MT5." }]
  );
  const [input, setInput] = React.useState('');
  const [typing, setTyping] = React.useState(false);
  const [error, setError] = React.useState('');
  const chatRef = React.useRef(null);

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

  const quickPrompts = [
  "I have a $5k account, low risk. Recommend an EA.",
  "What lot size should I use for $10k @ 2% risk?",
  "أفضل إكسبرت للذهب؟",
  "Compare APEX vs QUANTUM for FTMO"];


  async function sendMessage(text) {
    const msg = text.trim();
    if (!msg || typing) return;
    setError('');
    const userMsg = { role: 'user', text: msg };
    setMessages((m) => [...m, userMsg]);
    setInput('');
    setTyping(true);

    // Build conversation history for Groq (last 10 turns)
    const history = messages.slice(-10).map((m) => ({
      role: m.role === 'bot' ? 'assistant' : 'user',
      content: m.text || (typeof m.content === 'string' ? m.content : '')
    })).filter((m) => m.content);

    try {
      const reply = await window.AI.chat([{ role: 'user', content: msg }], history);
      setMessages((m) => [...m, { role: 'bot', text: reply }]);
    } catch (e) {
      setError(e.message || 'AI service error. Try again.');
      setMessages((m) => [...m, { role: 'bot', text: '⚠ ' + (e.message || 'Sorry, the AI service is temporarily unavailable. Please try again in a moment.') }]);
    } finally {
      setTyping(false);
    }
  }

  function renderText(text) {
    // Convert **bold** to <strong> and line breaks to <br>
    const parts = text.split(/(\*\*[^*]+\*\*)/g);
    return parts.map((p, i) => {
      if (p.startsWith('**') && p.endsWith('**')) {
        return <strong key={i} style={{ color: 'var(--cyan)' }}>{p.slice(2, -2)}</strong>;
      }
      return <span key={i}>{p.split('\n').map((line, j, arr) =>
        <React.Fragment key={j}>{line}{j < arr.length - 1 && <br />}</React.Fragment>
        )}</span>;
    });
  }

  return (
    <div>
      <section style={{ padding: '32px 0' }}>
        <div className="container">
          <div className="grid" style={{ gridTemplateColumns: '1fr 320px', gap: 24, minHeight: 'calc(100vh - 200px)' }}>
            {/* Chat */}
            <div className="panel panel-glow" style={{ display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
              <div style={{ padding: '20px 24px', borderBottom: '1px solid var(--line)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <div className="flex gap-3" style={{ alignItems: 'center' }}>
                  <div style={{ width: 40, height: 40, borderRadius: '50%', background: 'var(--grad-1)', display: 'grid', placeItems: 'center', color: '#000', fontWeight: 800, fontFamily: 'var(--font-mono)', boxShadow: '0 0 16px rgba(0,229,255,0.4)' }}>EFF</div>
                  <div>
                    <div style={{ fontWeight: 600 }}>EFF AI Agent</div>
                    <div className="text-xs font-mono text-cyan"><span className="dot dot-pulse" /> Powered by Groq · Llama 3.3</div>
                  </div>
                </div>
                <div className="flex gap-2">
                  <span className="tag">EN</span>
                  <span className="tag tag-magenta">العربية</span>
                </div>
              </div>

              <div ref={chatRef} style={{ flex: 1, padding: 24, overflowY: 'auto', minHeight: 400, maxHeight: 'calc(100vh - 320px)' }}>
                {messages.map((m, i) =>
                <div key={i} className="chat-msg">
                    <div className={`chat-avatar ${m.role}`}>{m.role === 'bot' ? 'EFF' : 'U'}</div>
                    <div className={`chat-bubble ${m.role}`}>
                      {renderText(m.text || '')}
                    </div>
                  </div>
                )}
                {typing &&
                <div className="chat-msg">
                    <div className="chat-avatar bot">EFF</div>
                    <div className="chat-bubble bot"><div className="typing"><span /><span /><span /></div></div>
                  </div>
                }
              </div>

              {messages.length === 1 &&
              <div style={{ padding: '0 24px 16px' }}>
                  <div className="text-xs text-muted font-mono mb-3">SUGGESTED PROMPTS</div>
                  <div className="flex gap-2" style={{ flexWrap: 'wrap' }}>
                    {quickPrompts.map((p, i) =>
                  <button key={i} className="btn btn-ghost btn-sm" style={{ fontSize: 11, padding: '8px 12px', textTransform: 'none', letterSpacing: 'normal' }} onClick={() => sendMessage(p)}>{p}</button>
                  )}
                  </div>
                </div>
              }

              <div style={{ padding: 16, borderTop: '1px solid var(--line)' }}>
                <form className="flex gap-2" onSubmit={(e) => {e.preventDefault();sendMessage(input);}}>
                  <input className="input" placeholder="// Ask anything · اسألني أي شيء" value={input} onChange={(e) => setInput(e.target.value)} style={{ flex: 1 }} disabled={typing} />
                  <button className="btn btn-primary btn-sheen" type="submit" disabled={typing || !input.trim()}>Send →</button>
                </form>
                <div className="text-xs text-muted mt-3 font-mono">
                  Powered by Groq · Llama 3.3 70B · trained on the EFF catalog
                </div>
              </div>
            </div>

            {/* Side panel — agent capabilities */}
            <div className="flex-col gap-4">
              <div className="panel panel-padded">
                <span className="eyebrow">CAPABILITIES</span>
                <div className="mt-4 flex-col gap-3">
                  {[
                  { i: '◈', t: 'EA Recommendation', d: 'Matches your profile to systems' },
                  { i: '◆', t: 'Parameter Tuning', d: 'Lot size, SL, TP for your account' },
                  { i: '◇', t: 'EA Comparison', d: 'Side-by-side specs and stats' },
                  { i: '◉', t: 'Risk Recommendations', d: 'Correlation, exposure, DD limits' },
                  { i: '○', t: 'Bilingual', d: 'العربية + English' }].
                  map((c) =>
                  <div key={c.t} className="flex gap-3" style={{ alignItems: 'flex-start' }}>
                      <div style={{ color: 'var(--cyan)', fontSize: 18 }}>{c.i}</div>
                      <div style={{ flex: 1 }}>
                        <div className="text-sm" style={{ fontWeight: 600 }}>{c.t}</div>
                        <div className="text-xs text-muted mt-1">{c.d}</div>
                      </div>
                    </div>
                  )}
                </div>
              </div>

              <div className="panel panel-padded">
                <span className="eyebrow">LIBRARY</span>
                <div className="grid grid-2 mt-4" style={{ gap: 8 }}>
                  <div><div className="stat-label" style={{ fontSize: 9 }}>EAs</div><div className="font-mono text-cyan">{window.EA_LIST?.length || 10}</div></div>
                  <div><div className="stat-label" style={{ fontSize: 9 }}>Model</div><div className="font-mono text-green">Llama 3.3</div></div>
                  <div><div className="stat-label" style={{ fontSize: 9 }}>Latency</div><div className="font-mono text-amber">~1s</div></div>
                  <div><div className="stat-label" style={{ fontSize: 9 }}>Lang</div><div className="font-mono">AR/EN</div></div>
                </div>
              </div>

              <div className="panel panel-padded" style={{ background: 'rgba(255,45,170,0.04)', borderColor: 'rgba(255,45,170,0.25)' }}>
                <span className="eyebrow" style={{ color: 'var(--magenta)' }}>PRIVACY</span>
                <p className="mt-3 text-sm" style={{ color: 'var(--text-2)' }}>Chats are not stored. Each conversation starts fresh. Your messages go through our proxy to Groq.

                </p>
              </div>
            </div>
          </div>
        </div>
      </section>
    </div>);

}

window.AgentPage = AgentPage;