// AI Agent screen — 4 agent tabs, real Claude chat, contextual data
const AIAgentScreen = () => {
  const I = window.Icons;
  const agents = window.MOCK.agents;
  const m = window.MOCK.todayMetrics;
  const [activeAgent, setActiveAgent] = useState('sleep');
  const [messages, setMessages] = useState({});
  const [input, setInput] = useState('');
  const [busy, setBusy] = useState(false);
  const scrollRef = useRef(null);
  const toast = window.useToast();

  const agent = agents.find(a => a.id === activeAgent);
  const msgs = messages[activeAgent] || [{ role: 'agent', text: agent.intro }];

  useEffect(() => {
    if (!messages[activeAgent]) {
      setMessages(prev => ({ ...prev, [activeAgent]: [{ role: 'agent', text: agent.intro }] }));
    }
  }, [activeAgent]);

  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [msgs.length, busy]);

  const send = async (text) => {
    if (!text.trim() || busy) return;
    const cur = messages[activeAgent] || [{ role: 'agent', text: agent.intro }];
    const next = [...cur, { role: 'user', text }];
    setMessages(prev => ({ ...prev, [activeAgent]: next }));
    setInput('');
    setBusy(true);

    const systemContext = {
      sleep: `You are the Sleep Coach for sleepagotchi. Be concise (3-5 short bullet points or 2-3 sentences). User's data: Sleep score 87, total 7h47m, deep 22%, REM 24%, HRV 68ms (slightly below baseline), resting HR 52bpm, sleep efficiency 91%. Last night bedtime was later than usual. Caffeine logged at 4:30PM. Sound supportive and specific.`,
      wellness: `You are the Wellness Agent for sleepagotchi. Aggregate sleep + activity + mood. User: HRV 68ms, stress 42/100, mood 78/100, readiness 82, recovery 76. Suggest supplements (magnesium glycinate is already recommended), wind-down practices (box breathing), and check-ins. Be concise (3-5 bullets max). End with a clear next action.`,
      meal: `You are the Meal Planner for sleepagotchi. The Wellness Agent flagged low Magnesium and low Vitamin D. User wants sleep-supporting nutrition. Suggest specific meals/recipes with brief macros. Be concise (3-5 bullets) and helpful. Mention you can hand off ingredients to the Shopping Agent.`,
      shopping: `You are the Shopping Agent for sleepagotchi. You source ingredients & supplements. Available payment: SLEEP token (5% discount) or linked card. Current cart: salmon, quinoa, spinach, almonds, yogurt, dark chocolate. Be concise (3-5 bullets), give realistic prices, and offer to confirm the order.`,
    };

    try {
      const reply = await window.callClaude({
        agentId: activeAgent,
        system: systemContext[activeAgent] + '\n\nReply directly as the agent. Keep under 100 words. No markdown headers; you can use simple bullets with - or • only.',
        messages: [
          ...next.map(m => ({ role: m.role === 'user' ? 'user' : 'assistant', content: m.text })),
        ],
      });
      setMessages(prev => ({ ...prev, [activeAgent]: [...next, { role: 'agent', text: reply.trim() }] }));
    } catch (e) {
      setMessages(prev => ({ ...prev, [activeAgent]: [...next, { role: 'agent', text: "I'm having trouble reaching my brain right now — try again in a moment." }] }));
    } finally {
      setBusy(false);
    }
  };

  return (
    <div className="col" style={{ gap: 22 }}>
      <Topbar title="Your AI Health & Wellness Agents" subtitle="Personalised intelligence. Better decisions. Better you." />

      <div className="grid" style={{ gridTemplateColumns: '1fr 280px', gap: 16, alignItems: 'start' }}>
        {/* Left: chat */}
        <div className="card" style={{ padding: 0, overflow: 'hidden', display: 'flex', flexDirection: 'column', minHeight: 620 }}>
          {/* Agent switcher */}
          <div style={{ display: 'flex', gap: 4, padding: 14, borderBottom: '1px solid var(--border-soft)', overflowX: 'auto' }}>
            {agents.map(a => (
              <button
                key={a.id}
                onClick={() => setActiveAgent(a.id)}
                className={`tab ${activeAgent === a.id ? 'active' : ''}`}
                style={activeAgent === a.id ? { background: a.color, color: '#1a1330' } : {}}
              >
                <span style={{ marginRight: 6 }}>{a.emoji}</span>{a.name}
              </button>
            ))}
          </div>

          {/* Active agent identity — the Dino IS the Sleep Coach */}
          <div className="agent-id">
            {agent.id === 'sleep'
              ? <div className="agent-id-avatar"><Mascot score={m.sleepScore} size={56} mood="love" hideGlow /></div>
              : <div className="agent-id-avatar" style={{ background: agent.color + '26' }}>{agent.emoji}</div>}
            <div>
              <div className="agent-id-name">{agent.name} <span className="online" /></div>
              <div className="agent-id-tag">{agent.tagline}</div>
            </div>
          </div>

          {/* Messages */}
          <div ref={scrollRef} style={{ flex: 1, padding: '16px 20px', overflowY: 'auto', display: 'flex', flexDirection: 'column', gap: 14, maxHeight: 460 }}>
            {msgs.map((msg, i) => (
              <div key={i} style={{ display: 'flex', gap: 10, justifyContent: msg.role === 'user' ? 'flex-end' : 'flex-start' }}>
                {msg.role === 'agent' && (
                  <div style={{
                    width: 30, height: 30, borderRadius: '50%', flex: '0 0 30px',
                    background: agent.color,
                    display: 'grid', placeItems: 'center', fontSize: 14,
                  }}>{agent.emoji}</div>
                )}
                <div style={{
                  maxWidth: '76%',
                  padding: '11px 14px',
                  borderRadius: msg.role === 'user' ? '14px 14px 4px 14px' : '4px 14px 14px 14px',
                  background: msg.role === 'user' ? 'var(--primary)' : 'var(--surface-2)',
                  color: msg.role === 'user' ? 'white' : 'var(--text)',
                  fontSize: 13.5, lineHeight: 1.55,
                  whiteSpace: 'pre-wrap',
                }}>{msg.text}</div>
              </div>
            ))}
            {busy && (
              <div style={{ display: 'flex', gap: 10 }}>
                <div style={{ width: 30, height: 30, borderRadius: '50%', background: agent.color, display: 'grid', placeItems: 'center' }}>{agent.emoji}</div>
                <div style={{ padding: '12px 14px', borderRadius: '4px 14px 14px 14px', background: 'var(--surface-2)', display: 'flex', gap: 4 }}>
                  {[0, 1, 2].map(i => (
                    <span key={i} style={{
                      width: 6, height: 6, borderRadius: '50%', background: 'var(--text-3)',
                      animation: `pulse 1.2s ease-in-out ${i * 0.2}s infinite`,
                    }}></span>
                  ))}
                </div>
              </div>
            )}
          </div>

          {/* Suggestions */}
          <div style={{ padding: '12px 20px', display: 'flex', flexWrap: 'wrap', gap: 6, borderTop: '1px solid var(--border-soft)' }}>
            {agent.suggestions.map(s => (
              <button key={s} className="btn xs ghost" onClick={() => send(s)} disabled={busy}>{s}</button>
            ))}
          </div>

          {/* Input */}
          <div style={{ padding: 14, borderTop: '1px solid var(--border-soft)' }}>
            <form onSubmit={(e) => { e.preventDefault(); send(input); }} style={{ display: 'flex', gap: 8, alignItems: 'center', background: 'var(--surface-2)', borderRadius: 12, padding: '4px 4px 4px 14px', border: '1px solid var(--border-soft)' }}>
              <input
                value={input}
                onChange={e => setInput(e.target.value)}
                placeholder={`Ask ${agent.name}...`}
                style={{ flex: 1, background: 'transparent', border: 'none', outline: 'none', padding: '10px 0', fontSize: 14 }}
                disabled={busy}
              />
              <button type="submit" className="btn primary sm" disabled={busy || !input.trim()} style={{ borderRadius: 9 }}>
                <I.Send size={13} />
              </button>
            </form>
            <div style={{ fontSize: 11, color: 'var(--text-4)', marginTop: 8, textAlign: 'center' }}>
              AI Agent uses your connected data with permission.
            </div>
          </div>
        </div>

        {/* Right: Health overview */}
        <div className="col" style={{ gap: 16 }}>
          <div className="card">
            <div className="card-head">
              <h3>Health Overview</h3>
              <button className="btn xs ghost">Today <I.ChevronDown size={11} /></button>
            </div>
            <div style={{ display: 'grid', placeItems: 'center', padding: '4px 0 12px' }}>
              <Ring value={m.readiness} size={140} stroke={11} sub="Readiness · Good" />
            </div>
            <div className="col" style={{ gap: 10 }}>
              {[
                { label: 'Sleep', v: 87, c: 'var(--primary)' },
                { label: 'Recovery', v: 76, c: 'var(--accent-cyan)' },
                { label: 'Activity', v: 80, c: 'var(--accent-mint)' },
                { label: 'Stress', v: 42, c: 'var(--accent-amber)' },
                { label: 'Mood', v: 78, c: 'var(--accent-pink)' },
              ].map(r => (
                <div key={r.label} style={{ display: 'grid', gridTemplateColumns: '90px 1fr 30px', gap: 8, alignItems: 'center', fontSize: 13 }}>
                  <span className="muted">{r.label}</span>
                  <ProgressBar value={r.v} color={r.c} />
                  <span className="mono" style={{ textAlign: 'right' }}>{r.v}</span>
                </div>
              ))}
            </div>
          </div>

          <div className="card">
            <h3 style={{ margin: '0 0 12px', fontSize: 14 }}>AI Actions This Week</h3>
            <div className="row" style={{ gap: 10, marginBottom: 8 }}>
              <div style={{ width: 30, height: 30, borderRadius: 8, background: 'rgba(143,227,184,0.15)', display: 'grid', placeItems: 'center', color: 'var(--good)' }}>
                <I.Check size={16}/>
              </div>
              <div className="mono" style={{ fontSize: 26, fontWeight: 600 }}>12</div>
            </div>
            <div className="row" style={{ gap: 4, fontSize: 12, color: 'var(--good)' }}>
              <I.ArrowUp size={11}/> 30% vs last week
            </div>
          </div>

          <div className="card" style={{ background: 'linear-gradient(180deg, rgba(184,169,255,0.10), transparent)' }}>
            <h3 style={{ margin: '0 0 8px', fontSize: 14 }}>Connected Sources</h3>
            <div className="col" style={{ gap: 8 }}>
              <div className="row" style={{ justifyContent: 'space-between', fontSize: 13 }}><span>Oura Ring</span><span className="tag good">Live</span></div>
              <div className="row" style={{ justifyContent: 'space-between', fontSize: 13 }}><span>Apple Health</span><span className="tag good">Live</span></div>
              <div className="row" style={{ justifyContent: 'space-between', fontSize: 13 }}><span>Manual log</span><span className="tag">Daily</span></div>
            </div>
          </div>
        </div>
      </div>

      <style>{`@keyframes pulse { 0%, 100% { opacity: 0.3; transform: scale(0.9); } 50% { opacity: 1; transform: scale(1.1); } }`}</style>
    </div>
  );
};

window.AIAgentScreen = AIAgentScreen;
