/* ===== Growing Now — Typeform-style contact flow (hosted by Zuki) ===== */
(function () {
  const { useState, useEffect, useRef } = React;
  const Icon = window.Icon;

  window.gcalLink = function (lang = 'es') {
    return window.GN.bookingUrl('zuki', lang, 'lead_form');
  };

  window.saveLead = async function (lead) {
    const response = await fetch('/api/submit-lead', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(lead)
    });
    if (!response.ok) throw new Error('Lead submission failed');
    const data = await response.json();
    if (!data.ok) throw new Error('Lead submission was not confirmed');
    return data;
  };

  const TIER = {
    hot: { es: 'Cliente ideal', en: 'Ideal client', c: '#2E8C3A' },
    warm: { es: 'Buen potencial', en: 'Good potential', c: '#F7941E' },
    cold: { es: 'Por explorar', en: 'To explore', c: '#2E8BD6' },
  };

  function Gauge({ value, color, label }) {
    const r = 54, c = 2 * Math.PI * r, off = c * (1 - value / 100);
    return (
      <div style={{ position: 'relative', width: 140, height: 140 }}>
        <svg width="140" height="140" style={{ transform: 'rotate(-90deg)' }}>
          <circle cx="70" cy="70" r={r} fill="none" stroke="rgba(0,0,0,.08)" strokeWidth="12" />
          <circle cx="70" cy="70" r={r} fill="none" stroke={color} strokeWidth="12" strokeLinecap="round" strokeDasharray={c} strokeDashoffset={off} style={{ transition: 'stroke-dashoffset 1.2s cubic-bezier(.2,.8,.2,1)' }} />
        </svg>
        <div style={{ position: 'absolute', inset: 0, display: 'grid', placeItems: 'center', textAlign: 'center' }}>
          <div>
            <div style={{ fontFamily: 'var(--font-display)', fontWeight: 700, fontSize: '2.2rem', color }}>{value}</div>
            <div style={{ fontSize: '.7rem', color: 'var(--ink-soft)' }}>{label}</div>
          </div>
        </div>
      </div>
    );
  }

  function ContactModal({ lang, onClose, onChat }) {
    const L = window.I18N.STR[lang];
    const Q = window.GN.questions;
    const zuki = window.GN.byId.zuki;
    const [idx, setIdx] = useState(-1);     // -1 intro, n = done
    const [ans, setAns] = useState({});
    const [err, setErr] = useState('');
    const [result, setResult] = useState(null);
    const [submitting, setSubmitting] = useState(false);
    const inputRef = useRef(null);

    useEffect(() => { document.body.classList.add('no-scroll'); return () => document.body.classList.remove('no-scroll'); }, []);
    useEffect(() => { setErr(''); if (inputRef.current) setTimeout(() => inputRef.current.focus(), 120); }, [idx]);

    const total = Q.length;
    const q = idx >= 0 && idx < total ? Q[idx] : null;

    function next() {
      if (q) {
        if (q.required && !ans[q.id]) { setErr(L.form_required); return; }
        if (q.type === 'email' && ans.email && !/^\S+@\S+\.\S+$/.test(ans.email)) { setErr(L.form_required); return; }
      }
      if (idx === total - 1) return submit();
      setIdx(idx + 1);
    }
    function back() { if (idx > -1) setIdx(idx - 1); }
    async function submit() {
      if (submitting) return;
      const sc = window.GN.score(ans);
      const lead = { id: 'L' + Date.now().toString(36), ts: Date.now(), agent_id: 'zuki', source: 'lead_form', answers: ans, score: sc, status: 'new', lang };
      setSubmitting(true);
      setErr('');
      try {
        await window.saveLead(lead);
        setResult({ lead, sc });
        setIdx(total);
      } catch (error) {
        setErr(L.form_submit_error);
      } finally {
        setSubmitting(false);
      }
    }
    const setVal = (v) => setAns(a => ({ ...a, [q.id]: v }));
    const toggle = (v) => setAns(a => { const cur = a[q.id] || []; return { ...a, [q.id]: cur.includes(v) ? cur.filter(x => x !== v) : [...cur, v] }; });
    const chooseSingle = (v) => {
      setAns(a => ({ ...a, [q.id]: v }));
      setErr('');
      setTimeout(() => setIdx(current => current + 1), 220);
    };

    const progress = idx < 0 ? 0 : idx >= total ? 100 : Math.round((idx / total) * 100);

    return (
      <div className="modal-back" style={{ background: 'rgba(30,28,24,.6)' }}>
        <div className="modal-card glass" style={{ maxWidth: 720, width: '100%', minHeight: 520, maxHeight: '92vh', borderRadius: 32, padding: 0, overflow: 'hidden', display: 'flex', flexDirection: 'column', background: `linear-gradient(165deg, rgba(254,241,222,.92), rgba(255,255,255,.85))` }}>
          {/* progress */}
          <div style={{ height: 6, background: 'rgba(0,0,0,.06)', flex: '0 0 auto' }}>
            <div style={{ height: '100%', width: progress + '%', background: 'linear-gradient(90deg,var(--orange),var(--green))', transition: 'width .4s' }}></div>
          </div>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '16px 22px 0' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <div className="portrait-clip" data-agent="zuki" style={{ width: 38, height: 38, border: `2px solid ${zuki.accent}`, background: zuki.tint }}><img src={zuki.portrait} alt="Zuki" /></div>
              <strong style={{ fontFamily: 'var(--font-display)' }}>Zuki</strong>
            </div>
            <button onClick={onClose} className="glass-soft" style={{ border: 'none', borderRadius: 99, width: 38, height: 38, cursor: 'pointer', display: 'grid', placeItems: 'center' }}><Icon name="x" size={18} /></button>
          </div>

          <div className="scroll-thin" style={{ flex: 1, overflowY: 'auto', padding: 'clamp(24px,4vw,44px)', display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
            {idx === -1 && (
              <div key="intro" className="fade-q">
                <div style={{ position: 'relative', width: 96, height: 96, marginBottom: 20 }}>
                  <span className="floaty" style={{ position: 'absolute', inset: -8, borderRadius: 99, background: `radial-gradient(circle,${zuki.accent}66,transparent 70%)`, filter: 'blur(8px)' }}></span>
                  <div className="portrait-clip floaty" data-agent="zuki" style={{ position: 'absolute', inset: 0, border: `4px solid ${zuki.accent}`, background: zuki.tint }}>
                    <img src={zuki.portrait} alt="Zuki" />
                  </div>
                </div>
                <h2 style={{ fontSize: '2.2rem', margin: '0 0 12px' }}>{L.form_intro_title}</h2>
                <p style={{ color: 'var(--ink-soft)', fontSize: '1.1rem', lineHeight: 1.6, marginBottom: 28, maxWidth: 460 }}>{L.form_intro_sub}</p>
                <p style={{ color: 'var(--ink-soft)', fontSize: '.82rem', lineHeight: 1.5, margin: '-12px 0 22px', maxWidth: 500 }}>
                  {lang === 'es' ? 'Al enviar, aceptas que usemos tus datos para responder a tu solicitud. Consulta nuestra ' : 'By submitting, you agree that we may use your information to respond to your request. See our '}
                  <a href="/privacy.html" target="_blank" rel="noopener">{lang === 'es' ? 'Política de privacidad' : 'Privacy Policy'}</a>
                  {lang === 'es' ? ' y el ' : ' and '}
                  <a href="/ai-notice.html" target="_blank" rel="noopener">{lang === 'es' ? 'aviso de IA' : 'AI notice'}</a>.
                </p>
                <button className="btn btn-orange" style={{ fontSize: '1.05rem' }} onClick={() => setIdx(0)}>{L.form_begin} <Icon name="arrow" size={18} /></button>
              </div>
            )}

            {q && (
              <div key={idx} className="fade-q">
                <div style={{ color: 'var(--orange-d)', fontWeight: 700, fontFamily: 'var(--font-display)', marginBottom: 8 }}>{idx + 1} <span style={{ opacity: .5 }}>/ {total}</span></div>
                <h2 style={{ fontSize: 'clamp(1.5rem,3.4vw,2.1rem)', margin: '0 0 6px' }}>{q.q[lang]}</h2>
                {q.sub && <p style={{ color: 'var(--ink-soft)', margin: '0 0 22px' }}>{q.sub[lang]}</p>}
                <div style={{ marginTop: q.sub ? 0 : 22 }}>
                  {(q.type === 'text' || q.type === 'email') && (
                    <input ref={inputRef} type={q.type} value={ans[q.id] || ''} placeholder={q.ph[lang]}
                      onChange={e => setVal(e.target.value)} onKeyDown={e => e.key === 'Enter' && next()}
                      style={fieldStyle} />
                  )}
                  {q.type === 'textarea' && (
                    <textarea ref={inputRef} value={ans[q.id] || ''} placeholder={q.ph[lang]} rows={3}
                      onChange={e => setVal(e.target.value)} style={{ ...fieldStyle, resize: 'vertical', minHeight: 90 }} />
                  )}
                  {(q.type === 'single' || q.type === 'multi') && (
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                      {q.options.map(o => {
                        const sel = q.type === 'multi' ? (ans[q.id] || []).includes(o.v) : ans[q.id] === o.v;
                        return (
                          <button key={o.v} onClick={() => { if (q.type === 'multi') toggle(o.v); else chooseSingle(o.v); }}
                            style={{ ...optStyle, borderColor: sel ? 'var(--orange)' : 'rgba(0,0,0,.1)', background: sel ? 'rgba(247,148,30,.12)' : 'rgba(255,255,255,.7)' }}>
                            <span style={{ width: 26, height: 26, borderRadius: q.type === 'multi' ? 8 : 99, border: `2px solid ${sel ? 'var(--orange)' : 'rgba(0,0,0,.2)'}`, background: sel ? 'var(--orange)' : 'transparent', display: 'grid', placeItems: 'center', flex: '0 0 auto' }}>
                              {sel && <Icon name="check" size={14} color="#fff" />}
                            </span>
                            <span style={{ fontWeight: 600 }}>{o[lang]}</span>
                          </button>
                        );
                      })}
                    </div>
                  )}
                </div>
                {err && <div style={{ color: '#d23', marginTop: 14, fontWeight: 600, fontSize: '.92rem' }}>{err}</div>}
                <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginTop: 26 }}>
                  <button className="btn btn-orange" onClick={next} disabled={submitting}>{submitting ? L.form_sending : (idx === total - 1 ? L.form_submit : L.form_next)} <Icon name="arrow" size={18} /></button>
                  {(q.type === 'text' || q.type === 'email' || q.type === 'textarea') && <span style={{ color: 'var(--ink-soft)', fontSize: '.85rem' }}>{L.form_enter}</span>}
                  {idx > 0 && <button className="btn btn-ghost" style={{ marginLeft: 'auto' }} onClick={back}>{L.form_back}</button>}
                </div>
              </div>
            )}

            {idx === total && result && (() => {
              const tier = TIER[result.sc.tier];
              return (
                <div key="done" className="fade-q" style={{ textAlign: 'center' }}>
                  <h2 style={{ fontSize: '2.2rem', margin: '0 0 8px' }}>{L.form_done_title}</h2>
                  <p style={{ color: 'var(--ink-soft)', marginBottom: 24, maxWidth: 460, marginInline: 'auto' }}>{L.form_done_sub}</p>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 20, flexWrap: 'wrap', marginBottom: 26 }}>
                    <Gauge value={result.sc.total} color={tier.c} label={L.form_done_score} />
                    <div className="chip" style={{ background: tier.c + '1a', color: tier.c, fontSize: '1rem', padding: '.6em 1.1em' }}>{tier[lang]}</div>
                  </div>
                  <div style={{ display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
                    <a className="btn btn-orange" href={window.gcalLink(lang)} target="_blank" rel="noopener">
                      <Icon name="calendar" size={18} /> {L.form_book}
                    </a>
                    <button className="btn btn-ghost" onClick={() => { onClose(); onChat(); }}><Icon name="message" size={18} /> {L.form_chat_more}</button>
                  </div>
                </div>
              );
            })()}
          </div>
        </div>
      </div>
    );
  }
  const fieldStyle = { width: '100%', fontSize: '1.15rem', padding: '14px 4px', border: 'none', borderBottom: '2px solid rgba(0,0,0,.18)', background: 'transparent', outline: 'none', fontFamily: 'var(--font-body)', color: 'var(--ink)' };
  const optStyle = { display: 'flex', alignItems: 'center', gap: 14, padding: '14px 18px', borderRadius: 16, border: '2px solid', cursor: 'pointer', textAlign: 'left', fontSize: '1.02rem', transition: 'all .18s', fontFamily: 'var(--font-body)' };
  window.ContactModal = ContactModal;
})();
