/* ============================================================
   Tapa do Dia — Controle de acesso (login)
   ------------------------------------------------------------
   COMO FUNCIONA
   - A compradora entra com EMAIL + SENHA DE ACESSO.
   - A senha de acesso é a mesma que o Stripe mostra na tela de
     "obrigada pela compra" (você configura isso no painel do Stripe).
   - Quem entra fica logada (sessão salva no aparelho).

   >>> O QUE VOCÊ PODE EDITAR <<<
   1) ACCESS_PASSWORD: a senha que libera o app. Troque pela sua e
      coloque a MESMA na mensagem de agradecimento do Stripe.
   2) AUTHORIZED_EMAILS: (opcional) se quiser liberar SÓ para emails
      específicos, liste-os aqui. Deixe a lista vazia [] para aceitar
      qualquer email que tenha a senha de acesso correta.
   3) CHECKOUT_URL: seu link de compra (para quem ainda não comprou).
   ============================================================ */

window.AUTH_CONFIG = {
  ACCESS_PASSWORD: 'TAPA0549',          // <-- TROQUE pela sua senha
  AUTHORIZED_EMAILS: [],                // <-- ex: ['ana@email.com','maria@email.com'] — vazio = qualquer email + senha certa
  CHECKOUT_URL: 'https://buy.stripe.com/dRmeVe0r767bdDygxB6Vq04'
};

const AUTH_KEY = 'tapadodia.auth.v1';

window.authLoad = function () {
  try {
    const s = JSON.parse(localStorage.getItem(AUTH_KEY));
    if (s && s.email && s.ok) return s;
  } catch (e) {}
  return null;
};
window.authSave = function (email) {
  try { localStorage.setItem(AUTH_KEY, JSON.stringify({ email: email, ok: true, ts: Date.now() })); } catch (e) {}
};
window.authClear = function () {
  try { localStorage.removeItem(AUTH_KEY); } catch (e) {}
};

(function () {
  const { useState } = React;

  const normEmail = (e) => (e || '').trim().toLowerCase();
  const validEmail = (e) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(normEmail(e));

  function LoginGate({ onSuccess }) {
    const cfg = window.AUTH_CONFIG;
    const [email, setEmail] = useState('');
    const [pass, setPass] = useState('');
    const [err, setErr] = useState('');
    const [show, setShow] = useState(false);

    function submit(e) {
      e.preventDefault();
      const em = normEmail(email);
      if (!validEmail(em)) { setErr('Digite um email válido.'); return; }

      const allow = cfg.AUTHORIZED_EMAILS || [];
      if (allow.length && !allow.map(normEmail).includes(em)) {
        setErr('Este email não está liberado. Use o email da sua compra.');
        return;
      }
      const ok = (pass || '').trim().toLowerCase() === String(cfg.ACCESS_PASSWORD).trim().toLowerCase();
      if (!ok) { setErr('Senha de acesso incorreta. Confira a mensagem que você recebeu após a compra.'); return; }

      window.authSave(em);
      onSuccess(em);
    }

    return (
      <div className="auth-stage">
        <style>{AUTH_CSS}</style>
        <div className="auth-glow" aria-hidden="true"></div>
        <div className="auth-grain" aria-hidden="true"></div>

        <div className="auth-card">
          <div className="auth-brand">
            <div className="auth-rule"></div>
            <h1 className="auth-word">Tapa do Dia</h1>
            <p className="auth-sub">Mulheres Milionárias</p>
          </div>

          <div className="auth-head">
            <span className="auth-kicker">Acesso exclusivo</span>
            <h2 className="auth-title">Entre na sua conta</h2>
            <p className="auth-lead">Use o email da sua compra e a senha de acesso que você recebeu.</p>
          </div>

          <form className="auth-form" onSubmit={submit} noValidate>
            <label className="auth-field">
              <span>Email da compra</span>
              <input
                type="email" inputMode="email" autoComplete="email"
                placeholder="voce@email.com"
                value={email}
                onChange={(e) => { setEmail(e.target.value); setErr(''); }}
              />
            </label>

            <label className="auth-field">
              <span>Senha de acesso</span>
              <div className="auth-pass">
                <input
                  type={show ? 'text' : 'password'} autoComplete="current-password"
                  placeholder="sua senha de acesso"
                  value={pass}
                  onChange={(e) => { setPass(e.target.value); setErr(''); }}
                />
                <button type="button" className="auth-eye" onClick={() => setShow(s => !s)}>
                  {show ? 'ocultar' : 'ver'}
                </button>
              </div>
            </label>

            {err && <p className="auth-err">{err}</p>}

            <button type="submit" className="auth-btn">Entrar no app</button>
          </form>

          <div className="auth-foot">
            <p>Ainda não tem acesso?</p>
            <a href={cfg.CHECKOUT_URL}>Garantir meu acesso →</a>
          </div>
        </div>
      </div>
    );
  }

  window.LoginGate = LoginGate;
})();

const AUTH_CSS = `
.auth-stage{
  position:relative; min-height:100dvh; width:100%;
  display:flex; align-items:center; justify-content:center;
  padding:clamp(20px,5vh,48px) 22px calc(env(safe-area-inset-bottom) + 26px);
  isolation:isolate;
}
.auth-glow{
  position:fixed; inset:0; z-index:-2; pointer-events:none;
  background:
    radial-gradient(60% 48% at 50% 30%, var(--accent-glow), transparent 70%),
    linear-gradient(180deg, var(--bg-2), var(--bg) 60%);
}
.auth-grain{
  position:fixed; inset:0; z-index:-1; pointer-events:none; opacity:var(--grain,0.04);
  background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='160' height='160'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='0.8' numOctaves='2'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E");
  mix-blend-mode:overlay;
}
.auth-card{
  width:100%; max-width:440px;
  background:linear-gradient(180deg,var(--surface-2),var(--surface));
  border:1px solid var(--hairline); border-radius:24px;
  padding:clamp(30px,6vw,46px) clamp(24px,6vw,40px) clamp(28px,5vw,38px);
  box-shadow:var(--card-shadow, 0 50px 100px -34px rgba(0,0,0,0.4));
  position:relative; overflow:hidden;
}
.auth-card::before{
  content:""; position:absolute; left:0; top:0; bottom:0; width:3px;
  background:var(--accent); opacity:.9;
}
.auth-brand{ text-align:center; display:flex; flex-direction:column; align-items:center; gap:4px; margin-bottom:26px; }
.auth-rule{ width:34px; height:2px; background:var(--accent); border-radius:2px; margin-bottom:10px; }
.auth-word{ font-family:var(--font-quote); font-weight:700; letter-spacing:-0.03em; font-size:clamp(26px,7vw,34px); color:var(--ink); line-height:.9; }
.auth-sub{ font-family:var(--font-mono); text-transform:uppercase; letter-spacing:.4em; font-size:9.5px; color:var(--accent); padding-left:.4em; }

.auth-head{ text-align:center; margin-bottom:24px; }
.auth-kicker{ font-family:var(--font-mono); text-transform:uppercase; letter-spacing:.26em; font-size:10px; color:var(--accent); }
.auth-title{ font-family:var(--font-quote); font-weight:700; letter-spacing:-0.02em; font-size:clamp(22px,5vw,28px); color:var(--ink); margin:10px 0 8px; }
.auth-lead{ color:var(--ink-soft); font-size:14px; line-height:1.5; max-width:34ch; margin:0 auto; }

.auth-form{ display:flex; flex-direction:column; gap:16px; }
.auth-field{ display:flex; flex-direction:column; gap:7px; }
.auth-field > span{ font-family:var(--font-mono); text-transform:uppercase; letter-spacing:.12em; font-size:10.5px; color:var(--ink-faint); }
.auth-field input{
  width:100%; font-family:var(--font-ui); font-size:16px; color:var(--ink);
  background:var(--bg-2); border:1px solid var(--hairline); border-radius:12px;
  padding:14px 15px; outline:none; transition:border-color .18s, box-shadow .18s;
}
.auth-field input::placeholder{ color:var(--ink-faint); }
.auth-field input:focus{ border-color:var(--accent); box-shadow:0 0 0 3px var(--accent-glow); }
.auth-pass{ position:relative; display:flex; }
.auth-pass input{ padding-right:64px; }
.auth-eye{
  position:absolute; right:7px; top:50%; transform:translateY(-50%);
  font-family:var(--font-mono); font-size:11px; letter-spacing:.06em; text-transform:uppercase;
  color:var(--ink-soft); background:transparent; border:0; cursor:pointer; padding:8px 10px;
}
.auth-eye:hover{ color:var(--accent); }

.auth-err{
  color:#c4584f; font-size:13px; line-height:1.45;
  background:color-mix(in srgb, #c4584f 9%, transparent);
  border:1px solid color-mix(in srgb, #c4584f 26%, transparent);
  border-radius:10px; padding:11px 13px; margin:-2px 0 0;
}

.auth-btn{
  margin-top:6px; font-family:var(--font-quote); font-weight:600; font-size:17px; letter-spacing:-0.01em;
  background:var(--accent); color:var(--accent-ink); border:0; border-radius:999px;
  padding:16px 24px; cursor:pointer; transition:transform .12s ease, filter .18s ease;
  box-shadow:0 14px 34px -14px var(--accent-glow);
}
.auth-btn:hover{ filter:brightness(1.06); }
.auth-btn:active{ transform:translateY(1px) scale(.99); }

.auth-foot{ text-align:center; margin-top:24px; padding-top:22px; border-top:1px solid var(--hairline); }
.auth-foot p{ color:var(--ink-faint); font-size:13px; margin-bottom:6px; }
.auth-foot a{ font-family:var(--font-quote); font-weight:600; font-size:15px; color:var(--accent); text-decoration:none; }
.auth-foot a:hover{ text-decoration:underline; }
`;
