/* Nina website — fluxo de entrada (ligado à API real).
   Cadastro: registro (nome/e-mail/WhatsApp) → confirmar número (a Nina te envia o código) → trial ativo.
   Login:    confirmar número (mesmo OTP).
   OTP é outbound: o backend ENVIA o código pro WhatsApp (POST /auth/request-code). "Abrir WhatsApp" é só atalho.
   Sem API/erro de rede (preview estático) → modo demo: o fluxo avança pra dar pra ver o visual. */
const { useState: useStateA, useRef: useRefA } = React;

const WA_LINK = 'https://wa.me/5581973327563';
const EMAIL_DOMAINS = ['gmail.com', 'hotmail.com', 'outlook.com', 'yahoo.com.br', 'icloud.com'];
const AUTH_API = window.NINA_API_BASE || '/api';

/* POST helper. 3 casos:
   - rede/sem-API (TypeError) ou rota inexistente (404) → { demo:true } pra avançar (preview).
   - erro com { error } (ex.: código inválido) → lança Error(error) pra mostrar na tela.
   - sucesso → json. */
async function authPost(path, body) {
  let r;
  try {
    r = await fetch(AUTH_API + path, {
      method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),
    });
  } catch (e) {
    return { demo: true };
  }
  if (r.status === 404) return { demo: true };
  if (!r.ok) {
    const j = await r.json().catch(() => ({}));
    throw new Error(j.error || `erro ${r.status}`);
  }
  return r.json().catch(() => ({}));
}

function emailSuggestions(value) {
  if (!value || value.indexOf('@') === -1) return [];
  const at = value.indexOf('@');
  const local = value.slice(0, at);
  const domain = value.slice(at + 1).toLowerCase();
  if (!local) return [];
  return EMAIL_DOMAINS.filter(d => d.startsWith(domain) && d !== domain).slice(0, 4).map(d => local + '@' + d);
}

function formatPhone(raw) {
  const d = (raw || '').replace(/\D/g, '').slice(0, 11);
  if (!d) return '';
  let out = '(' + d.slice(0, 2);
  if (d.length >= 2) out += ') ';
  if (d.length > 2) out += d.slice(2, 3);
  if (d.length > 3) out += ' ' + d.slice(3, 7);
  if (d.length > 7) out += '-' + d.slice(7, 11);
  return out;
}

function Field({ label, children }) {
  return (
    <div style={{ marginBottom: 16 }}>
      <label style={{ display: 'block', fontSize: 13, fontWeight: 600, marginBottom: 6 }}>{label}</label>
      {children}
    </div>
  );
}

const inputStyle = (focused) => ({
  width: '100%', boxSizing: 'border-box', border: '1.5px solid ' + (focused ? 'var(--coral)' : 'var(--line)'),
  borderRadius: 12, padding: '11px 13px', fontFamily: 'var(--font-body)', fontSize: 16, background: 'var(--surface)',
  color: 'var(--ink)', outline: 'none', boxShadow: focused ? '0 0 0 2px var(--amber)' : 'none', transition: 'border-color var(--dur-fast) var(--ease-out), box-shadow var(--dur-fast) var(--ease-out)',
});

function Auth({ onBack, startStep = 'register' }) {
  const isLogin = startStep === 'otp';
  const [step, setStep] = useStateA(startStep); // register | otp | done
  const [form, setForm] = useStateA({ name: '', email: '', phone: '' });
  const [code, setCode] = useStateA(['', '', '', '']);
  const [codeSent, setCodeSent] = useStateA(!isLogin && startStep === 'otp');
  const [codeTransition, setCodeTransition] = useStateA(false);
  const [otpNotice, setOtpNotice] = useStateA('');
  const [sending, setSending] = useStateA(false);
  const [busy, setBusy] = useStateA(false);
  const [err, setErr] = useStateA('');
  const [codeError, setCodeError] = useStateA(false);
  const [focus, setFocus] = useStateA('');
  const [showSug, setShowSug] = useStateA(false);
  const [otpEnabled, setOtpEnabled] = useStateA(true);
  const codeRefs = useRefA([]);
  useLucide();

  // Lê config do login: se OTP estiver desligado (toggle admin), login é só por número.
  React.useEffect(() => {
    let on = true;
    (async () => {
      try { const r = await fetch(AUTH_API + '/auth/config'); if (r.ok) { const c = await r.json(); if (on && typeof c.otpEnabled === 'boolean') setOtpEnabled(c.otpEnabled); } } catch (e) { /* mantém default */ }
    })();
    return () => { on = false; };
  }, []);

  const set = (k, v) => setForm(f => ({ ...f, [k]: v }));
  const sugs = emailSuggestions(form.email);
  const phoneDigits = (form.phone || '').replace(/\D/g, '');

  const showCodeFields = !otpEnabled || (codeSent && !codeTransition);
  const beginCodeStep = (notice) => {
    setCode(['', '', '', '']);
    setCodeError(false);
    setCodeSent(true);
    setCodeTransition(true);
    setOtpNotice(notice || 'Código enviado no WhatsApp.');
    window.setTimeout(() => setCodeTransition(false), 650);
  };

  React.useEffect(() => {
    if (step !== 'otp' || !otpEnabled || !showCodeFields) return;
    const id = window.setTimeout(() => {
      if (codeRefs.current[0]) codeRefs.current[0].focus();
    }, 80);
    return () => window.clearTimeout(id);
  }, [step, otpEnabled, showCodeFields]);

  const onCodeChange = (i, v) => {
    const digit = v.replace(/\D/g, '').slice(-1);
    const next = [...code]; next[i] = digit; setCode(next); setCodeError(false); setErr('');
    if (digit && i < 3) codeRefs.current[i + 1] && codeRefs.current[i + 1].focus();
  };
  const onCodeKey = (i, e) => {
    if (e.key === 'Backspace' && !code[i] && i > 0) codeRefs.current[i - 1] && codeRefs.current[i - 1].focus();
  };
  const onCodePaste = (e) => {
    const txt = ((e.clipboardData && e.clipboardData.getData('text')) || '').replace(/\D/g, '').slice(0, 4);
    if (!txt) return;
    e.preventDefault();
    const next = ['', '', '', '']; for (let j = 0; j < txt.length; j++) next[j] = txt[j];
    setCode(next); setCodeError(false);
    codeRefs.current[Math.min(txt.length, 3)] && codeRefs.current[Math.min(txt.length, 3)].focus();
  };

  // Registro → arma+envia o código pro número; avança pra confirmação.
  const submitRegister = async () => {
    setErr('');
    if (!form.name.trim()) { setErr('Como a Nina vai te chamar?'); return; }
    if (phoneDigits.length < 10) { setErr('Confere seu WhatsApp com DDD 🙂'); return; }
    if (!otpEnabled) { confirmCode(); return; } // OTP off → entra direto pelo número
    setBusy(true);
    try {
      await authPost('/auth/request-code', { phone: phoneDigits });
      beginCodeStep('Código enviado no WhatsApp.');
      setStep('otp');
    } catch (e) { setErr(e.message); } finally { setBusy(false); }
  };

  // (Re)envia o código pro número informado.
  const requestCode = async () => {
    if (phoneDigits.length < 10) { setErr('Informe seu WhatsApp pra receber o código.'); return; }
    setSending(true); setErr(''); setOtpNotice('');
    try {
      await authPost('/auth/request-code', { phone: phoneDigits });
      beginCodeStep(codeSent ? 'Código reenviado no WhatsApp.' : 'Código enviado no WhatsApp.');
    } catch (e) {
      setErr(e.message || 'Não consegui enviar o código agora. Tenta de novo.');
    } finally { setSending(false); }
  };

  // Confirma o código → token + role → painel. Manda name/email no 1º acesso.
  const confirmCode = async () => {
    setErr('');
    if (phoneDigits.length < 10) { setErr('Informe seu WhatsApp pra confirmar.'); return; }
    if (otpEnabled && !codeSent) { setErr('Primeiro toque em Receber código.'); return; }
    if (otpEnabled && code.join('').length < 4) { setCodeError(true); return; }
    setBusy(true);
    try {
      const res = await authPost('/auth/verify', {
        phone: phoneDigits, code: code.join(''),
        name: form.name.trim() || undefined, email: form.email.trim() || undefined,
      });
      if (res && res.token) {
        localStorage.setItem('nina_token', res.token);
        if (res.user && res.user.role) localStorage.setItem('nina_role', res.user.role);
      }
      setStep('done');
    } catch (e) { setCodeError(true); setErr(e.message || 'Código inválido. Confere com a Nina 🙂'); } finally { setBusy(false); }
  };

  const goPanel = () => { window.location.href = 'app/index.html'; };

  const Steps = () => {
    if (isLogin) return null;
    const items = ['Conta', 'WhatsApp'];
    const idx = step === 'register' ? 0 : 1;
    return (
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8, marginBottom: 24 }}>
        {items.map((s, i) => (
          <React.Fragment key={s}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
              <div style={{ width: 22, height: 22, borderRadius: '50%', display: 'grid', placeItems: 'center', fontSize: 12, fontWeight: 700, background: i <= idx ? 'var(--coral-strong)' : 'var(--line)', color: i <= idx ? '#fff' : 'var(--subtle)' }}>{i < idx ? '✓' : i + 1}</div>
              <span style={{ fontSize: 12.5, fontWeight: 600, color: i <= idx ? 'var(--ink)' : 'var(--subtle)' }}>{s}</span>
            </div>
            {i < items.length - 1 && <div style={{ width: 22, height: 2, background: i < idx ? 'var(--coral-strong)' : 'var(--line)', borderRadius: 2 }}></div>}
          </React.Fragment>
        ))}
      </div>
    );
  };

  return (
    <div style={{ minHeight: '100vh', display: 'grid', placeItems: 'center', background: 'var(--page)', padding: 16, boxSizing: 'border-box' }}>
      <div style={{ width: '100%', maxWidth: 420 }}>
        <div style={{ textAlign: 'center', marginBottom: 24 }}><Logo height={38} variant="lockup" /></div>
        <div style={{ background: 'var(--surface)', borderRadius: 24, padding: 'clamp(20px, 5vw, 32px)', boxShadow: 'var(--shadow-md)', border: '1px solid var(--line)', boxSizing: 'border-box' }}>
          {step !== 'done' && <Steps />}

          {step === 'register' && (
            <React.Fragment>
              <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 25, margin: '0 0 6px' }}>Criar conta grátis</h1>
              <p style={{ color: 'var(--muted)', fontSize: 14.5, lineHeight: 1.5, margin: '0 0 22px' }}>Leva um minuto. Depois é só confirmar seu número 🙂</p>
              <Field label="Seu nome">
                <input value={form.name} onChange={e => set('name', e.target.value)} onFocus={() => setFocus('name')} onBlur={() => setFocus('')} placeholder="Como a Nina vai te chamar" style={inputStyle(focus === 'name')} />
              </Field>
              <Field label="E-mail">
                <div style={{ position: 'relative' }}>
                  <input value={form.email} onChange={e => { set('email', e.target.value); setShowSug(true); }} onFocus={() => { setFocus('email'); setShowSug(true); }} onBlur={() => { setFocus(''); setTimeout(() => setShowSug(false), 120); }} type="email" autoComplete="off" placeholder="voce@email.com" style={inputStyle(focus === 'email')} />
                  {showSug && sugs.length > 0 && (
                    <div style={{ position: 'absolute', top: 'calc(100% + 6px)', left: 0, right: 0, zIndex: 5, background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 12, boxShadow: 'var(--shadow-md)', overflow: 'hidden' }}>
                      {sugs.map((s, i) => (
                        <button key={s} type="button" onMouseDown={e => { e.preventDefault(); set('email', s); setShowSug(false); }}
                          style={{ display: 'flex', alignItems: 'center', gap: 9, width: '100%', textAlign: 'left', padding: '10px 13px', border: 0, borderTop: i ? '1px solid var(--line)' : 0, background: 'transparent', cursor: 'pointer', fontFamily: 'var(--font-body)', fontSize: 14.5, color: 'var(--ink)' }}
                          onMouseEnter={e => e.currentTarget.style.background = 'var(--surface-warm)'} onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
                          <Icon name="mail" size={15} color="var(--subtle)" /><span>{s.split('@')[0]}<b style={{ color: 'var(--coral-strong)' }}>@{s.split('@')[1]}</b></span>
                        </button>
                      ))}
                    </div>
                  )}
                </div>
              </Field>
              <Field label="WhatsApp">
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, ...inputStyle(focus === 'phone'), padding: '0 13px' }}>
                  <span style={{ color: 'var(--muted)', fontSize: 15, fontWeight: 600 }}>+55</span>
                  <input value={formatPhone(form.phone)} onChange={e => set('phone', e.target.value.replace(/\D/g, '').slice(0, 11))} onFocus={() => setFocus('phone')} onBlur={() => setFocus('')} inputMode="numeric" placeholder="(81) 9 7332-7563"
                    style={{ flex: 1, border: 0, outline: 'none', fontFamily: 'var(--font-body)', fontSize: 16, background: 'transparent', color: 'var(--ink)', padding: '11px 0' }} />
                </div>
              </Field>
              <Button variant="primary" full size="lg" onClick={() => !busy && submitRegister()}>{busy ? 'Criando…' : 'Criar conta grátis'}</Button>
              {err && <p style={{ color: 'var(--expense)', fontSize: 13, textAlign: 'center', margin: '12px 0 0' }}>{err}</p>}
              <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7, marginTop: 14, color: 'var(--mint-strong)', fontSize: 12.5, fontWeight: 600 }}>
                <Icon name="shield-check" size={15} /> 7 dias grátis · sem cartão · sem cobrança agora
              </div>
              <button onClick={onBack} style={{ display: 'block', margin: '16px auto 0', background: 'none', border: 0, color: 'var(--muted)', fontSize: 14, cursor: 'pointer', fontFamily: 'var(--font-body)' }}>← Voltar ao site</button>
            </React.Fragment>
          )}

          {step === 'otp' && (
            <React.Fragment>
              <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 25, margin: '0 0 6px' }}>Confirmar seu número</h1>
              <p style={{ color: 'var(--muted)', fontSize: 14.5, lineHeight: 1.55, margin: '0 0 18px' }}>{!otpEnabled ? 'Informe seu WhatsApp pra entrar. Seu número é o seu login.' : codeSent ? 'Pronto! A Nina te enviou um código no WhatsApp. Digite ele abaixo pra confirmar.' : 'Informe seu WhatsApp e a Nina te envia um código de confirmação.'}</p>
              {isLogin && (
                <div style={{ marginBottom: 14 }}>
                  <label style={{ display: 'block', fontSize: 13, fontWeight: 600, marginBottom: 6 }}>Seu WhatsApp</label>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10, ...inputStyle(focus === 'phone'), padding: '0 13px' }}>
                    <span style={{ color: 'var(--muted)', fontSize: 15, fontWeight: 600 }}>+55</span>
                    <input value={formatPhone(form.phone)} onChange={e => set('phone', e.target.value.replace(/\D/g, '').slice(0, 11))} onFocus={() => setFocus('phone')} onBlur={() => setFocus('')} inputMode="numeric" placeholder="(81) 9 7332-7563"
                      style={{ flex: 1, border: 0, outline: 'none', fontFamily: 'var(--font-body)', fontSize: 16, background: 'transparent', color: 'var(--ink)', padding: '11px 0' }} />
                  </div>
                  {otpEnabled && !codeSent && <Button variant="whatsapp" full icon="message-circle" style={{ marginTop: 12 }} onClick={() => !sending && requestCode()}>{sending ? 'Enviando…' : 'Receber código'}</Button>}
                </div>
              )}
              {otpEnabled && codeSent && codeTransition && (
                <div className="nina-pulse-once" style={{ textAlign: 'center', padding: '12px 0 18px' }}>
                  <div style={{ width: 58, height: 58, borderRadius: '50%', background: 'var(--mint-tint)', display: 'grid', placeItems: 'center', margin: '0 auto 12px' }}>
                    <NinaLoader size={30} />
                  </div>
                  <div style={{ fontSize: 14, fontWeight: 700, color: 'var(--ink)' }}>Código enviado</div>
                  <div style={{ fontSize: 13, color: 'var(--muted)', marginTop: 4 }}>Abrindo o campo de confirmação…</div>
                </div>
              )}
              {otpEnabled && showCodeFields && (
                <React.Fragment>
                  <div style={{ background: 'var(--surface-warm)', borderRadius: 14, padding: '13px 15px', margin: '4px 0 16px', display: 'flex', gap: 10 }}>
                    <Icon name="user-plus" size={18} color="var(--coral-strong)" style={{ marginTop: 1 }} />
                    <div style={{ fontSize: 13, color: 'var(--ink)', lineHeight: 1.5 }}><b>Adicione a Nina aos contatos</b> pra não perder os lembretes. <a href={WA_LINK} target="_blank" rel="noreferrer" style={{ color: 'var(--coral-strong)', fontWeight: 600 }}>Abrir conversa no WhatsApp</a></div>
                  </div>
                  <label style={{ display: 'block', fontSize: 13, fontWeight: 600, marginBottom: 10, textAlign: 'center' }}>Digite o código que a Nina enviou</label>
                  <div style={{ display: 'flex', gap: 12, justifyContent: 'center', marginBottom: (codeError || err) ? 8 : 22 }}>
                    {code.map((d, i) => (
                      <input key={i} ref={el => codeRefs.current[i] = el} value={d}
                        onChange={e => onCodeChange(i, e.target.value)} onKeyDown={e => onCodeKey(i, e)} onPaste={onCodePaste}
                        onFocus={e => e.target.select()} maxLength={1} inputMode="numeric"
                        className={d ? 'nina-pop' : undefined}
                        style={{ width: 54, height: 62, textAlign: 'center', fontSize: 25, fontWeight: 700, borderRadius: 14, border: '1.5px solid ' + (codeError ? 'var(--expense)' : d ? 'var(--coral)' : 'var(--line)'), background: 'var(--surface)', color: 'var(--ink)', outline: 'none', fontFamily: 'var(--font-body)', boxShadow: d ? '0 0 0 2px var(--amber)' : 'none', transition: 'border-color var(--dur-fast) var(--ease-out), box-shadow var(--dur-fast) var(--ease-out)' }} />
                    ))}
                  </div>
                </React.Fragment>
              )}
              {(codeError || err) && <p style={{ color: 'var(--expense)', fontSize: 13, textAlign: 'center', margin: '0 0 16px' }}>{err || 'Código incompleto ou inválido. Confere com a Nina 🙂'}</p>}
              {otpNotice && showCodeFields && <p style={{ color: 'var(--mint-strong)', fontSize: 13, fontWeight: 600, textAlign: 'center', margin: '0 0 14px' }}>{otpNotice}</p>}
              {showCodeFields && <Button variant="primary" full onClick={() => !busy && confirmCode()}>{busy ? 'Entrando…' : otpEnabled ? 'Confirmar' : 'Entrar'}</Button>}
              <div style={{ display: 'flex', justifyContent: 'center', gap: 18, marginTop: 16 }}>
                <button onClick={() => (isLogin ? onBack() : setStep('register'))} style={{ background: 'none', border: 0, color: 'var(--muted)', fontSize: 13.5, cursor: 'pointer', fontFamily: 'var(--font-body)' }}>← Voltar</button>
                {otpEnabled && codeSent && <button onClick={requestCode} style={{ background: 'none', border: 0, color: 'var(--coral-strong)', fontSize: 13.5, fontWeight: 600, cursor: 'pointer', fontFamily: 'var(--font-body)' }}>{sending ? 'Enviando…' : 'Reenviar código'}</button>}
              </div>
            </React.Fragment>
          )}

          {step === 'done' && (
            <div className="nina-pulse-once" style={{ textAlign: 'center', padding: '8px 0', position: 'relative' }}>
              <span className="nina-burst" style={{ '--bx': '-46px', '--by': '-28px', background: 'var(--coral)' }}></span>
              <span className="nina-burst" style={{ '--bx': '36px', '--by': '-40px', background: '#FFD37A', animationDelay: '60ms' }}></span>
              <span className="nina-burst" style={{ '--bx': '-18px', '--by': '-46px', background: 'var(--mint-strong)', animationDelay: '120ms' }}></span>
              <span className="nina-burst" style={{ '--bx': '50px', '--by': '-22px', background: 'var(--coral)', animationDelay: '40ms' }}></span>
              <div style={{ width: 72, height: 72, borderRadius: '50%', background: 'var(--mint-tint)', display: 'grid', placeItems: 'center', margin: '0 auto 18px' }}>
                <svg className="nina-check" viewBox="0 0 32 32" width="36" height="36" aria-hidden="true">
                  <path d="M7 17 L13.5 23 L25 10" fill="none" stroke="var(--mint-strong)" strokeWidth="4" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
              </div>
              <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 24, margin: '0 0 8px' }}>{isLogin ? 'Tudo certo!' : 'Seus 7 dias grátis começaram 🎉'}</h1>
              <p style={{ color: 'var(--muted)', fontSize: 15, lineHeight: 1.5, margin: '0 0 20px' }}>{isLogin ? 'Você está dentro. Vamos dar uma olhada no seu mês?' : 'Sem cobrança agora. Aproveite tudo da Nina — quando quiser assinar o Pro, é R$ 9,90/mês via Pix, lá no painel.'}</p>
              <Button variant="primary" full iconRight="arrow-right" onClick={goPanel}>Ir pro painel</Button>
            </div>
          )}
        </div>
        <p style={{ textAlign: 'center', color: 'var(--subtle)', fontSize: 12.5, marginTop: 18, lineHeight: 1.5 }}>Ao continuar você concorda com os <a href="legal.html" style={{ color: 'var(--muted)' }}>Termos</a> e a <a href="legal.html" style={{ color: 'var(--muted)' }}>Privacidade</a>.</p>
      </div>
    </div>
  );
}

Object.assign(window, { Auth });
