/* ===== Growing Now — Agent Chat System (Groq) ===== */
(function () {
  const { useState, useEffect, useRef } = React;
  const Icon = window.Icon;

  const PRIVACY_NOTE = {
    es: 'No compartas contraseñas ni información sensible. La IA puede equivocarse.',
    en: 'Do not share passwords or sensitive information. AI can make mistakes.'
  };

  const GREETINGS = {
    zuki:  { es: 'Hola, soy Zuki 🦊, tu aliada para organizar ideas y convertirlas en acciones.',          en: "Hi, I'm Zuki 🦊, your ally for organizing ideas and turning them into actions." },
    tula:  { es: 'Hola, soy Tula 🐢, estoy aquí para ayudarte a avanzar con calma y claridad.',            en: "Hi, I'm Tula 🐢, I'm here to help you move forward with calm and clarity." },
    piplo: { es: 'Hola, soy Piplo 🐦, observo conversaciones para descubrir oportunidades de crecimiento.', en: "Hi, I'm Piplo 🐦, I observe conversations to discover growth opportunities." },
    nox:   { es: 'Hola, soy Nox 🐺, tu estratega para detectar oportunidades y tomar mejores decisiones.',  en: "Hi, I'm Nox 🐺, your strategist for spotting opportunities and making better decisions." },
    hugo:  { es: 'Hola, soy Hugo 🦉, tu creativo para convertir ideas en mensajes que conectan.',           en: "Hi, I'm Hugo 🦉, your creative for turning ideas into messages that connect." },
    max:   { es: 'Hola, soy Max 🐻, tu aliado para transformar planes en resultados.',                      en: "Hi, I'm Max 🐻, your ally for transforming plans into results." }
  };

  async function callGroq(agentId, messages, lang) {
    const r = await fetch('/api/chat', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        agentId,
        lang,
        messages
      })
    });
    if (!r.ok) throw new Error('API error');
    const d = await r.json();
    return d.text;
  }

  /* ── AgentChatPanel: panel modal para cualquier agente ── */
  function AgentChatPanel({ agent, lang, onClose }) {
    const id = agent.id;
    const greeting = GREETINGS[id]?.[lang] || GREETINGS.zuki[lang];
    const [msgs, setMsgs] = useState([{ role: 'assistant', text: greeting }]);
    const [input, setInput]  = useState('');
    const [busy, setBusy]    = useState(false);
    const bodyRef = useRef(null);

    useEffect(() => {
      setMsgs([{ role: 'assistant', text: GREETINGS[id]?.[lang] || GREETINGS.zuki[lang] }]);
    }, [id, lang]);

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

    async function send(text) {
      const content = (text ?? input).trim();
      if (!content || busy) return;
      const history = [...msgs, { role: 'user', text: content }];
      setMsgs(history); setInput(''); setBusy(true);
      const apiMsgs = history.map(m => ({ role: m.role === 'user' ? 'user' : 'assistant', content: m.text }));
      try {
        const reply = await callGroq(id, apiMsgs, lang);
        setMsgs(m => [...m, { role: 'assistant', text: reply }]);
      } catch {
        setMsgs(m => [...m, { role: 'assistant', text: lang === 'es'
          ? `Ahora mismo no puedo conectar 😅 ¡Agenda una llamada con el botón de arriba!`
          : `Can't connect right now 😅 Book a call with the button above!` }]);
      }
      setBusy(false);
    }

    return (
      <div className="modal-back" onClick={onClose} style={{ zIndex: 85 }}>
        <div onClick={e => e.stopPropagation()} className="glass modal-card"
          style={{ maxWidth: 420, width: '100%', height: 'min(600px,calc(100vh - 80px))', borderRadius: 26,
            display: 'flex', flexDirection: 'column', overflow: 'hidden',
            background: `linear-gradient(180deg,${agent.tint}f0,rgba(255,255,255,.97))` }}>

          {/* Header */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px', borderBottom: '1px solid rgba(0,0,0,.06)' }}>
            <div className="portrait-clip" data-agent={id}
              style={{ width: 46, height: 46, flexShrink: 0, border: `2.5px solid ${agent.accent}`, background: agent.tint }}>
              <img src={agent.portrait} alt={agent.name} />
            </div>
            <div style={{ flex: 1 }}>
              <strong style={{ fontFamily: 'var(--font-display)', fontSize: '1.1rem', color: agent.accent2 }}>{agent.name}</strong>
              <div style={{ fontSize: '.78rem', color: 'var(--ink-soft)' }}>{agent.role[lang]}</div>
            </div>
            <button onClick={onClose} className="glass-soft"
              style={{ border: 'none', width: 36, height: 36, borderRadius: 10, cursor: 'pointer', display: 'grid', placeItems: 'center' }}>
              <Icon name="x" size={18} />
            </button>
          </div>

          {/* Messages */}
          <div ref={bodyRef} className="scroll-thin"
            style={{ flex: 1, overflowY: 'auto', padding: 16, display: 'flex', flexDirection: 'column', gap: 12 }}>
            {msgs.map((m, i) => (
              <div key={i} style={{ display: 'flex', justifyContent: m.role === 'user' ? 'flex-end' : 'flex-start' }}>
                <div style={{ maxWidth: '82%', padding: '10px 14px', borderRadius: 16, lineHeight: 1.55, fontSize: '.95rem',
                  ...(m.role === 'user'
                    ? { background: `linear-gradient(135deg,${agent.accent},${agent.accent2})`, color: '#fff', borderBottomRightRadius: 4 }
                    : { background: '#fff', color: 'var(--ink)', borderBottomLeftRadius: 4, boxShadow: '0 4px 14px -8px rgba(0,0,0,.25)' }) }}>
                  {m.text}
                </div>
              </div>
            ))}
            {busy && (
              <div style={{ display: 'flex', gap: 4, padding: '8px 14px', alignSelf: 'flex-start', background: '#fff', borderRadius: 16, boxShadow: '0 4px 14px -8px rgba(0,0,0,.25)' }}>
                {[0,1,2].map(i => <span key={i} className="typing-dot" style={{ animationDelay: i * 0.15 + 's', background: agent.accent }} />)}
              </div>
            )}
          </div>

          {/* Cal.com */}
          <a href={window.GN.bookingUrl(id, lang, 'agent_chat')} target="_blank" rel="noopener"
            style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
              margin: '0 16px 8px', padding: '10px', borderRadius: 12, textDecoration: 'none',
              fontWeight: 700, fontFamily: 'var(--font-display)', fontSize: '.9rem',
              color: agent.accent2, background: `${agent.accent}18` }}>
            <Icon name="calendar" size={16} color={agent.accent2} />
            {lang === 'es' ? `Agendar llamada con ${agent.name}` : `Book a call with ${agent.name}`}
          </a>

          {/* Input */}
          <div style={{ display: 'flex', gap: 8, padding: '12px 14px', borderTop: '1px solid rgba(0,0,0,.06)' }}>
            <input value={input} onChange={e => setInput(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && send()}
              placeholder={lang === 'es' ? `Escríbele a ${agent.name}…` : `Message ${agent.name}…`}
              style={{ flex: 1, border: 'none', outline: 'none', background: 'rgba(0,0,0,.04)', borderRadius: 99, padding: '11px 16px', fontFamily: 'var(--font-body)', fontSize: '.95rem' }} />
            <button onClick={() => send()} disabled={busy || !input.trim()}
              style={{ border: 'none', cursor: 'pointer', width: 42, height: 42, borderRadius: 99, display: 'grid', placeItems: 'center',
                color: '#fff', background: `linear-gradient(135deg,${agent.accent},${agent.accent2})`,
                opacity: busy || !input.trim() ? .45 : 1, transition: 'opacity .2s' }}>
              <Icon name="send" size={18} color="#fff" />
            </button>
          </div>
          <div style={{ padding: '0 16px 10px', fontSize: '.68rem', lineHeight: 1.3, textAlign: 'center', color: 'var(--ink-soft)' }}>
            {PRIVACY_NOTE[lang]}
          </div>
        </div>
      </div>
    );
  }

  /* ── ZukiLauncher: botón flotante + panel de Zuki ── */
  function ZukiLauncher({ lang, openSignal }) {
    const L = window.I18N.STR[lang];
    const zuki = window.GN.byId.zuki;
    const [open, setOpen] = useState(false);
    const [msgs, setMsgs] = useState([{ role: 'assistant', text: GREETINGS.zuki[lang] }]);
    const [input, setInput] = useState('');
    const [busy, setBusy]   = useState(false);
    const bodyRef = useRef(null);

    useEffect(() => { setMsgs([{ role: 'assistant', text: GREETINGS.zuki[lang] }]); }, [lang]);
    useEffect(() => { if (openSignal) setOpen(true); }, [openSignal]);
    useEffect(() => { if (bodyRef.current) bodyRef.current.scrollTop = bodyRef.current.scrollHeight; }, [msgs, busy, open]);

    async function send(text) {
      const content = (text ?? input).trim();
      if (!content || busy) return;
      const history = [...msgs, { role: 'user', text: content }];
      setMsgs(history); setInput(''); setBusy(true);
      const apiMsgs = history.map(m => ({ role: m.role === 'user' ? 'user' : 'assistant', content: m.text }));
      try {
        const reply = await callGroq('zuki', apiMsgs, lang);
        setMsgs(m => [...m, { role: 'assistant', text: reply }]);
      } catch {
        setMsgs(m => [...m, { role: 'assistant', text: lang === 'es'
          ? 'Ahora mismo no puedo conectar 😅. ¡Agenda una llamada con el botón de arriba!'
          : "Can't reach my brain right now 😅. Book a call with the button above!" }]);
      }
      setBusy(false);
    }

    return (
      <>
        {/* Launcher button */}
        <button onClick={() => setOpen(o => !o)} aria-label="Zuki"
          style={{ position: 'fixed', right: 22, bottom: 22, zIndex: 90, width: 68, height: 68,
            borderRadius: 99, border: 'none', cursor: 'pointer', padding: 0, background: 'none' }}>
          <span className={open ? '' : 'floaty'}
            style={{ position: 'absolute', inset: -6, borderRadius: 99, background: `radial-gradient(circle,${zuki.accent}88,transparent 70%)`, filter: 'blur(8px)' }} />
          <div className="portrait-clip" data-agent="zuki"
            style={{ position: 'absolute', inset: 0, border: `3px solid ${zuki.accent}`, background: zuki.tint, boxShadow: '0 12px 28px -10px rgba(0,0,0,.5)' }}>
            <img src={zuki.portrait} alt="Zuki" />
          </div>
          {!open && <span style={{ position: 'absolute', top: -2, right: -2, width: 18, height: 18, borderRadius: 99, background: 'var(--green)', border: '2px solid #fff' }} />}
        </button>

        {/* Zuki panel */}
        {open && (
          <div className="glass zuki-panel"
            style={{ position: 'fixed', right: 22, bottom: 100, zIndex: 90,
              width: 'min(380px,calc(100vw - 32px))', height: 'min(560px,calc(100vh - 140px))',
              borderRadius: 26, display: 'flex', flexDirection: 'column', overflow: 'hidden',
              background: 'linear-gradient(180deg,rgba(254,241,222,.92),rgba(255,255,255,.95))' }}>

            {/* Header */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px', borderBottom: '1px solid rgba(0,0,0,.06)' }}>
              <div style={{ position: 'relative', width: 44, height: 44 }}>
                <div className="portrait-clip" data-agent="zuki"
                  style={{ position: 'absolute', inset: 0, border: `2px solid ${zuki.accent}`, background: zuki.tint }}>
                  <img src={zuki.portrait} alt="Zuki" />
                </div>
                <span style={{ position: 'absolute', bottom: 0, right: 0, width: 12, height: 12, borderRadius: 99, background: 'var(--green)', border: '2px solid #fff' }} />
              </div>
              <div style={{ flex: 1 }}>
                <strong style={{ fontFamily: 'var(--font-display)', fontSize: '1.1rem' }}>{L.chat_title}</strong>
                <div style={{ fontSize: '.78rem', color: 'var(--ink-soft)' }}>{L.chat_role}</div>
              </div>
              <button onClick={() => setOpen(false)} className="glass-soft"
                style={{ border: 'none', width: 36, height: 36, borderRadius: 10, cursor: 'pointer', display: 'grid', placeItems: 'center' }}>
                <Icon name="x" size={18} />
              </button>
            </div>

            {/* Messages */}
            <div ref={bodyRef} className="scroll-thin"
              style={{ flex: 1, overflowY: 'auto', padding: 16, display: 'flex', flexDirection: 'column', gap: 12 }}>
              {msgs.map((m, i) => (
                <div key={i} style={{ display: 'flex', justifyContent: m.role === 'user' ? 'flex-end' : 'flex-start' }}>
                  <div style={{ maxWidth: '82%', padding: '10px 14px', borderRadius: 16, lineHeight: 1.55, fontSize: '.95rem',
                    ...(m.role === 'user'
                      ? { background: 'linear-gradient(135deg,var(--blue),var(--blue-l))', color: '#fff', borderBottomRightRadius: 4 }
                      : { background: '#fff', color: 'var(--ink)', borderBottomLeftRadius: 4, boxShadow: '0 4px 14px -8px rgba(0,0,0,.3)' }) }}>
                    {m.text}
                  </div>
                </div>
              ))}
              {busy && (
                <div style={{ display: 'flex', gap: 4, padding: '8px 14px', alignSelf: 'flex-start', background: '#fff', borderRadius: 16, boxShadow: '0 4px 14px -8px rgba(0,0,0,.3)' }}>
                  {[0,1,2].map(i => <span key={i} className="typing-dot" style={{ animationDelay: i * 0.15 + 's' }} />)}
                </div>
              )}
            </div>

            {/* Cal.com */}
            <a href={window.GN.bookingUrl('zuki', lang, 'launcher')} target="_blank" rel="noopener"
              style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                margin: '0 16px 8px', padding: '10px', borderRadius: 12, textDecoration: 'none',
                fontWeight: 700, fontFamily: 'var(--font-display)', color: 'var(--green-d)',
                background: 'rgba(63,174,74,.12)', fontSize: '.9rem' }}>
              <Icon name="calendar" size={16} color="var(--green-d)" /> {L.chat_book}
            </a>

            {/* Input */}
            <div style={{ display: 'flex', gap: 8, padding: '12px 14px', borderTop: '1px solid rgba(0,0,0,.06)' }}>
              <input value={input} onChange={e => setInput(e.target.value)}
                onKeyDown={e => e.key === 'Enter' && send()}
                placeholder={L.chat_ph}
                style={{ flex: 1, border: 'none', outline: 'none', background: 'rgba(0,0,0,.04)', borderRadius: 99, padding: '11px 16px', fontFamily: 'var(--font-body)', fontSize: '.95rem' }} />
              <button onClick={() => send()} disabled={busy || !input.trim()}
                style={{ border: 'none', cursor: 'pointer', width: 42, height: 42, borderRadius: 99, display: 'grid', placeItems: 'center',
                  color: '#fff', background: 'linear-gradient(135deg,var(--orange),var(--orange-d))',
                  opacity: busy || !input.trim() ? .45 : 1 }}>
                <Icon name="send" size={18} color="#fff" />
              </button>
            </div>
            <div style={{ padding: '0 16px 10px', fontSize: '.68rem', lineHeight: 1.3, textAlign: 'center', color: 'var(--ink-soft)' }}>
              {PRIVACY_NOTE[lang]}
            </div>
          </div>
        )}
      </>
    );
  }

  window.AgentChatPanel = AgentChatPanel;
  window.ZukiLauncher   = ZukiLauncher;
})();
