/* Feedback ORG — Modals: Contact (6 steps), Instagram, Video lightbox + ModalHost */

/* ---------- generic overlay shell ---------- */
function Overlay({ children, onClose, maxWidth = 520 }) {
  useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', onKey);
    const prev = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    return () => { document.removeEventListener('keydown', onKey); document.body.style.overflow = prev; };
  }, []);
  useEffect(() => { refreshIcons(); });
  return (
    <div className="fb-overlay" onMouseDown={(e) => { if (e.target === e.currentTarget) onClose(); }}
      style={{ position: 'fixed', inset: 0, zIndex: 200, background: 'rgba(15,14,17,0.72)', backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)',
        display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20 }}>
      <div className="fb-modal-card" style={{ width: '100%', maxWidth, maxHeight: '92vh', overflowY: 'auto',
        background: 'var(--fb-ink-soft)', border: '1px solid var(--border)', borderRadius: 'var(--radius-lg)', boxShadow: 'var(--shadow-lg)' }}>
        {children}
      </div>
    </div>
  );
}

/* ====================== CONTACT MODAL (6 steps) ====================== */
const FAIXAS = ['Até 50', '50–100', '100–250', '250–500', '+500'];
const STEPS = [
  { key: 'nome', q: 'Qual seu nome?', type: 'text', ph: 'Seu nome', icon: 'user' },
  { key: 'email', q: 'Qual seu e-mail?', type: 'email', ph: 'voce@empresa.com.br', icon: 'mail' },
  { key: 'telefone', q: 'Qual seu telefone?', type: 'tel', ph: '(00) 00000-0000', icon: 'phone' },
  { key: 'empresa', q: 'Nome da empresa?', type: 'text', ph: 'Sua empresa', icon: 'building-2' },
  { key: 'faixa', q: 'Faixa de colaboradores?', type: 'choice', icon: 'users' },
  { key: 'dor', q: 'Sua dor hoje?', type: 'textarea', ph: 'Em uma frase, o que mais te incomoda?', icon: 'message-circle' },
];

function formatPhone(raw) {
  const d = raw.replace(/\D/g, '').slice(0, 11);
  if (d.length <= 2) return d;
  if (d.length <= 3) return `${d.slice(0,2)} ${d.slice(2)}`;
  if (d.length <= 7) return `${d.slice(0,2)} ${d.slice(2,3)} ${d.slice(3)}`;
  return `${d.slice(0,2)} ${d.slice(2,3)} ${d.slice(3,7)}-${d.slice(7)}`;
}

function ContactModal({ onClose, src }) {
  const { Button, Input } = window.FeedbackORGDesignSystem_591435;
  const [step, setStep] = useState(0);
  const [dir, setDir] = useState('next');
  const [data, setData] = useState({});
  const [done, setDone] = useState(false);
  const [err, setErr] = useState('');
  const [lgpd, setLgpd] = useState(false);
  const [loading, setLoading] = useState(false);
  const [apiErr, setApiErr] = useState('');
  const [turnstileToken, setTurnstileToken] = useState('');
  const [hp, setHp] = useState('');
  const inputRef = useRef(null);
  const turnstileRef = useRef(null);

  useEffect(() => { if (inputRef.current) inputRef.current.focus(); setErr(''); setTurnstileToken(''); }, [step]);

  useEffect(() => {
    if (typeof window.onTurnstileToken === 'undefined') {
      window.onTurnstileToken = (token) => { setTurnstileToken(token); };
    }
  }, []);

  /* Explicit Turnstile render on step 6.
     Auto-scan only runs on page load; when the widget div is added
     later via React state change, we must call render() ourselves. */
  useEffect(() => {
    if (step !== STEPS.length - 1) return;
    const container = turnstileRef.current?.querySelector('.cf-turnstile');
    if (!container || container.children.length > 0) return;
    let widgetId = null;
    let cancelled = false;
    const tryRender = () => {
      if (cancelled) return;
      if (window.turnstile && typeof window.turnstile.render === 'function') {
        try {
          widgetId = window.turnstile.render(container, {
            sitekey: '0x4AAAAAADrGQTMUUsocb-Sd',
            callback: (token) => setTurnstileToken(token),
            'error-callback': () => setTurnstileToken(''),
            'expired-callback': () => setTurnstileToken(''),
          });
        } catch (_) { /* already rendered — safe to ignore */ }
      } else {
        setTimeout(tryRender, 200);
      }
    };
    tryRender();
    return () => {
      cancelled = true;
      if (widgetId !== null && window.turnstile && typeof window.turnstile.remove === 'function') {
        try { window.turnstile.remove(widgetId); } catch (_) {}
      }
    };
  }, [step]);

  const cur = STEPS[step];
  const val = data[cur?.key] || '';

  const validate = () => {
    if (cur.type === 'email') return /.+@.+\..+/.test(val.trim()) ? '' : 'Informe um e-mail válido.';
    if (cur.type === 'textarea') return !lgpd ? 'Você precisa aceitar os Termos de Uso da LGPD.' : '';
    return val.trim() ? '' : 'Este campo é obrigatório.';
  };

  const go = (nextStep, direction) => { setDir(direction); setStep(nextStep); };
  const submitForm = async () => {
    setLoading(true);
    setApiErr('');
    const params = new URLSearchParams(location.search);
    try {
      const res = await fetch('https://fclrnkahnnmqhbewtagh.supabase.co/functions/v1/api-inbound-signup', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          form_key: 'lp-feedback',
          email: data.email,
          name: data.nome,
          phone: data.telefone,
          role: '',
          company: data.empresa,
          description: data.dor,
          utm: Object.fromEntries(
            ['source', 'medium', 'campaign']
              .map((k) => [k, params.get('utm_' + k)])
              .filter(([, v]) => v)
          ),
          turnstile_token: turnstileToken,
          hp: hp,
        }),
      });
      if (!res.ok) {
        const json = await res.json();
        throw new Error(json.error || 'Erro ao enviar dados');
      }
      setDone(true);
    } catch (e) {
      setApiErr(e.message);
    } finally {
      setLoading(false);
    }
  };

  const next = () => {
    const e = validate();
    if (e) { setErr(e); return; }
    if (step === STEPS.length - 1) { submitForm(); return; }
    go(step + 1, 'next');
  };
  const back = () => { if (step === 0) { onClose(); return; } go(step - 1, 'prev'); };
  const setField = (v) => setData((d) => ({ ...d, [cur.key]: v }));

  if (done) {
    return (
      <Overlay onClose={onClose}>
        <div style={{ padding: 'clamp(36px,6vw,52px)', textAlign: 'center' }}>
          <div style={{ width: 72, height: 72, margin: '0 auto', borderRadius: '50%', background: 'var(--accent)', color: 'var(--accent-ink)', display: 'flex', alignItems: 'center', justifyContent: 'center', animation: 'fb-check-pop .5s var(--ease-out) both' }}>
            <Icon name="check" size={36} strokeWidth={3} />
          </div>
          <h3 style={{ fontSize: 'clamp(1.4rem,3vw,1.9rem)', marginTop: 26 }}>Recebido.</h3>
          <p style={{ color: 'var(--text-muted)', fontSize: 16, marginTop: 12, maxWidth: 380, marginLeft: 'auto', marginRight: 'auto', lineHeight: 1.5 }}>
            Em breve entraremos em contato com você!
          </p>
          <div style={{ marginTop: 30 }}>
            <Button variant="primary" size="lg" onClick={onClose}>Fechar</Button>
          </div>
        </div>
      </Overlay>
    );
  }

  const pct = ((step) / STEPS.length) * 100;

  return (
    <Overlay onClose={onClose}>
      {/* honeypot: humano nunca preenche; se vier preenchido, o servidor descarta */}
      <input
        type="text"
        name="hp"
        tabIndex={-1}
        autoComplete="off"
        aria-hidden="true"
        value={hp}
        onChange={(e) => setHp(e.target.value)}
        style={{ position: 'absolute', left: '-9999px', top: 'auto', width: 1, height: 1, opacity: 0, pointerEvents: 'none' }}
      />
      {/* header: progress */}
      <div style={{ padding: '22px clamp(26px,5vw,40px) 0' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 14 }}>
          <button onClick={back} style={{ display: 'inline-flex', alignItems: 'center', gap: 6, background: 'none', border: 'none', color: 'var(--text-muted)', cursor: 'pointer', fontSize: 13.5, fontFamily: 'var(--font-body)', padding: 0 }}>
            <Icon name="arrow-left" size={16} /> {step === 0 ? 'Fechar' : 'Voltar'}
          </button>
          <span style={{ fontSize: 12, color: 'var(--text-dim)', letterSpacing: '0.04em', fontWeight: 600 }}>Etapa {step + 1} de {STEPS.length}</span>
          <button onClick={onClose} style={{ background: 'none', border: 'none', color: 'var(--text-muted)', cursor: 'pointer', padding: 0, display: 'flex' }}><Icon name="x" size={18} /></button>
        </div>
        <div style={{ height: 4, background: 'var(--fb-ink)', borderRadius: 'var(--radius-pill)', overflow: 'hidden' }}>
          <div style={{ height: '100%', width: `${pct}%`, background: 'var(--accent)', borderRadius: 'var(--radius-pill)', transition: 'width .4s var(--ease-out)' }}></div>
        </div>
      </div>

      {/* body: animated per step */}
      <div key={step} className={dir === 'next' ? 'fb-step-next' : 'fb-step-prev'} style={{ padding: 'clamp(26px,4vw,38px) clamp(26px,5vw,40px) clamp(24px,4vw,34px)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, color: 'var(--accent)', marginBottom: 16 }}>
          <div style={{ width: 40, height: 40, borderRadius: 'var(--radius)', background: 'var(--fb-ink)', border: '1px solid var(--border-strong)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon name={cur.icon} size={20} /></div>
        </div>
        <h3 style={{ fontSize: 'clamp(1.4rem, 3vw, 1.85rem)', lineHeight: 1.1 }}>{cur.q}</h3>

        <div style={{ marginTop: 22 }}>
          {cur.type === 'choice' ? (
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 10 }}>
              {FAIXAS.map((f) => (
                <button key={f} onClick={() => { setField(f); setTimeout(() => go(step + 1, 'next'), 120); }}
                  style={{ flex: '1 1 28%', minWidth: 92, padding: '14px 12px', borderRadius: 'var(--radius)', cursor: 'pointer',
                    fontFamily: 'var(--font-body)', fontWeight: 600, fontSize: 15,
                    background: val === f ? 'var(--accent)' : 'var(--fb-ink)', color: val === f ? 'var(--accent-ink)' : 'var(--text)',
                    border: `1px solid ${val === f ? 'var(--accent)' : 'var(--border-strong)'}`, transition: 'all var(--dur) var(--ease)' }}
                  onMouseEnter={(e) => { if (val !== f) e.currentTarget.style.borderColor = 'var(--accent)'; }}
                  onMouseLeave={(e) => { if (val !== f) e.currentTarget.style.borderColor = 'var(--border-strong)'; }}>{f}</button>
              ))}
            </div>
          ) : cur.type === 'textarea' ? (
            <div>
              <textarea ref={inputRef} value={val} onChange={(e) => setField(e.target.value)} rows={3} placeholder={cur.ph}
                style={{ width: '100%', resize: 'vertical', fontFamily: 'var(--font-body)', fontSize: 15, padding: '12px 14px', borderRadius: 'var(--radius)', outline: 'none',
                  background: 'var(--fb-ink)', color: 'var(--text)', border: '1px solid var(--border-strong)', boxSizing: 'border-box' }}
                onFocus={(e) => e.target.style.borderColor = 'var(--accent)'} onBlur={(e) => e.target.style.borderColor = 'var(--border-strong)'} />
              <label style={{ display: 'flex', alignItems: 'flex-start', gap: 10, marginTop: 14, cursor: 'pointer' }}>
                <input type="checkbox" checked={lgpd} onChange={(e) => { setLgpd(e.target.checked); setErr(''); }}
                  style={{ marginTop: 2, accentColor: 'var(--accent)', width: 16, height: 16, flexShrink: 0, cursor: 'pointer' }} />
                <span style={{ fontSize: 13, color: 'var(--text-muted)', lineHeight: 1.5 }}>
                  Concordo com os <strong style={{ color: 'var(--text)' }}>Termos de Uso da LGPD</strong>
                </span>
              </label>
            </div>
          ) : (
            <input ref={inputRef} type={cur.type} value={val} placeholder={cur.ph}
              onChange={(e) => {
                const v = cur.key === 'telefone' ? formatPhone(e.target.value) : e.target.value;
                setField(v);
              }}
              onKeyDown={(e) => { if (e.key === 'Enter') next(); }}
              style={{ width: '100%', fontFamily: 'var(--font-body)', fontSize: 16, padding: '14px 16px', borderRadius: 'var(--radius)', outline: 'none',
                background: 'var(--fb-ink)', color: 'var(--text)', border: `1px solid ${err ? 'var(--danger)' : 'var(--border-strong)'}` }}
              onFocus={(e) => { if (!err) e.target.style.borderColor = 'var(--accent)'; }} onBlur={(e) => { if (!err) e.target.style.borderColor = 'var(--border-strong)'; }} />
          )}
          {err && <p style={{ color: 'var(--danger)', fontSize: 13, marginTop: 8 }}>{err}</p>}
        </div>

        {cur.type !== 'choice' && (
          <div style={{ marginTop: 26 }}>
            {step === STEPS.length - 1 && (
              <div ref={turnstileRef} style={{ marginBottom: 16, display: 'flex', justifyContent: 'center' }}>
                <div className="cf-turnstile" data-sitekey="0x4AAAAAADrGQTMUUsocb-Sd" data-callback="onTurnstileToken"></div>
              </div>
            )}
            <Button variant="primary" size="lg" full onClick={next} disabled={loading || (step === STEPS.length - 1 && !turnstileToken)}
              iconRight={<Icon name={step === STEPS.length - 1 ? 'send' : 'arrow-right'} size={18} strokeWidth={2.2} />}>
              {loading ? 'Enviando...' : (step === STEPS.length - 1 ? 'Falar com especialista' : 'Continuar')}
            </Button>
            {apiErr && <p style={{ color: 'var(--danger)', fontSize: 13, marginTop: 8 }}>{apiErr}</p>}
          </div>
        )}
      </div>

      <div style={{ padding: '0 clamp(26px,5vw,40px) 22px', display: 'flex', alignItems: 'center', gap: 8, color: 'var(--text-dim)', fontSize: 12 }}>
        <Icon name="lock" size={13} /> Seus dados estão protegidos · LGPD
      </div>
    </Overlay>
  );
}



/* ====================== VIDEO LIGHTBOX ====================== */
function VideoModal({ onClose }) {
  return (
    <Overlay onClose={onClose} maxWidth={900}>
      <div style={{ position: 'relative' }}>
        <button onClick={onClose} style={{ position: 'absolute', top: 12, right: 12, zIndex: 2, width: 38, height: 38, borderRadius: '50%', background: 'rgba(0,0,0,0.5)', border: '1px solid var(--border-strong)', color: 'var(--text)', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', backdropFilter: 'blur(4px)' }}><Icon name="x" size={18} /></button>
        <div style={{ aspectRatio: '16/9', borderRadius: 'var(--radius-lg)', overflow: 'hidden', background: '#141318' }}>
          <iframe
            src="https://player.vimeo.com/video/1201924604?autoplay=1&title=0&byline=0&portrait=0&controls=0"
            style={{ width: '100%', height: '100%', border: 'none', display: 'block' }}
            allow="autoplay; fullscreen; picture-in-picture"
            allowFullScreen
          />
        </div>
      </div>
    </Overlay>
  );
}

/* ====================== MODAL HOST ====================== */
function ModalHost() {
  const [modal, setModal] = useState(null);
  useEffect(() => {
    const onOpen = (e) => setModal(e.detail);
    document.addEventListener('fb:open', onOpen);
    return () => document.removeEventListener('fb:open', onOpen);
  }, []);
  if (!modal) return null;
  const close = () => setModal(null);
  if (modal.name === 'contact') return <ContactModal onClose={close} src={modal.payload?.src} />;
if (modal.name === 'video') return <VideoModal onClose={close} />;
  return null;
}

Object.assign(window, { ModalHost });
