// Live AI Lab (DeepSeek) + FAQ + Contact (with form) + Footer

// === CONFIG ===
// DeepSeek proxy endpoint. The Node server (server.js) handles `/api/chat`
// and forwards to DeepSeek with the secret API key.
const DEEPSEEK_ENDPOINT = window.__DEEPSEEK_ENDPOINT || '/api/chat';
// Optional contact form endpoint (Formspree, Getform, or `/api/contact`).
// If empty, the form falls back to mailto.
const CONTACT_ENDPOINT = window.__CONTACT_ENDPOINT || '';

// Number of USER messages after which we gracefully invite the conversation
// to continue on WhatsApp. The chat is showcase, not closing channel.
const HANDOFF_AFTER = 4;

async function callDeepseek(messages, lang) {
  const r = await fetch(DEEPSEEK_ENDPOINT, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ messages, lang })
  });
  if (!r.ok) {
    const err = await r.text().catch(() => '');
    throw new Error('endpoint ' + r.status + ' ' + err);
  }
  const data = await r.json();
  // server.js normalizes to { reply: "..." }, but accept raw OpenAI-shape too.
  return data.reply
      || data.choices?.[0]?.message?.content
      || (lang === 'pt'
          ? 'Não consegui responder agora. Tenta de novo em alguns segundos.'
          : 'I could not reply just now. Try again in a few seconds.');
}

function WhatsAppHandoff({ t, lang, history }) {
  // Build a deep-link with a pre-filled message summarising the chat
  const lastUser = [...history].reverse().find(m => m.role === 'user');
  const seed = lastUser ? lastUser.content : '';
  const intro = lang === 'pt'
    ? 'Oi! Acabei de conversar com a IA no site da Cerne e queria continuar por aqui.'
    : 'Hi! I just chatted with the AI on the Cerne site and would like to continue here.';
  const seedLabel = lang === 'pt' ? 'Última pergunta' : 'Last question';
  const text = encodeURIComponent(seed ? `${intro}\n\n${seedLabel}: ${seed}` : intro);
  const href = `https://wa.me/${t.contact.whatsapp}?text=${text}`;
  return (
    <div className="msg msg-handoff">
      <div className="msg-role mono">CERNE</div>
      <div className="handoff-card">
        <div className="handoff-title serif">{t.lab.handoffTitle}</div>
        <div className="handoff-body">{t.lab.handoffBody}</div>
        <a href={href} target="_blank" rel="noopener noreferrer" className="btn primary handoff-btn" data-cursor>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="currentColor" aria-hidden="true">
            <path d="M.057 24l1.687-6.163c-1.041-1.804-1.588-3.849-1.587-5.946.003-6.556 5.338-11.891 11.893-11.891 3.181.001 6.167 1.24 8.413 3.488 2.245 2.248 3.481 5.236 3.48 8.414-.003 6.557-5.338 11.892-11.893 11.892-1.99-.001-3.951-.5-5.688-1.448l-6.305 1.654zm6.597-3.807c1.676.995 3.276 1.591 5.392 1.592 5.448 0 9.886-4.434 9.889-9.885.002-5.462-4.415-9.89-9.881-9.892-5.452 0-9.887 4.434-9.889 9.884-.001 2.225.651 3.891 1.746 5.634l-.999 3.648 3.742-.981zm11.387-5.464c-.074-.124-.272-.198-.57-.347-.297-.149-1.758-.868-2.031-.967-.272-.099-.47-.149-.669.149-.198.297-.768.967-.941 1.165-.173.198-.347.223-.644.074-.297-.149-1.255-.462-2.39-1.475-.883-.788-1.48-1.761-1.653-2.059-.173-.297-.018-.458.13-.606.134-.133.297-.347.446-.521.151-.172.2-.296.3-.495.099-.198.05-.372-.025-.521-.075-.148-.669-1.611-.916-2.206-.242-.579-.487-.501-.669-.51l-.57-.01c-.198 0-.52.074-.792.372s-1.04 1.016-1.04 2.479 1.065 2.876 1.213 3.074c.149.198 2.095 3.2 5.076 4.487.709.306 1.263.489 1.694.626.712.226 1.36.194 1.872.118.571-.085 1.758-.719 2.006-1.413.247-.694.247-1.289.173-1.413z"/>
          </svg>
          {t.lab.handoffCta}
        </a>
      </div>
    </div>
  );
}

function Lab({ t, lang }) {
  const [messages, setMessages] = React.useState([{ role: 'assistant', content: t.lab.welcome }]);
  const [input, setInput] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState(null);
  const scrollRef = React.useRef(null);

  React.useEffect(() => {
    setMessages([{ role: 'assistant', content: t.lab.welcome }]);
    setError(null);
  }, [lang]);
  React.useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages, loading]);

  const userMsgCount = messages.filter(m => m.role === 'user').length;
  const showHandoff = userMsgCount >= HANDOFF_AFTER;

  const send = async (text) => {
    const q = (text ?? input).trim();
    if (!q || loading) return;
    setInput('');
    setError(null);
    const history = [...messages, { role: 'user', content: q }];
    setMessages(history);
    setLoading(true);
    try {
      const reply = await callDeepseek(
        history.map(m => ({ role: m.role, content: m.content })),
        lang
      );
      setMessages([...history, { role: 'assistant', content: reply }]);
    } catch (e) {
      setError(lang === 'pt'
        ? 'Tive um problema para responder. O backend de IA pode estar fora do ar — tente de novo ou fale com a gente direto no WhatsApp.'
        : 'I hit a snag. The AI backend might be offline — try again or reach us on WhatsApp.');
      setMessages(history); // keep history clean; show error inline
    } finally { setLoading(false); }
  };

  return (
    <section id="lab" className="lab">
      <div className="container">
        <div className="section-head reveal">
          <span className="eyebrow">{t.lab.eyebrow}</span>
          <h2 className="section-title serif">{t.lab.title}</h2>
          <p className="section-sub">{t.lab.sub}</p>
        </div>
        <div className="lab-shell reveal">
          <div className="lab-window">
            <div className="lab-topbar mono">
              <span className="lab-dot" />
              <span>cerne.agent · live</span>
              <span className="lab-tag">deepseek-chat</span>
            </div>
            <div ref={scrollRef} className="lab-log">
              {messages.map((m, i) => (
                <div key={i} className={`msg msg-${m.role}`}>
                  <div className="msg-role mono">{m.role === 'user' ? (lang === 'pt' ? 'VOCÊ' : 'YOU') : 'CERNE'}</div>
                  <div className="msg-body">{m.content}</div>
                </div>
              ))}
              {loading && (
                <div className="msg msg-assistant">
                  <div className="msg-role mono">CERNE</div>
                  <div className="msg-body typing"><span/><span/><span/></div>
                </div>
              )}
              {error && (
                <div className="msg msg-error">
                  <div className="msg-role mono">!</div>
                  <div className="msg-body">{error}</div>
                </div>
              )}
              {showHandoff && !loading && (
                <WhatsAppHandoff t={t} lang={lang} history={messages} />
              )}
            </div>
            <div className="lab-seeds">
              {t.lab.seed.map((s, i) => (
                <button key={i} className="seed mono" onClick={() => send(s)} disabled={loading} data-cursor>{s}</button>
              ))}
            </div>
            <form className="lab-input" onSubmit={(e) => { e.preventDefault(); send(); }}>
              <span className="prompt mono" aria-hidden="true">&gt;</span>
              <input
                value={input}
                onChange={(e) => setInput(e.target.value)}
                placeholder={t.lab.placeholder}
                disabled={loading}
                aria-label={t.lab.placeholder}
                data-cursor
              />
              <button type="submit" className="btn primary" disabled={loading || !input.trim()} data-cursor>
                {t.lab.send} <span className="arrow">↵</span>
              </button>
            </form>
          </div>
        </div>
      </div>
    </section>
  );
}

function Faq({ t }) {
  const [open, setOpen] = React.useState(0);
  return (
    <section id="faq" className="faq">
      <div className="container">
        <div className="section-head reveal">
          <span className="eyebrow">{t.faq.eyebrow}</span>
          <h2 className="section-title serif">{t.faq.title}</h2>
        </div>
        <div className="faq-list reveal">
          {t.faq.items.map((it, i) => (
            <div key={i} className={`faq-item ${open === i ? 'open' : ''}`} onClick={() => setOpen(open === i ? -1 : i)} data-cursor>
              <div className="faq-q">
                <span className="faq-n mono">{String(i + 1).padStart(2, '0')}</span>
                <span className="faq-qt">{it.q}</span>
                <span className="faq-toggle" aria-hidden="true">{open === i ? '−' : '+'}</span>
              </div>
              <div className="faq-a"><div>{it.a}</div></div>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

function ContactForm({ t, lang }) {
  const [state, setState] = React.useState('idle'); // idle | sending | ok | err
  const [form, setForm] = React.useState({ name: '', email: '', company: '', message: '' });
  const L = lang === 'pt' ? {
    name: 'Nome', email: 'Email', company: 'Empresa', msg: 'Conte sobre o projeto',
    send: 'Enviar mensagem', sending: 'Enviando…',
    ok: 'Recebemos — respondemos em até 24 horas.',
    err: 'Algo deu errado. Tenta pelo WhatsApp ou email?'
  } : {
    name: 'Name', email: 'Email', company: 'Company', msg: 'Tell us about the project',
    send: 'Send message', sending: 'Sending…',
    ok: 'Got it — we\'ll reply within 24 hours.',
    err: 'Something went wrong. Try WhatsApp or email instead?'
  };

  const submit = async (e) => {
    e.preventDefault();
    if (!form.name || !form.email || !form.message) return;
    setState('sending');
    try {
      if (!CONTACT_ENDPOINT) {
        const body = `${form.name} <${form.email}> — ${form.company}\n\n${form.message}`;
        window.location.href = `mailto:${t.contact.email}?subject=${encodeURIComponent('[Site] ' + form.name)}&body=${encodeURIComponent(body)}`;
        setState('ok');
        return;
      }
      const r = await fetch(CONTACT_ENDPOINT, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
        body: JSON.stringify(form)
      });
      if (!r.ok) throw new Error('send fail');
      setState('ok');
      setForm({ name: '', email: '', company: '', message: '' });
    } catch (e) {
      setState('err');
    }
  };

  return (
    <form className="contact-form" onSubmit={submit}>
      <div className="cf-row">
        <label>
          <span className="mono">{L.name}</span>
          <input required value={form.name} onChange={e => setForm({...form, name: e.target.value})} data-cursor autoComplete="name" />
        </label>
        <label>
          <span className="mono">{L.email}</span>
          <input type="email" required value={form.email} onChange={e => setForm({...form, email: e.target.value})} data-cursor autoComplete="email" />
        </label>
      </div>
      <label>
        <span className="mono">{L.company}</span>
        <input value={form.company} onChange={e => setForm({...form, company: e.target.value})} data-cursor autoComplete="organization" />
      </label>
      <label>
        <span className="mono">{L.msg}</span>
        <textarea required rows={4} value={form.message} onChange={e => setForm({...form, message: e.target.value})} data-cursor />
      </label>
      <div className="cf-foot">
        <button type="submit" className="btn primary big" disabled={state === 'sending'} data-cursor>
          {state === 'sending' ? L.sending : L.send} <span className="arrow">→</span>
        </button>
        {state === 'ok' && <span className="cf-ok mono">✓ {L.ok}</span>}
        {state === 'err' && <span className="cf-err mono">✗ {L.err}</span>}
      </div>
    </form>
  );
}

function Contact({ t, lang }) {
  const waText = encodeURIComponent(lang === 'pt'
    ? 'Oi! Cheguei pelo site da Cerne. Quero conversar sobre um projeto.'
    : 'Hi! I came from the Cerne site. I\'d like to talk about a project.');
  const waHref = `https://wa.me/${t.contact.whatsapp}?text=${waText}`;
  return (
    <section id="contact" className="contact">
      <div className="container">
        <div className="contact-inner reveal">
          <span className="eyebrow">{t.contact.eyebrow}</span>
          <h2 className="contact-title serif">
            {t.contact.title.map((l, i) => (
              <span key={i} className={`line ${i === 1 ? 'accent' : ''}`}>{l}</span>
            ))}
          </h2>
          <p className="contact-sub">{t.contact.sub}</p>
          <div className="contact-layout">
            <div className="contact-links">
              <a href={`mailto:${t.contact.email}`} className="contact-link" data-cursor>
                <span className="mono">EMAIL</span>
                <span className="serif">{t.contact.email}</span>
              </a>
              <a href={waHref} target="_blank" rel="noopener noreferrer" className="contact-link" data-cursor>
                <span className="mono">{t.contact.whatsappLabel}</span>
                <span className="serif">{t.contact.phone}</span>
              </a>
            </div>
            <ContactForm t={t} lang={lang} />
          </div>
        </div>
      </div>
    </section>
  );
}

function Footer({ t }) {
  return (
    <footer className="footer">
      <div className="container footer-inner">
        <div className="footer-brand">
          <div className="serif footer-mark">Cerne<span className="accent">.</span>AI</div>
          <div className="mono footer-tag">{t.footer.tag}</div>
        </div>
        <div className="footer-meta mono">
          <span>{t.footer.made}</span>
          <span>{t.footer.rights}</span>
        </div>
      </div>
    </footer>
  );
}

window.Lab = Lab;
window.Faq = Faq;
window.Contact = Contact;
window.Footer = Footer;
