// auth.jsx — Sign in / Sign up / Forgot password / Reset password screens
// Uses window.AuthAPI from db.js. Shares Vital aesthetic with the rest of the app.

const { useState: auS, useEffect: auE } = React;

// ── Shared chrome ───────────────────────────────────────────────────────────
function AuthShell({ children, lang, setLang, onClose }) {
  return (
    <div className="auth-shell">
      {onClose && (
        <button type="button" className="auth-overlay-close" onClick={onClose}
                aria-label={lang === 'zh' ? '關閉' : 'Close'}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none"
               stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
            <path d="M6 6l12 12M6 18L18 6"/>
          </svg>
        </button>
      )}
      <div className="auth-top">
        <VitalBrand markSize={36} />
        <LangPill lang={lang} setLang={setLang} />
      </div>
      <div className="auth-body">{children}</div>
      <div className="auth-foot mono muted-2">
        {lang === 'zh' ? '所有資料於本地及 Supabase 安全儲存' : 'Secured via Supabase · Hong Kong NCHK aligned'}
      </div>
    </div>
  );
}

function AuthField({ label, type='text', value, onChange, placeholder, autoFocus, autoComplete }) {
  return (
    <label className="auth-field">
      <div className="auth-label mono">{label}</div>
      <input
        className="auth-input"
        type={type}
        value={value}
        onChange={e => onChange(e.target.value)}
        placeholder={placeholder}
        autoFocus={autoFocus}
        autoComplete={autoComplete}
      />
    </label>
  );
}

function AuthError({ msg, lang }) {
  if (!msg) return null;
  // friendlier copy for common errors
  let pretty = msg;
  const m = msg.toLowerCase();
  if (m.includes('invalid login'))         pretty = lang === 'zh' ? '電郵或密碼不正確' : 'Email or password is incorrect';
  else if (m.includes('already registered')) pretty = lang === 'zh' ? '此電郵已註冊 — 請登入' : 'Already registered — please sign in';
  else if (m.includes('email not confirmed')) pretty = lang === 'zh' ? '請先到電郵驗證帳戶' : 'Please confirm your email first';
  else if (m.includes('password should be')) pretty = lang === 'zh' ? '密碼最少 6 位' : 'Password must be at least 6 characters';
  return <div className="auth-error">{pretty}</div>;
}

// ── Sign in ─────────────────────────────────────────────────────────────────
function SignInScreen({ lang, setLang, goSignUp, goForgot, onClose }) {
  const [email, setEmail] = auS('');
  const [pw, setPw] = auS('');
  const [busy, setBusy] = auS(false);
  const [err, setErr] = auS('');

  const submit = async (e) => {
    e?.preventDefault?.();
    if (!email || !pw) return;
    setBusy(true); setErr('');
    const { error } = await AuthAPI.signIn(email.trim(), pw);
    setBusy(false);
    if (error) setErr(error.message);
    // success: auth state listener in app.jsx will swap the route
  };

  return (
    <AuthShell lang={lang} setLang={setLang} onClose={onClose}>
      <div className="auth-eyebrow mono">{lang === 'zh' ? '登入' : 'Sign in'}</div>
      <h1 className="auth-title serif">
        {lang === 'zh' ? '歡迎回來。' : 'Welcome back.'}
      </h1>
      <p className="auth-sub">
        {lang === 'zh' ? '繼續追蹤你的 CNE 進度。' : 'Pick up where you left off — your CNE points and saved courses are waiting.'}
      </p>

      <form onSubmit={submit} className="auth-form">
        <AuthField label={lang === 'zh' ? '電郵' : 'Email'} type="email"
          value={email} onChange={setEmail} autoFocus autoComplete="email"
          placeholder="you@hospital.hk" />
        <AuthField label={lang === 'zh' ? '密碼' : 'Password'} type="password"
          value={pw} onChange={setPw} autoComplete="current-password"
          placeholder="••••••••" />
        <AuthError msg={err} lang={lang} />
        <button className="auth-primary" type="submit" disabled={busy}>
          {busy ? (lang === 'zh' ? '登入中…' : 'Signing in…') : (lang === 'zh' ? '登入' : 'Sign in')}
        </button>
      </form>

      <div className="auth-links">
        <button className="auth-link" type="button" onClick={goForgot}>
          {lang === 'zh' ? '忘記密碼？' : 'Forgot password?'}
        </button>
        <span className="muted-2" style={{ fontSize: 12 }}>·</span>
        <button className="auth-link" type="button" onClick={goSignUp}>
          {lang === 'zh' ? '建立帳戶' : 'Create account'}
        </button>
      </div>
    </AuthShell>
  );
}

// ── Sign up ─────────────────────────────────────────────────────────────────
function SignUpScreen({ lang, setLang, goSignIn, onClose }) {
  const [email, setEmail] = auS('');
  const [pw, setPw] = auS('');
  const [pw2, setPw2] = auS('');
  const [busy, setBusy] = auS(false);
  const [err, setErr] = auS('');
  const [sent, setSent] = auS(false);

  const submit = async (e) => {
    e?.preventDefault?.();
    if (!email || !pw) return;
    if (pw.length < 6)  return setErr(lang === 'zh' ? '密碼最少 6 位' : 'Password must be at least 6 characters');
    if (pw !== pw2)     return setErr(lang === 'zh' ? '兩次輸入的密碼不一致' : "Passwords don't match");
    setBusy(true); setErr('');
    const { data, error } = await AuthAPI.signUp(email.trim(), pw);
    setBusy(false);
    if (error) return setErr(error.message);
    // Supabase by default returns a session for confirmed-via-link projects;
    // if email confirmations are on, no session is returned — show "check inbox".
    if (data?.session) {
      // session listener will route us forward
    } else {
      setSent(true);
    }
  };

  if (sent) {
    return (
      <AuthShell lang={lang} setLang={setLang} onClose={onClose}>
        <div className="auth-eyebrow mono">{lang === 'zh' ? '請查看電郵' : 'Check your inbox'}</div>
        <h1 className="auth-title serif">
          {lang === 'zh' ? '差一步。' : 'One more step.'}
        </h1>
        <p className="auth-sub">
          {lang === 'zh'
            ? `我們已寄送驗證連結至 ${email}。請點擊連結完成註冊。`
            : `We've emailed a confirmation link to ${email}. Click it to finish setting up your account.`}
        </p>
        <button className="auth-primary" onClick={goSignIn} style={{ marginTop: 24 }}>
          {lang === 'zh' ? '返回登入' : 'Back to sign in'}
        </button>
      </AuthShell>
    );
  }

  return (
    <AuthShell lang={lang} setLang={setLang} onClose={onClose}>
      <div className="auth-eyebrow mono">{lang === 'zh' ? '建立帳戶' : 'Create account'}</div>
      <h1 className="auth-title serif">
        {lang === 'zh' ? '由今天開始。' : 'Start today.'}
      </h1>
      <p className="auth-sub">
        {lang === 'zh' ? '由 NCHK 認可的 13 間機構，118 個課程。' : '118 NCHK-accredited courses from 13 providers — in one place.'}
      </p>

      <form onSubmit={submit} className="auth-form">
        <AuthField label={lang === 'zh' ? '電郵' : 'Email'} type="email"
          value={email} onChange={setEmail} autoFocus autoComplete="email"
          placeholder="you@hospital.hk" />
        <AuthField label={lang === 'zh' ? '密碼' : 'Password'} type="password"
          value={pw} onChange={setPw} autoComplete="new-password"
          placeholder={lang === 'zh' ? '至少 6 位' : 'At least 6 characters'} />
        <AuthField label={lang === 'zh' ? '確認密碼' : 'Confirm password'} type="password"
          value={pw2} onChange={setPw2} autoComplete="new-password"
          placeholder="••••••••" />
        <AuthError msg={err} lang={lang} />
        <button className="auth-primary" type="submit" disabled={busy}>
          {busy ? (lang === 'zh' ? '建立中…' : 'Creating…') : (lang === 'zh' ? '建立帳戶' : 'Create account')}
        </button>
      </form>

      <div className="auth-links">
        <span className="muted-2" style={{ fontSize: 13 }}>
          {lang === 'zh' ? '已有帳戶？' : 'Already have an account?'}
        </span>
        <button className="auth-link" type="button" onClick={goSignIn}>
          {lang === 'zh' ? '登入' : 'Sign in'}
        </button>
      </div>
    </AuthShell>
  );
}

// ── Forgot / reset password ────────────────────────────────────────────────
function ForgotScreen({ lang, setLang, goSignIn, onClose }) {
  const [email, setEmail] = auS('');
  const [busy, setBusy] = auS(false);
  const [err, setErr] = auS('');
  const [sent, setSent] = auS(false);

  const submit = async (e) => {
    e?.preventDefault?.();
    if (!email) return;
    setBusy(true); setErr('');
    const { error } = await AuthAPI.resetPassword(email.trim());
    setBusy(false);
    if (error) return setErr(error.message);
    setSent(true);
  };

  if (sent) {
    return (
      <AuthShell lang={lang} setLang={setLang} onClose={onClose}>
        <div className="auth-eyebrow mono">{lang === 'zh' ? '已寄出' : 'Sent'}</div>
        <h1 className="auth-title serif">
          {lang === 'zh' ? '查看電郵。' : 'Check your inbox.'}
        </h1>
        <p className="auth-sub">
          {lang === 'zh'
            ? `重設連結已寄送至 ${email}。`
            : `A reset link is on its way to ${email}.`}
        </p>
        <button className="auth-primary" onClick={goSignIn} style={{ marginTop: 24 }}>
          {lang === 'zh' ? '返回登入' : 'Back to sign in'}
        </button>
      </AuthShell>
    );
  }

  return (
    <AuthShell lang={lang} setLang={setLang} onClose={onClose}>
      <div className="auth-eyebrow mono">{lang === 'zh' ? '重設密碼' : 'Reset password'}</div>
      <h1 className="auth-title serif">
        {lang === 'zh' ? '沒問題。' : "It happens."}
      </h1>
      <p className="auth-sub">
        {lang === 'zh' ? '輸入電郵，我們會寄出重設連結。' : "Enter your email and we'll send you a reset link."}
      </p>

      <form onSubmit={submit} className="auth-form">
        <AuthField label={lang === 'zh' ? '電郵' : 'Email'} type="email"
          value={email} onChange={setEmail} autoFocus autoComplete="email"
          placeholder="you@hospital.hk" />
        <AuthError msg={err} lang={lang} />
        <button className="auth-primary" type="submit" disabled={busy}>
          {busy ? (lang === 'zh' ? '處理中…' : 'Sending…') : (lang === 'zh' ? '寄出重設連結' : 'Send reset link')}
        </button>
      </form>

      <div className="auth-links">
        <button className="auth-link" type="button" onClick={goSignIn}>
          ← {lang === 'zh' ? '返回登入' : 'Back to sign in'}
        </button>
      </div>
    </AuthShell>
  );
}

// Reset-password-from-link landing (when user clicks recovery email)
function ResetPasswordScreen({ lang, setLang, onDone, onClose }) {
  const [pw, setPw] = auS('');
  const [pw2, setPw2] = auS('');
  const [busy, setBusy] = auS(false);
  const [err, setErr] = auS('');

  const submit = async (e) => {
    e?.preventDefault?.();
    if (pw.length < 6) return setErr(lang === 'zh' ? '密碼最少 6 位' : 'Password must be at least 6 characters');
    if (pw !== pw2)    return setErr(lang === 'zh' ? '兩次輸入的密碼不一致' : "Passwords don't match");
    setBusy(true); setErr('');
    const { error } = await sb.auth.updateUser({ password: pw });
    setBusy(false);
    if (error) return setErr(error.message);
    onDone();
  };

  return (
    <AuthShell lang={lang} setLang={setLang} onClose={onClose}>
      <div className="auth-eyebrow mono">{lang === 'zh' ? '設定新密碼' : 'Set new password'}</div>
      <h1 className="auth-title serif">
        {lang === 'zh' ? '差不多了。' : 'Almost done.'}
      </h1>
      <p className="auth-sub">
        {lang === 'zh' ? '輸入新密碼以繼續。' : 'Pick a new password to continue.'}
      </p>
      <form onSubmit={submit} className="auth-form">
        <AuthField label={lang === 'zh' ? '新密碼' : 'New password'} type="password"
          value={pw} onChange={setPw} autoFocus autoComplete="new-password" />
        <AuthField label={lang === 'zh' ? '確認密碼' : 'Confirm password'} type="password"
          value={pw2} onChange={setPw2} autoComplete="new-password" />
        <AuthError msg={err} lang={lang} />
        <button className="auth-primary" type="submit" disabled={busy}>
          {busy ? (lang === 'zh' ? '處理中…' : 'Saving…') : (lang === 'zh' ? '儲存並登入' : 'Save and continue')}
        </button>
      </form>
    </AuthShell>
  );
}

// ── Auth router ─────────────────────────────────────────────────────────────
function AuthRouter({ lang, setLang, initialMode = 'signin', onClose }) {
  const [mode, setMode] = auS(initialMode);
  const shellProps = { lang, setLang, onClose };
  if (mode === 'signin')  return <SignInScreen {...shellProps} goSignUp={() => setMode('signup')} goForgot={() => setMode('forgot')} />;
  if (mode === 'signup')  return <SignUpScreen {...shellProps} goSignIn={() => setMode('signin')} />;
  if (mode === 'forgot')  return <ForgotScreen {...shellProps} goSignIn={() => setMode('signin')} />;
  if (mode === 'reset')   return <ResetPasswordScreen {...shellProps} onDone={() => setMode('signin')} />;
  return null;
}

Object.assign(window, { AuthRouter, SignInScreen, SignUpScreen, ForgotScreen, ResetPasswordScreen });
