/* NINA — entrada self-contained: registro, login (OTP), confirmar número.
   Ligado à API real: GET /auth/config, POST /auth/request-code, POST /auth/verify. */
const { useState: eUS, useEffect: eUE, useRef: eUR } = React;
const E = () => window.NinaData;
const AUTH_API = window.NINA_API_BASE || '/api';

async function authFetch(path, body) {
  const r = await fetch(AUTH_API + path, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(body || {}),
  });
  let data = null;
  try { data = await r.json(); } catch (e) {}
  if (!r.ok) throw new Error((data && data.error) || 'Não consegui completar. Tenta de novo?');
  return data;
}

function EntryShell({ children, title, sub }) {
  const cfg = E().config;
  return (
    <div className="entry">
      <aside className="entry__aside">
        <a href="index.html" className="entry__brand" style={{ textDecoration: 'none', color: 'inherit' }}>
          <img src={cfg.logos.mark} alt="" /><span>{cfg.projectName}</span>
        </a>
        <div>
          <h2 className="entry__aside-h">Sua vida financeira,<br />começando agora. 🧡</h2>
          <p style={{ color: 'var(--muted)', fontSize: 16, maxWidth: 360, lineHeight: 1.55 }}>Em um minuto você já está conversando comigo no WhatsApp e vendo pra onde vai cada real.</p>
          <div className="col" style={{ gap: 12, marginTop: 28 }}>
            {['Grátis por 7 dias, sem cartão', 'Registre por texto, áudio ou foto', 'Seus dados são só seus (LGPD)'].map((t) => (
              <div key={t} className="row" style={{ gap: 10, fontSize: 14, fontWeight: 600 }}><Icon name="checkCircle" size={18} style={{ color: 'var(--coral-strong)' }} />{t}</div>
            ))}
          </div>
        </div>
        <div className="subtle" style={{ fontSize: 13 }}>© 2026 {cfg.projectName}</div>
      </aside>
      <main className="entry__panel">
        <div className="entry__form rise">
          <div style={{ marginBottom: 28 }}>
            <h1 style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 30, margin: '0 0 6px', letterSpacing: '-0.02em' }}>{title}</h1>
            <p className="muted" style={{ margin: 0 }}>{sub}</p>
          </div>
          {children}
        </div>
      </main>
    </div>
  );
}

function Registro({ go }) {
  const [form, setForm] = eUS({ nome: '', email: '', wa: '' });
  const [loading, setLoading] = eUS(false);
  const [err, setErr] = eUS('');
  const set = (k) => (e) => setForm((s) => ({ ...s, [k]: e.target.value }));
  const valid = form.nome.trim() && form.email.includes('@') && form.wa.replace(/\D/g, '').length >= 10;
  const maskWa = (v) => {
    const d = v.replace(/\D/g, '').slice(0, 11);
    if (d.length <= 2) return d.length ? `(${d}` : '';
    if (d.length <= 7) return `(${d.slice(0, 2)}) ${d.slice(2)}`;
    return `(${d.slice(0, 2)}) ${d.slice(2, 7)}-${d.slice(7)}`;
  };
  const phoneFull = () => '55' + form.wa.replace(/\D/g, '');
  const submit = async (e) => {
    e.preventDefault(); if (!valid || loading) return;
    setErr(''); setLoading(true);
    try {
      const r = await authFetch('/auth/request-code', { phone: phoneFull() });
      go('confirmar', { wa: form.wa, nome: form.nome, email: form.email, phone: phoneFull(), otpDisabled: !!r.otpDisabled });
    } catch (ex) { setErr(ex.message); } finally { setLoading(false); }
  };
  return (
    <EntryShell title="Criar conta grátis" sub="7 dias pra testar tudo, sem cartão.">
      <form onSubmit={submit} className="col" style={{ gap: 16 }}>
        <Field label="Como te chamo?"><Input value={form.nome} onChange={set('nome')} placeholder="Seu nome" autoFocus /></Field>
        <Field label="E-mail"><Input value={form.email} onChange={set('email')} type="email" placeholder="voce@email.com" /></Field>
        <Field label="WhatsApp" error={err || undefined}>
          <div className="row" style={{ gap: 8 }}>
            <span className="input" style={{ width: 64, flex: 'none', display: 'grid', placeItems: 'center', fontWeight: 700, color: 'var(--muted)' }}>+55</span>
            <Input value={form.wa} onChange={(e) => setForm((s) => ({ ...s, wa: maskWa(e.target.value) }))} placeholder="(11) 99999-9999" inputMode="numeric" />
          </div>
        </Field>
        <Button type="submit" block size="lg" style={!valid || loading ? { opacity: .55, pointerEvents: 'none' } : {}}>
          {loading ? <><span className="spin" /> Criando sua conta…</> : 'Criar conta grátis'}
        </Button>
        <div className="row" style={{ gap: 8, justifyContent: 'center', color: 'var(--mint-strong)', fontSize: 13, fontWeight: 600 }}>
          <Icon name="shield" size={15} /> 7 dias grátis · sem cartão · cancele quando quiser
        </div>
        <div className="subtle lp-center" style={{ fontSize: 13, marginTop: 4 }}>
          Já tem conta? <a href="#login" onClick={(e) => { e.preventDefault(); go('login'); }} style={{ color: 'var(--coral-strong)', fontWeight: 600 }}>Entrar</a>
        </div>
      </form>
    </EntryShell>
  );
}

function Login({ go }) {
  const [wa, setWa] = eUS('');
  const [loading, setLoading] = eUS(false);
  const [err, setErr] = eUS('');
  const maskWa = (v) => { const d = v.replace(/\D/g, '').slice(0, 11); if (d.length <= 2) return d.length ? `(${d}` : ''; if (d.length <= 7) return `(${d.slice(0, 2)}) ${d.slice(2)}`; return `(${d.slice(0, 2)}) ${d.slice(2, 7)}-${d.slice(7)}`; };
  const valid = wa.replace(/\D/g, '').length >= 10;
  const submit = async (e) => {
    e.preventDefault(); if (!valid || loading) return;
    setErr(''); setLoading(true);
    const phone = '55' + wa.replace(/\D/g, '');
    try {
      const r = await authFetch('/auth/request-code', { phone });
      go('confirmar', { wa, nome: 'de volta', phone, otpDisabled: !!r.otpDisabled });
    } catch (ex) { setErr(ex.message); } finally { setLoading(false); }
  };
  return (
    <EntryShell title="Entrar" sub="Sem senha — eu te envio um código no WhatsApp.">
      <form onSubmit={submit} className="col" style={{ gap: 16 }}>
        <Field label="Seu WhatsApp" error={err || undefined}>
          <div className="row" style={{ gap: 8 }}>
            <span className="input" style={{ width: 64, flex: 'none', display: 'grid', placeItems: 'center', fontWeight: 700, color: 'var(--muted)' }}>+55</span>
            <Input value={wa} onChange={(e) => setWa(maskWa(e.target.value))} placeholder="(11) 99999-9999" inputMode="numeric" autoFocus />
          </div>
        </Field>
        <Button type="submit" block size="lg" style={!valid || loading ? { opacity: .55, pointerEvents: 'none' } : {}}>{loading ? <><span className="spin" /> Enviando pro seu WhatsApp…</> : 'Receber código'}</Button>
        <div className="subtle lp-center" style={{ fontSize: 13 }}>Novo por aqui? <a href="#" onClick={(e) => { e.preventDefault(); go('registro'); }} style={{ color: 'var(--coral-strong)', fontWeight: 600 }}>Criar conta grátis</a></div>
      </form>
    </EntryShell>
  );
}

function Confirmar({ go, data }) {
  const cfg = E().config;
  const otpOff = data && data.otpDisabled;
  const [code, setCode] = eUS(['', '', '', '']);
  const [done, setDone] = eUS(false);
  const [busy, setBusy] = eUS(false);
  const [err, setErr] = eUS('');
  const refs = [eUR(), eUR(), eUR(), eUR()];
  const onChange = (i, v) => {
    const d = v.replace(/\D/g, '').slice(-1);
    setCode((c) => { const n = [...c]; n[i] = d; return n; });
    if (d && i < 3) refs[i + 1].current && refs[i + 1].current.focus();
  };
  const onKey = (i, e) => { if (e.key === 'Backspace' && !code[i] && i > 0) refs[i - 1].current && refs[i - 1].current.focus(); };
  const onPaste = (e) => {
    const digits = (e.clipboardData.getData('text') || '').replace(/\D/g, '').slice(0, 4).split('');
    if (!digits.length) return;
    e.preventDefault();
    setCode([0, 1, 2, 3].map((i) => digits[i] || ''));
    const last = Math.min(digits.length, 4) - 1;
    refs[last].current && refs[last].current.focus();
  };
  const doVerify = eUR(async () => {});
  doVerify.current = async () => {
    if (busy || done) return;
    setBusy(true); setErr('');
    try {
      const r = await authFetch('/auth/verify', {
        phone: data.phone, code: code.join(''), name: data.nome, email: data.email,
      });
      if (r.token) {
        localStorage.setItem('nina_token', r.token);
        if (r.user && r.user.role) localStorage.setItem('nina_role', r.user.role);
      }
      setDone(true);
      setTimeout(() => { window.location.href = 'app/index.html'; }, 1600);
    } catch (ex) { setErr(ex.message); } finally { setBusy(false); }
  };
  const full = code.every((c) => c);
  eUE(() => {
    if (otpOff && !done && !busy) { doVerify.current(); return; }
    if (full && !done && !busy) doVerify.current();
    // eslint-disable-next-line
  }, [full, otpOff]);
  const wa = `https://wa.me/${cfg.contact.whatsapp}?text=oi`;
  return (
    <EntryShell title={done ? 'Tudo certo! 🧡' : 'Confirme seu número'} sub={done ? 'Te levando pro seu painel…' : otpOff ? 'Entrando direto pelo número (validação).' : `Te enviei um código de 4 dígitos no WhatsApp${data && data.wa ? ' ' + data.wa : ''}.`}>
      {done ? (
        <div style={{ textAlign: 'center', padding: '12px 0' }}>
          <div style={{ position: 'relative', width: 96, height: 96, margin: '0 auto 16px' }}>
            <svg width="96" height="96" viewBox="0 0 96 96"><circle cx="48" cy="48" r="44" fill="var(--mint-tint)" /><path d="M30 49 L43 62 L66 36" fill="none" stroke="var(--mint-strong)" strokeWidth="5" strokeLinecap="round" strokeLinejoin="round" strokeDasharray="80" strokeDashoffset="80" style={{ animation: 'drawCheck 600ms ease-out forwards' }} /></svg>
          </div>
          <p className="muted">Bem-vinda{data && data.nome ? ', ' + (data.nome.split(' ')[0]) : ''}! Já estou organizando tudo pra você.</p>
        </div>
      ) : otpOff ? (
        <div className="col" style={{ gap: 16, alignItems: 'center', textAlign: 'center' }}>
          <span className="spin spin--dark" />
          {err && <div className="field__error">{err}</div>}
        </div>
      ) : (
        <div className="col" style={{ gap: 22 }}>
          <a href={wa} className="btn btn--whats btn--lg btn--block" target="_blank" rel="noopener"><Icon name="whatsapp" /> Abrir WhatsApp</a>
          <div className="otp-inputs" onPaste={onPaste}>
            {code.map((c, i) => <input key={i} ref={refs[i]} value={c} onChange={(e) => onChange(i, e.target.value)} onKeyDown={(e) => onKey(i, e)} inputMode="numeric" maxLength={1} autoFocus={i === 0} disabled={busy} />)}
          </div>
          {err && <div className="field__error lp-center">{err}</div>}
          <div className="subtle lp-center" style={{ fontSize: 12 }}>Colou o código? Eu preencho e te levo pro painel automaticamente.</div>
          <div className="subtle lp-center" style={{ fontSize: 13 }}>
            Não chegou?{' '}
            <button onClick={async () => { try { await authFetch('/auth/request-code', { phone: data.phone }); window.ninaToast('Código reenviado'); } catch (ex) { window.ninaToast(ex.message, 'error'); } }} style={{ border: 'none', background: 'none', color: 'var(--coral-strong)', fontWeight: 600, cursor: 'pointer' }}>Reenviar</button>
            {' '}· <button onClick={() => go('registro')} style={{ border: 'none', background: 'none', color: 'var(--muted)', fontWeight: 600, cursor: 'pointer' }}>Trocar número</button>
          </div>
        </div>
      )}
    </EntryShell>
  );
}

function EntryApp() {
  const [route, setRoute] = eUS(() => (location.hash.replace('#', '') || 'registro'));
  const [data, setData] = eUS(null);
  const go = (r, d) => { if (d) setData(d); setRoute(r); location.hash = r; window.scrollTo(0, 0); };
  eUE(() => { const onH = () => setRoute(location.hash.replace('#', '') || 'registro'); window.addEventListener('hashchange', onH); return () => window.removeEventListener('hashchange', onH); }, []);
  let view;
  if (route === 'login') view = <Login go={go} />;
  else if (route === 'confirmar' && data) view = <Confirmar go={go} data={data} />;
  else if (route === 'confirmar') view = <Login go={go} />;
  else view = <Registro go={go} />;
  return <>{view}<ToastHost /></>;
}

// White-label: busca marca real antes de montar (mesmo padrão da landing).
(async () => {
  try {
    const r = await fetch(AUTH_API + '/config');
    if (r.ok) {
      const cfg = await r.json();
      const nd = window.NinaData;
      nd.config.projectName = cfg.projectName || nd.config.projectName;
      if (cfg.contact) Object.assign(nd.config.contact, cfg.contact);
      if (cfg.logos) Object.assign(nd.config.logos, {
        mark: cfg.logos.mark || nd.config.logos.mark,
        lockup: cfg.logos.lockup || nd.config.logos.lockup,
      });
      if (cfg.palette && cfg.palette.accent) {
        window.applyNinaPalette({ accent: cfg.palette.accent, strong: cfg.palette.accent, tint: cfg.palette.accent + '22' });
      }
    }
  } catch (e) { /* segue com o default */ }
  ReactDOM.createRoot(document.getElementById('root')).render(<EntryApp />);
})();
