/* ===== Pago na Hora — Auth screens (login, forgot, reset) ===== */

// Shared error banner. Renders nothing when there is no message.
function AuthError({ message }) {
  if (!message) return null;
  return (
    <div className="panel" style={{ marginTop: 18, padding: '12px 14px', borderColor: 'var(--red, #C8453F)', background: '#FDF1F0', display: 'flex', gap: 10, alignItems: 'flex-start' }}>
      <Icon name="x" size={16} color="#C8453F" />
      <span style={{ color: '#9A2E29', fontSize: 13.5, fontWeight: 600, lineHeight: 1.4 }}>{message}</span>
    </div>
  );
}

// Shared shell: centered card matching the onboarding layout.
function AuthShell({ children }) {
  return (
    <div className="ob">
      <div className="ob-top">
        <a className="logo" href="https://pagonahora.com/" style={{ cursor: 'pointer' }}><BrandMark /> Pago <span className="thin">na Hora</span></a>
      </div>
      <div className="ob-body">
        <div className="ob-card" style={{ maxWidth: 440 }}>
          {children}
        </div>
      </div>
    </div>
  );
}

// Reads ?token= from the query string or the hash (e.g. #redefinir-senha?token=abc).
function readTokenFromUrl() {
  const fromSearch = new URLSearchParams(location.search).get('token');
  if (fromSearch) return fromSearch;
  const hash = location.hash || '';
  const qIndex = hash.indexOf('?');
  if (qIndex >= 0) {
    const token = new URLSearchParams(hash.slice(qIndex + 1)).get('token');
    if (token) return token;
  }
  return '';
}

// Renders the "Entrar com Google" button using Google Identity Services.
// Hidden entirely when window.PNH_GOOGLE_CLIENT_ID is not configured.
function GoogleButton({ onCredential, onError }) {
  const ref = useRef(null);
  const clientId = window.PNH_GOOGLE_CLIENT_ID;

  useEffect(() => {
    if (!clientId || !ref.current) return;
    let cancelled = false;

    // Wait for the GIS script (loaded async in index.html) to be ready.
    const tryInit = () => {
      if (cancelled) return;
      if (!(window.google && window.google.accounts && window.google.accounts.id)) {
        setTimeout(tryInit, 250);
        return;
      }
      try {
        window.google.accounts.id.initialize({
          client_id: clientId,
          callback: (response) => {
            if (response && response.credential) onCredential(response.credential);
            else if (onError) onError('Não foi possível autenticar com o Google.');
          },
        });
        window.google.accounts.id.renderButton(ref.current, {
          theme: 'outline', size: 'large', width: 360, text: 'continue_with', shape: 'pill',
        });
      } catch (e) {
        if (onError) onError('Falha ao carregar o login do Google.');
      }
    };
    tryInit();
    return () => { cancelled = true; };
  }, [clientId]);

  if (!clientId) return null;

  return (
    <div style={{ marginTop: 18 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 12, margin: '4px 0 16px', color: 'var(--ink-3)', fontSize: 12.5, fontWeight: 700 }}>
        <span style={{ flex: 1, height: 1, background: 'var(--line)' }}></span>
        OU
        <span style={{ flex: 1, height: 1, background: 'var(--line)' }}></span>
      </div>
      <div ref={ref} style={{ display: 'flex', justifyContent: 'center' }}></div>
    </div>
  );
}

/* ---------- Login ---------- */
function Login({ onAuthed }) {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState('');

  // Stores the session and notifies the parent with the MeResponse.
  async function completeLogin(loginResponse) {
    PNH.session.setSession({ token: loginResponse.token, account_id: loginResponse.account_id, me: loginResponse });
    let me = loginResponse;
    try {
      me = await PNH.api.auth.me();
      PNH.session.setSession({ me });
    } catch (e) {
      // Fall back to the login payload if /auth/me fails; the user is still authenticated.
    }
    if (onAuthed) onAuthed(me);
  }

  async function submit(e) {
    e.preventDefault();
    if (busy) return;
    setError('');
    setBusy(true);
    try {
      const res = await PNH.api.auth.login({ email: email.trim(), password });
      await completeLogin(res);
    } catch (err) {
      setError(err.detail || err.message || 'Não foi possível entrar.');
      setBusy(false);
    }
  }

  async function onGoogle(credential) {
    setError('');
    setBusy(true);
    try {
      const res = await PNH.api.auth.loginGoogle({ credential });
      await completeLogin(res);
    } catch (err) {
      setError(err.detail || err.message || 'Não foi possível entrar com o Google.');
      setBusy(false);
    }
  }

  const canSubmit = email.trim() && password && !busy;

  return (
    <AuthShell>
      <h2>Entrar na sua conta</h2>
      <p className="lead">Acesse o painel da Pago na Hora.</p>

      <form onSubmit={submit}>
        <div className="field">
          <label>E-mail</label>
          <input type="email" autoComplete="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="voce@email.com" />
        </div>
        <div className="field">
          <label>Senha</label>
          <input type="password" autoComplete="current-password" value={password} onChange={e => setPassword(e.target.value)} placeholder="Sua senha" />
          <div className="hint" style={{ textAlign: 'right' }}>
            <a href="#esqueci" style={{ color: 'var(--blue-600)', fontWeight: 700 }}>Esqueci minha senha</a>
          </div>
        </div>

        <AuthError message={error} />

        <div className="ob-actions" style={{ marginTop: 24 }}>
          <button type="submit" className="btn btn-primary grow" disabled={!canSubmit} style={{ opacity: canSubmit ? 1 : .5, cursor: canSubmit ? 'pointer' : 'not-allowed' }}>
            {busy ? 'Entrando…' : 'Entrar'} <Icon name="arrowR" size={16} />
          </button>
        </div>
      </form>

      <GoogleButton onCredential={onGoogle} onError={setError} />

      <p className="lead" style={{ fontSize: 14, marginTop: 24, textAlign: 'center' }}>
        Não tem conta? <a href="#onboarding" style={{ color: 'var(--blue-600)', fontWeight: 700 }}>Criar conta</a>
      </p>
    </AuthShell>
  );
}

/* ---------- Forgot password ---------- */
function ForgotPassword() {
  const [email, setEmail] = useState('');
  const [busy, setBusy] = useState(false);
  const [sent, setSent] = useState(false);

  async function submit(e) {
    e.preventDefault();
    if (busy) return;
    setBusy(true);
    try {
      await PNH.api.auth.requestPasswordReset({ email: email.trim() });
    } catch (err) {
      // Always show the same neutral message — never reveal whether the e-mail exists.
    }
    setBusy(false);
    setSent(true);
  }

  if (sent) {
    return (
      <AuthShell>
        <div className="bigcheck" style={{ marginBottom: 18 }}><Icon name="check" size={40} color="var(--green)" sw={3} /></div>
        <h2>Verifique seu e-mail</h2>
        <p className="lead">Se houver uma conta associada a esse e-mail, enviamos um link para redefinir sua senha. Confira também a caixa de spam.</p>
        <div className="ob-actions" style={{ marginTop: 24 }}>
          <a href="#login" className="btn btn-primary grow" style={{ justifyContent: 'center' }}><Icon name="arrowL" size={16} /> Voltar para entrar</a>
        </div>
      </AuthShell>
    );
  }

  const canSubmit = email.trim() && !busy;

  return (
    <AuthShell>
      <h2>Esqueceu a senha?</h2>
      <p className="lead">Informe seu e-mail e enviaremos um link para criar uma nova senha.</p>
      <form onSubmit={submit}>
        <div className="field">
          <label>E-mail</label>
          <input type="email" autoComplete="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="voce@email.com" />
        </div>
        <div className="ob-actions" style={{ marginTop: 24 }}>
          <a href="#login" className="btn btn-ghost"><Icon name="arrowL" size={16} /> Voltar</a>
          <button type="submit" className="btn btn-primary grow" disabled={!canSubmit} style={{ opacity: canSubmit ? 1 : .5, cursor: canSubmit ? 'pointer' : 'not-allowed' }}>
            {busy ? 'Enviando…' : 'Enviar link'} <Icon name="send" size={16} />
          </button>
        </div>
      </form>
    </AuthShell>
  );
}

/* ---------- Reset password ---------- */
function ResetPassword() {
  const [token] = useState(readTokenFromUrl);
  const [password, setPassword] = useState('');
  const [confirm, setConfirm] = useState('');
  const [busy, setBusy] = useState(false);
  const [error, setError] = useState('');
  const [done, setDone] = useState(false);

  async function submit(e) {
    e.preventDefault();
    if (busy) return;
    setError('');
    if (password.length < 8) { setError('A senha deve ter ao menos 8 caracteres.'); return; }
    if (password !== confirm) { setError('As senhas não conferem.'); return; }
    setBusy(true);
    try {
      await PNH.api.auth.resetPassword({ token, password });
      setDone(true);
    } catch (err) {
      setError(err.detail || err.message || 'Não foi possível redefinir a senha.');
      setBusy(false);
    }
  }

  if (done) {
    return (
      <AuthShell>
        <div className="bigcheck" style={{ marginBottom: 18 }}><Icon name="check" size={40} color="var(--green)" sw={3} /></div>
        <h2>Senha redefinida!</h2>
        <p className="lead">Sua senha foi atualizada. Agora você já pode entrar com a nova senha.</p>
        <div className="ob-actions" style={{ marginTop: 24 }}>
          <a href="#login" className="btn btn-primary grow" style={{ justifyContent: 'center' }}>Ir para entrar <Icon name="arrowR" size={16} /></a>
        </div>
      </AuthShell>
    );
  }

  if (!token) {
    return (
      <AuthShell>
        <h2>Link inválido</h2>
        <p className="lead">Este link de redefinição é inválido ou expirou. Solicite um novo a partir da tela de login.</p>
        <div className="ob-actions" style={{ marginTop: 24 }}>
          <a href="#esqueci" className="btn btn-primary grow" style={{ justifyContent: 'center' }}>Solicitar novo link <Icon name="arrowR" size={16} /></a>
        </div>
      </AuthShell>
    );
  }

  const canSubmit = password && confirm && !busy;

  return (
    <AuthShell>
      <h2>Criar nova senha</h2>
      <p className="lead">Escolha uma senha com pelo menos 8 caracteres.</p>
      <form onSubmit={submit}>
        <div className="field">
          <label>Nova senha</label>
          <input type="password" autoComplete="new-password" value={password} onChange={e => setPassword(e.target.value)} placeholder="Nova senha" />
        </div>
        <div className="field">
          <label>Confirmar nova senha</label>
          <input type="password" autoComplete="new-password" value={confirm} onChange={e => setConfirm(e.target.value)} placeholder="Repita a senha" />
        </div>

        <AuthError message={error} />

        <div className="ob-actions" style={{ marginTop: 24 }}>
          <a href="#login" className="btn btn-ghost"><Icon name="arrowL" size={16} /> Cancelar</a>
          <button type="submit" className="btn btn-primary grow" disabled={!canSubmit} style={{ opacity: canSubmit ? 1 : .5, cursor: canSubmit ? 'pointer' : 'not-allowed' }}>
            {busy ? 'Salvando…' : 'Redefinir senha'} <Icon name="check" size={16} />
          </button>
        </div>
      </form>
    </AuthShell>
  );
}

/* ---------- Verify email ---------- */
function VerifyEmail() {
  const [token] = useState(readTokenFromUrl);
  // status: 'verifying' | 'ok' | 'error' | 'notoken'
  const [status, setStatus] = useState(token ? 'verifying' : 'notoken');
  const [error, setError] = useState('');

  useEffect(() => {
    if (!token) return;
    let cancelled = false;
    (async () => {
      try {
        await PNH.api.auth.verifyEmail({ token });
        if (cancelled) return;
        setStatus('ok');
        // If a session is open, refresh it so the in-app banner clears on return.
        if (PNH.session.getToken()) {
          try { PNH.session.setSession({ me: await PNH.api.auth.me() }); } catch (e) { /* non-blocking */ }
        }
      } catch (err) {
        if (cancelled) return;
        setError(err.detail || err.message || 'Não foi possível confirmar o e-mail.');
        setStatus('error');
      }
    })();
    return () => { cancelled = true; };
  }, [token]);

  const goNext = PNH.session.getToken() ? '#dashboard' : '#login';

  if (status === 'verifying') {
    return (
      <AuthShell>
        <h2>Confirmando seu e-mail…</h2>
        <p className="lead">Só um instante enquanto validamos o seu link.</p>
      </AuthShell>
    );
  }

  if (status === 'ok') {
    return (
      <AuthShell>
        <div className="bigcheck" style={{ marginBottom: 18 }}><Icon name="check" size={40} color="var(--green)" sw={3} /></div>
        <h2>E-mail confirmado!</h2>
        <p className="lead">Tudo certo — sua conta está verificada.</p>
        <div className="ob-actions" style={{ marginTop: 24 }}>
          <a href={goNext} className="btn btn-primary grow" style={{ justifyContent: 'center' }}>Ir para o painel <Icon name="arrowR" size={16} /></a>
        </div>
      </AuthShell>
    );
  }

  if (status === 'error') {
    return (
      <AuthShell>
        <h2>Link inválido ou expirado</h2>
        <p className="lead">{error} Entre na sua conta e reenvie a confirmação pelo aviso no topo do painel.</p>
        <div className="ob-actions" style={{ marginTop: 24 }}>
          <a href="#login" className="btn btn-primary grow" style={{ justifyContent: 'center' }}>Ir para entrar <Icon name="arrowR" size={16} /></a>
        </div>
      </AuthShell>
    );
  }

  return (
    <AuthShell>
      <h2>Link inválido</h2>
      <p className="lead">Este link de confirmação é inválido. Entre na sua conta e reenvie a confirmação pelo aviso no topo do painel.</p>
      <div className="ob-actions" style={{ marginTop: 24 }}>
        <a href="#login" className="btn btn-primary grow" style={{ justifyContent: 'center' }}>Ir para entrar <Icon name="arrowR" size={16} /></a>
      </div>
    </AuthShell>
  );
}

Object.assign(window, { Login, ForgotPassword, ResetPassword, VerifyEmail });
