// Email verification landing page (M2)
// Handles the ?status=invalid case from the API redirect.
// The success case (valid token) redirects straight to /#/dashboard?verified=1,
// so this page mainly shows errors and offers resend.
const VerifyEmailPage = () => {
  const t = useT();
  const ve = (t.auth && t.auth.verifyEmail) || {};
  const auth = (typeof window.useAuth === 'function') ? window.useAuth() : null;

  // Read status from hash query string
  const hashQuery = window.location.hash.split('?')[1] || '';
  const params = new URLSearchParams(hashQuery);
  const status = params.get('status') || '';

  const [resendState, setResendState] = React.useState('idle'); // idle | sending | sent | error

  const handleResend = async () => {
    setResendState('sending');
    try {
      const res = await fetch('/api/auth/resend-verification', {
        method: 'POST',
        credentials: 'same-origin',
      });
      if (res.ok) {
        setResendState('sent');
      } else {
        setResendState('error');
      }
    } catch (_) {
      setResendState('error');
    }
  };

  const isInvalid = status === 'invalid';

  return (
    <div className="pb-scroll">
      <PBNav />
      <div className="pb-auth-shell">
        <div className="pb-auth-card" data-testid="verify-card">
          <div style={{ marginBottom: 12 }}><PBLogo size={36} /></div>
          <h1 className="pb-auth-title" data-testid="verify-email-title">
            {ve.title || '验证邮箱'}
          </h1>

          {isInvalid ? (
            <div>
              <p className="pb-auth-sub" style={{ color: 'var(--pb-danger, #c0392b)', marginBottom: 20 }}>
                {ve.invalid || '该验证链接已失效或已使用，请重新发送。'}
              </p>

              {resendState === 'sent' ? (
                <div
                  data-testid="verify-resent-msg"
                  style={{ padding: '10px 14px', background: 'var(--pb-success-bg, #edfaf1)', border: '1px solid var(--pb-success)', borderRadius: 6, fontSize: 14, color: 'var(--pb-success-fg, #155724)', marginBottom: 16 }}
                >
                  {ve.resent || '验证邮件已重新发送，请查收。'}
                </div>
              ) : auth && auth.user ? (
                <button
                  type="button"
                  data-testid="verify-page-resend"
                  className="pb-btn pb-btn-primary"
                  style={{ width: '100%', marginBottom: 16 }}
                  disabled={resendState === 'sending'}
                  onClick={handleResend}
                >
                  {resendState === 'sending'
                    ? (ve.resending || '发送中…')
                    : (ve.resendBtn || '重新发送验证邮件')}
                </button>
              ) : (
                <div className="pb-auth-meta" style={{ marginBottom: 16 }}>
                  <span
                    className="pb-link"
                    onClick={() => navigateTo('/login')}
                  >
                    {'返回登录'}
                  </span>
                </div>
              )}

              {resendState === 'error' && (
                <div style={{ fontSize: 13, color: 'var(--pb-danger, #c0392b)', marginBottom: 12 }}>
                  {'发送失败，请稍后重试。'}
                </div>
              )}
            </div>
          ) : (
            <div>
              <p className="pb-auth-sub">{ve.verifying || '正在验证…'}</p>
            </div>
          )}

          <div className="pb-auth-meta" style={{ marginTop: 16 }}>
            <span className="pb-link" onClick={() => navigateTo('/login')}>
              {'返回登录'}
            </span>
          </div>
        </div>
      </div>
      <PBFooter />
    </div>
  );
};
window.VerifyEmailPage = VerifyEmailPage;
