
function AuthShell({ kicker, title, desc, children }) {
  return (
    <div style={{ minHeight: '100vh', boxSizing: 'border-box', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 40, padding: '40px 20px' }}>
      <img src="assets/vertice-logo.svg" alt="Vértice Operations & Solutions" style={{ width: 220, maxWidth: '70%' }} />
      <main style={{ width: '100%', maxWidth: 420, boxSizing: 'border-box', background: 'var(--surface-dialog)', border: '1px solid var(--border-default)', borderRadius: 20, padding: '36px 32px', display: 'flex', flexDirection: 'column', gap: 28, animation: 'vx-enter 0.4s ease both' }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          <span style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 11, letterSpacing: '0.16em', color: 'var(--text-muted)' }}><i className="ph ph-lock-simple" style={{ fontSize: 14, color: 'var(--action-selected-icon)' }} />{kicker}</span>
          <h1 style={{ margin: 0, fontSize: 26, fontWeight: 600, letterSpacing: '-0.02em' }}>{title}</h1>
          <span style={{ fontSize: 14, color: 'var(--text-muted)' }}>{desc}</span>
        </div>
        {children}
      </main>
    </div>
  );
}

function ForgotPasswordScreen({ initialEmail, onBack }) {
  const { Input, Button, Alert } = window.VRticeDesignSystem_d763eb;
  const [email, setEmail] = React.useState(initialEmail || '');
  const [busy, setBusy] = React.useState(false), [touched, setTouched] = React.useState(false), [err, setErr] = React.useState(''), [sent, setSent] = React.useState(false);
  const re = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;
  const eErr = touched && !email.trim() ? 'Informe seu e-mail.' : touched && !re.test(email.trim()) ? 'Digite um e-mail válido.' : '';
  const submit = async e => {
    e.preventDefault(); setTouched(true); setErr('');
    if (!re.test(email.trim())) return;
    setBusy(true);
    const { error } = await window.VxAuth.requestReset(email.trim());
    setBusy(false);
    if (error) setErr(error); else setSent(true);
  };
  return (
    <AuthShell kicker="RECUPERAÇÃO DE ACESSO" title="Esqueci minha senha" desc="Informe o e-mail da sua conta. Enviaremos um link para definir uma nova senha.">
      {sent ? <>
        <Alert>Se o e-mail estiver cadastrado, você receberá um link de recuperação em instantes. Verifique também a caixa de spam.</Alert>
        <Button variant="secondary" size="lg" block onClick={onBack}>Voltar ao login</Button>
      </> : <form onSubmit={submit} noValidate style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
        {err && <Alert tone="danger">{err}</Alert>}
        <Input label="E-mail" type="email" size="lg" placeholder="nome@empresa.com" value={email} onChange={e => setEmail(e.target.value)} error={eErr} disabled={busy} />
        <Button type="submit" size="lg" block loading={busy}>{busy ? 'Enviando…' : 'Enviar link de recuperação'}</Button>
        <Button variant="link" onClick={onBack}>Voltar ao login</Button>
      </form>}
    </AuthShell>
  );
}

function ResetPasswordScreen({ onDone, onRequestNew }) {
  const { PasswordInput, Button, Alert, Spinner } = window.VRticeDesignSystem_d763eb;
  const A = window.VxAuth;
  const [status, setStatus] = React.useState('checking'); // checking | ready | invalid | done
  const [pw, setPw] = React.useState(''), [pw2, setPw2] = React.useState('');
  const [busy, setBusy] = React.useState(false), [touched, setTouched] = React.useState(false), [err, setErr] = React.useState('');
  React.useEffect(() => {
    if (A.linkError) { setStatus('invalid'); return; }
    return A.watchRecovery(ev => setStatus(ev === 'PASSWORD_RECOVERY' ? 'ready' : 'invalid'));
  }, []);
  const pErr = touched && !pw ? 'Informe a nova senha.' : touched && (pw.length < 8 || !/[A-Za-z]/.test(pw) || !/\d/.test(pw)) ? 'Use ao menos 8 caracteres, com letras e números.' : '';
  const cErr = touched && pw2 !== pw ? 'As senhas não coincidem.' : '';
  const submit = async e => {
    e.preventDefault(); setTouched(true); setErr('');
    if (!pw || pw.length < 8 || !/[A-Za-z]/.test(pw) || !/\d/.test(pw) || pw !== pw2) return;
    setBusy(true);
    const { error } = await A.updatePassword(pw);
    if (error) { setBusy(false); setErr(error); if (/Sessão de recuperação/.test(error)) setStatus('invalid'); return; }
    await A.signOut(); // encerra a sessão de recovery; o usuário entra com a nova senha
    setBusy(false); setStatus('done');
  };
  const expired = /expired/.test(A.linkError);
  return (
    <AuthShell kicker={A.linkType === 'invite' ? 'CONVITE' : 'RECUPERAÇÃO DE ACESSO'} title={A.linkType === 'invite' ? 'Definir sua senha' : 'Definir nova senha'} desc={A.linkType === 'invite' ? 'Você foi convidado para o Vértice OS. Escolha uma senha para entrar.' : 'Escolha uma senha para voltar a acessar o Vértice OS.'}>
      {status === 'checking' && <div style={{ display: 'flex', alignItems: 'center', gap: 12, color: 'var(--text-muted)', fontSize: 14 }}><Spinner />Validando link de recuperação…</div>}
      {status === 'invalid' && <>
        <Alert tone="danger">{expired ? 'Este link expirou.' : 'Este link é inválido ou já foi utilizado.'} Solicite um novo link de recuperação.</Alert>
        <Button size="lg" block onClick={onRequestNew}>Solicitar novo link</Button>
      </>}
      {status === 'ready' && <form onSubmit={submit} noValidate style={{ display: 'flex', flexDirection: 'column', gap: 20 }}>
        {err && <Alert tone="danger">{err}</Alert>}
        <PasswordInput label="Nova senha" placeholder="Mínimo de 8 caracteres" value={pw} onChange={e => setPw(e.target.value)} error={pErr} disabled={busy} />
        <PasswordInput label="Confirmar nova senha" placeholder="Repita a nova senha" value={pw2} onChange={e => setPw2(e.target.value)} error={cErr} disabled={busy} />
        <Button type="submit" size="lg" block loading={busy}>{busy ? 'Salvando…' : 'Salvar nova senha'}</Button>
      </form>}
      {status === 'done' && <>
        <Alert>Senha alterada com sucesso. Entre com a nova senha.</Alert>
        <Button size="lg" block onClick={onDone}>Ir para o login</Button>
      </>}
    </AuthShell>
  );
}
window.ForgotPasswordScreen = ForgotPasswordScreen;
window.ResetPasswordScreen = ResetPasswordScreen;
