// reset.jsx — Branded password-reset action handler.
//
// Mounted by AuthGate when the URL carries ?mode=resetPassword&oobCode=...
// Verifies the code, lets the user set a new password (≥10 chars), then
// auto-signs them in. On any unrecoverable error we hand off to the Login
// screen via sessionStorage flags + a clean reload.

function ResetPassword({ oobCode }) {
  const [phase,    setPhase]    = React.useState('verifying'); // verifying | ready | submitting | invalid
  const [email,    setEmail]    = React.useState('');
  const [password, setPassword] = React.useState('');
  const [showPw,   setShowPw]   = React.useState(false);
  const [touched,  setTouched]  = React.useState(false);
  const [err,      setErr]      = React.useState('');

  React.useEffect(() => {
    let cancelled = false;
    firebase.auth().verifyPasswordResetCode(oobCode)
      .then((em) => {
        if (cancelled) return;
        setEmail(em);
        setPhase('ready');
      })
      .catch((e) => {
        if (cancelled) return;
        console.warn('[norwill] verifyPasswordResetCode failed', e);
        setPhase('invalid');
      });
    return () => { cancelled = true; };
  }, [oobCode]);

  const submit = async (e) => {
    e.preventDefault();
    setErr('');
    setTouched(true);
    if (password.length < 10) {
      setErr('Password must be at least 10 characters.');
      return;
    }
    setPhase('submitting');
    try {
      await firebase.auth().confirmPasswordReset(oobCode, password);
    } catch (error) {
      if (error.code === 'auth/expired-action-code' || error.code === 'auth/invalid-action-code') {
        setPhase('invalid');
        return;
      }
      if (error.code === 'auth/weak-password') {
        setErr('Password is too weak. Use at least 10 characters.');
        setPhase('ready');
        return;
      }
      console.warn('[norwill] confirmPasswordReset failed', error);
      setErr("Couldn't set your password — try again.");
      setPhase('ready');
      return;
    }

    try {
      await firebase.auth().signInWithEmailAndPassword(email, password);
    } catch (error) {
      console.warn('[norwill] auto-signin after reset failed', error);
      try { sessionStorage.setItem('norwill-prefill-email-v1', email); } catch {}
    }
    // Reload to a clean URL. If signin succeeded, AuthGate lands the dashboard.
    // If it failed, AuthGate falls through to Login, which picks up the prefilled email.
    window.location.replace('/');
  };

  const requestNewLink = () => {
    try { sessionStorage.setItem('norwill-start-in-reset-mode', '1'); } catch {}
    window.location.replace('/');
  };

  const inputStyle = {
    padding: '11px 13px',
    border: '1px solid var(--line-strong)',
    borderRadius: 10,
    fontSize: 14,
    background: 'var(--card-alt)',
    color: 'var(--ink-900)',
    width: '100%',
    boxSizing: 'border-box',
  };
  const labelStyle = { display: 'flex', flexDirection: 'column', gap: 6 };
  const labelTextStyle = {
    fontSize: 11, fontWeight: 600, textTransform: 'uppercase',
    letterSpacing: 0.08, color: 'var(--ink-600)',
  };

  const Shell = ({ children }) => (
    <div className="brand-wash" style={{
      minHeight: '100vh',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 24,
    }}>
      <div className="slide-up" style={{
        width: '100%', maxWidth: 420,
        background: 'var(--card)',
        border: '1px solid var(--line)',
        borderRadius: 18,
        boxShadow: 'var(--shadow-md)',
        padding: '36px 32px 28px',
      }}>
        <div style={{
          display: 'flex', flexDirection: 'column', alignItems: 'center',
          gap: 10, marginBottom: 24,
        }}>
          <img src="Logo.png" alt="Norwill" style={{ width: 112, height: 112, objectFit: 'contain' }}/>
          <div style={{
            fontSize: 11, letterSpacing: 0.14, textTransform: 'uppercase',
            color: 'var(--brand-700)', fontWeight: 700,
          }}>Scorecard OS</div>
        </div>
        {children}
      </div>
    </div>
  );

  if (phase === 'verifying') {
    return (
      <Shell>
        <div style={{ textAlign: 'center', color: 'var(--ink-500)', fontSize: 14, padding: '8px 0 4px' }}>
          Verifying your link…
        </div>
      </Shell>
    );
  }

  if (phase === 'invalid') {
    return (
      <Shell>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
          <div>
            <div style={{ fontSize: 18, fontWeight: 600, color: 'var(--ink-900)', marginBottom: 6 }}>
              This link can't be used
            </div>
            <p style={{ margin: 0, fontSize: 13.5, color: 'var(--ink-600)', lineHeight: 1.55 }}>
              It has expired or has already been used. Reset links are valid for 1 hour.
            </p>
          </div>
          <button onClick={requestNewLink} style={{
            padding: '12px 14px', border: 'none', borderRadius: 10,
            background: 'linear-gradient(135deg, var(--brand-700), var(--brand-500))',
            color: '#fff', fontSize: 14, fontWeight: 600, letterSpacing: 0.02,
            cursor: 'pointer',
            boxShadow: '0 4px 14px rgba(11, 106, 116, 0.28)',
          }}>
            Request a new link
          </button>
        </div>
      </Shell>
    );
  }

  const busy = phase === 'submitting';
  const tooShort = touched && password.length > 0 && password.length < 10;

  return (
    <Shell>
      <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div>
          <div style={{ fontSize: 18, fontWeight: 600, color: 'var(--ink-900)', marginBottom: 4 }}>
            Set your password
          </div>
          <div style={{ fontSize: 13, color: 'var(--ink-500)' }}>for {email}</div>
        </div>

        <label style={labelStyle}>
          <span style={labelTextStyle}>New password</span>
          <div style={{ position: 'relative' }}>
            <input
              autoFocus
              type={showPw ? 'text' : 'password'}
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              onBlur={() => setTouched(true)}
              autoComplete="new-password"
              placeholder="At least 10 characters"
              required
              disabled={busy}
              style={{ ...inputStyle, paddingRight: 64 }}
            />
            <button
              type="button"
              onClick={() => setShowPw((s) => !s)}
              tabIndex={-1}
              style={{
                position: 'absolute', right: 8, top: '50%', transform: 'translateY(-50%)',
                background: 'none', border: 'none', padding: '4px 8px',
                fontSize: 11, fontWeight: 600, letterSpacing: 0.06, textTransform: 'uppercase',
                color: 'var(--ink-500)', cursor: 'pointer',
              }}
            >{showPw ? 'Hide' : 'Show'}</button>
          </div>
          <div style={{
            fontSize: 12,
            color: tooShort ? 'var(--bad)' : 'var(--ink-500)',
            marginTop: 2,
          }}>
            At least 10 characters
          </div>
        </label>

        {err && (
          <div style={{
            padding: '9px 12px', background: 'var(--bad-bg)', color: 'var(--bad)',
            borderRadius: 9, fontSize: 12.5, fontWeight: 500,
          }}>{err}</div>
        )}

        <button type="submit" disabled={busy} style={{
          marginTop: 4, padding: '12px 14px', border: 'none', borderRadius: 10,
          background: 'linear-gradient(135deg, var(--brand-700), var(--brand-500))',
          color: '#fff', fontSize: 14, fontWeight: 600, letterSpacing: 0.02,
          cursor: busy ? 'wait' : 'pointer', opacity: busy ? 0.75 : 1,
          boxShadow: '0 4px 14px rgba(11, 106, 116, 0.28)',
        }}>
          {busy ? 'Setting password…' : 'Set password & sign in'}
        </button>
      </form>
    </Shell>
  );
}

Object.assign(window, { ResetPassword });
