// WeWire admin — email + password sign in / sign up / reset.

const adminInputStyle = {
  width: '100%', height: 48, borderRadius: 12, border: `1px solid ${T.lineStrong}`,
  padding: '0 14px', fontFamily: FONT, fontSize: 15, color: T.ink, background: T.white,
  boxSizing: 'border-box', outline: 'none',
};

function AdminField({ label, children, hint }) {
  return (
    <label style={{ display: 'block', marginBottom: 16 }}>
      <div style={{ fontSize: 13, fontWeight: 600, color: T.muted, marginBottom: 7 }}>{label}</div>
      {children}
      {hint && <div style={{ fontSize: 12, color: T.subtle, marginTop: 6, lineHeight: 1.45 }}>{hint}</div>}
    </label>
  );
}

function AdminLogin({ onAuthenticated, error: bootError }) {
  const [mode, setMode] = React.useState('signin');
  const [email, setEmail] = React.useState(() => localStorage.getItem('ww_admin_email') || '');
  const [password, setPassword] = React.useState('');
  const [confirm, setConfirm] = React.useState('');
  const [newPassword, setNewPassword] = React.useState('');
  const [loading, setLoading] = React.useState(false);
  const [error, setError] = React.useState(bootError || '');
  const [notice, setNotice] = React.useState('');
  const [bootstrapping, setBootstrapping] = React.useState(true);
  const [supabaseReady, setSupabaseReady] = React.useState(() => window.WWSupabase?.enabled());

  React.useEffect(() => {
    let cancelled = false;
    (async () => {
      if (window.WWSupabase?.enabled()) {
        if (!cancelled) {
          setSupabaseReady(true);
          setBootstrapping(false);
        }
        return;
      }
      try {
        const ok = await window.WWSupabase?.bootstrapFromServer?.();
        if (!cancelled) setSupabaseReady(!!ok);
      } catch (_) {
        if (!cancelled) setSupabaseReady(false);
      } finally {
        if (!cancelled) setBootstrapping(false);
      }
    })();
    return () => { cancelled = true; };
  }, []);

  const isRecovery = typeof window !== 'undefined'
    && (/type=recovery|access_token=/.test(window.location.hash)
      || new URLSearchParams(window.location.search).has('reset_token'));

  React.useEffect(() => {
    if (isRecovery) setMode('reset');
  }, [isRecovery]);

  React.useEffect(() => {
    if (!supabaseReady) return undefined;
    const client = window.WWSupabase?.getClient?.();
    if (!client) return undefined;

    const { data: { subscription } } = client.auth.onAuthStateChange((event) => {
      if (event === 'PASSWORD_RECOVERY') setMode('reset');
    });

    const params = new URLSearchParams(window.location.search);
    const hash = window.location.hash || '';
    const looksLikeRecovery = params.get('reset_token')
      || params.get('code')
      || (/type=recovery/.test(hash) && /access_token=/.test(hash));

    if (looksLikeRecovery && window.WWAdmin?.establishRecoverySession) {
      WWAdmin.establishRecoverySession()
        .then(() => setMode('reset'))
        .catch((err) => setError(err.message || 'Could not open reset link.'));
    }

    return () => subscription.unsubscribe();
  }, [supabaseReady]);

  const switchMode = (next) => {
    setMode(next);
    setError('');
    setNotice('');
    setPassword('');
    setConfirm('');
    setNewPassword('');
    if (next !== 'reset' && window.location.hash) {
      window.history.replaceState({}, '', window.location.pathname);
    }
  };

  const finishAuth = async () => {
    const access = await WWAdmin.checkAdminAccess();
    if (!access.ok) {
      await WWAdmin.signOut();
      if (access.reason === 'not_allowlisted') {
        throw new Error('This email is not on the recruiting allowlist. Contact your team admin to get access.');
      }
      throw new Error('Could not verify dashboard access.');
    }
    if (email.trim()) localStorage.setItem('ww_admin_email', email.trim().toLowerCase());
    onAuthenticated && onAuthenticated(access);
  };

  const submitSignIn = async (e) => {
    e?.preventDefault();
    setError('');
    setNotice('');
    setLoading(true);
    try {
      await WWAdmin.signInWithPassword(email, password);
      await finishAuth();
    } catch (err) {
      setError(err.message || 'Sign-in failed.');
    } finally {
      setLoading(false);
    }
  };

  const submitSignUp = async (e) => {
    e?.preventDefault();
    setError('');
    setNotice('');
    if (password.length < 8) {
      setError('Password must be at least 8 characters.');
      return;
    }
    if (password !== confirm) {
      setError('Passwords do not match.');
      return;
    }
    setLoading(true);
    try {
      await WWAdmin.signUp(email, password);
      setNotice('Account created. Signing you in…');
      await WWAdmin.signInWithPassword(email, password);
      await finishAuth();
    } catch (err) {
      setError(err.message || 'Sign-up failed.');
    } finally {
      setLoading(false);
    }
  };

  const submitForgot = async (e) => {
    e?.preventDefault();
    setError('');
    setNotice('');
    setLoading(true);
    try {
      await WWAdmin.requestPasswordReset(email);
      setNotice('If that email is registered, we sent a reset link. Check your inbox.');
    } catch (err) {
      setError(err.message || 'Could not send reset email.');
    } finally {
      setLoading(false);
    }
  };

  const submitReset = async (e) => {
    e?.preventDefault();
    setError('');
    setNotice('');
    if (newPassword.length < 8) {
      setError('Password must be at least 8 characters.');
      return;
    }
    if (newPassword !== confirm) {
      setError('Passwords do not match.');
      return;
    }
    setLoading(true);
    try {
      await WWAdmin.updatePassword(newPassword);
      window.history.replaceState({}, '', window.location.pathname);
      setNotice('Password updated. Signing you in…');
      await finishAuth();
    } catch (err) {
      setError(err.message || 'Could not update password.');
    } finally {
      setLoading(false);
    }
  };

  const titles = {
    signin: 'Sign in',
    signup: 'Create your account',
    forgot: 'Reset password',
    reset: 'Choose a new password',
  };

  const hints = {
    signin: 'Access is limited to recruiting staff on the allowlist.',
    signup: 'Only emails on the WeWire recruiting allowlist can register. Use the work email you were added with.',
    forgot: 'Enter your work email. We will send a link to reset your password.',
    reset: 'Set a new password for your team account.',
  };

  return (
    <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center',
      background: T.ink, padding: 32, boxSizing: 'border-box' }}>
      <div style={{ width: '100%', maxWidth: 420, background: T.cream, borderRadius: 24, padding: '40px 36px',
        boxShadow: '0 40px 100px rgba(0,0,0,0.35)' }}>
        <img src="/assets/wewire-logo-ink.svg" alt="WeWire" style={{ height: 28, display: 'block', marginBottom: 28 }} />
        <Eyebrow>Team dashboard</Eyebrow>
        <h1 style={{ fontFamily: DISP, fontWeight: 600, fontSize: 28, letterSpacing: '-0.02em', margin: '10px 0 12px' }}>
          {titles[mode]}
        </h1>
        <p style={{ fontSize: 15, color: T.muted, lineHeight: 1.55, marginBottom: 22 }}>{hints[mode]}</p>

        {mode === 'signin' || mode === 'signup' ? (
          <div style={{ display: 'flex', gap: 8, marginBottom: 22, background: T.sand, borderRadius: 12, padding: 4 }}>
            {[['signin', 'Sign in'], ['signup', 'Sign up']].map(([k, label]) => (
              <button key={k} type="button" onClick={() => switchMode(k)} style={{
                flex: 1, height: 40, border: 'none', borderRadius: 9, cursor: 'pointer', fontFamily: FONT,
                fontSize: 14, fontWeight: 600,
                background: mode === k ? T.white : 'transparent',
                color: mode === k ? T.ink : T.muted,
                boxShadow: mode === k ? '0 1px 4px rgba(27,24,19,0.08)' : 'none',
              }}>{label}</button>
            ))}
          </div>
        ) : null}

        {!bootstrapping && !supabaseReady && (
          <Card pad={14} style={{ background: T.orangeSoft, border: 'none', marginBottom: 18 }}>
            <div style={{ fontSize: 13, color: T.orangeDeep, lineHeight: 1.45 }}>
              {window.WW_DEV
                ? <>Supabase is not configured locally. Run <b>npm start</b> with keys in <code>.env</code>.</>
                : <>Supabase keys are missing on Render. Open <b>Render → wewire-grad-2026 → Environment</b>, add <code>SUPABASE_URL</code>, <code>SUPABASE_ANON_KEY</code>, and <code>SUPABASE_SERVICE_ROLE_KEY</code> from your project <code>.env</code>, save, then <b>Manual Deploy</b>. Or run <code>./scripts/push-render-env.sh</code> after <code>render login</code>.</>}
            </div>
          </Card>
        )}
        {bootstrapping && (
          <Card pad={14} style={{ background: T.sand, border: 'none', marginBottom: 18 }}>
            <div style={{ fontSize: 13, color: T.muted }}>Checking server configuration…</div>
          </Card>
        )}

        {error && (
          <Card pad={14} style={{ background: T.redSoft, border: 'none', marginBottom: 18 }}>
            <div style={{ fontSize: 13, color: T.red, lineHeight: 1.45 }}>{error}</div>
          </Card>
        )}
        {notice && (
          <Card pad={14} style={{ background: T.greenSoft, border: 'none', marginBottom: 18 }}>
            <div style={{ fontSize: 13, color: T.green, lineHeight: 1.45 }}>{notice}</div>
          </Card>
        )}

        {mode === 'signup' && (
          <Card pad={14} style={{ background: T.sand, border: 'none', marginBottom: 18 }}>
            <div style={{ fontSize: 13, color: T.muted, lineHeight: 1.5 }}>
              <b>New here?</b> Your work email must be added to the access list by a team admin before you can register.
            </div>
          </Card>
        )}

        {mode === 'signin' && (
          <form onSubmit={submitSignIn}>
            <AdminField label="Work email">
              <input type="email" value={email} onChange={(e) => setEmail(e.target.value)}
                autoComplete="email" placeholder="you@wewire.com" required style={adminInputStyle} disabled={bootstrapping} />
            </AdminField>
            <AdminField label="Password">
              <input type="password" value={password} onChange={(e) => setPassword(e.target.value)}
                autoComplete="current-password" required style={adminInputStyle} disabled={bootstrapping} />
            </AdminField>
            <div style={{ textAlign: 'right', marginBottom: 14 }}>
              <button type="button" onClick={() => switchMode('forgot')} style={{
                background: 'none', border: 'none', cursor: 'pointer', fontFamily: FONT, fontSize: 13,
                color: T.muted, textDecoration: 'underline', padding: 0,
              }}>Forgot password?</button>
            </div>
            <Btn variant="primary" full type="submit" disabled={loading || bootstrapping || !email.trim() || !password} icon="arrow">
              {loading ? 'Signing in…' : 'Sign in'}
            </Btn>
          </form>
        )}

        {mode === 'signup' && (
          <form onSubmit={submitSignUp}>
            <AdminField label="Work email">
              <input type="email" value={email} onChange={(e) => setEmail(e.target.value)}
                autoComplete="email" placeholder="you@wewire.com" required style={adminInputStyle} disabled={bootstrapping || !supabaseReady} />
            </AdminField>
            <AdminField label="Password" hint="At least 8 characters">
              <input type="password" value={password} onChange={(e) => setPassword(e.target.value)}
                autoComplete="new-password" required minLength={8} style={adminInputStyle} disabled={bootstrapping || !supabaseReady} />
            </AdminField>
            <AdminField label="Confirm password">
              <input type="password" value={confirm} onChange={(e) => setConfirm(e.target.value)}
                autoComplete="new-password" required minLength={8} style={adminInputStyle} disabled={bootstrapping || !supabaseReady} />
            </AdminField>
            <Btn variant="primary" full type="submit" disabled={loading || !supabaseReady || !email.trim() || !password} icon="arrow">
              {loading ? 'Creating account…' : 'Create account'}
            </Btn>
          </form>
        )}

        {mode === 'forgot' && (
          <form onSubmit={submitForgot}>
            <AdminField label="Work email">
              <input type="email" value={email} onChange={(e) => setEmail(e.target.value)}
                autoComplete="email" placeholder="you@wewire.com" required style={adminInputStyle} disabled={bootstrapping} />
            </AdminField>
            <Btn variant="primary" full type="submit" disabled={loading || bootstrapping || !email.trim()} icon="arrow">
              {loading ? 'Sending…' : 'Send reset link'}
            </Btn>
            <div style={{ textAlign: 'center', marginTop: 16 }}>
              <button type="button" onClick={() => switchMode('signin')} style={{
                background: 'none', border: 'none', cursor: 'pointer', fontFamily: FONT, fontSize: 13, color: T.muted,
              }}>← Back to sign in</button>
            </div>
          </form>
        )}

        {mode === 'reset' && (
          <form onSubmit={submitReset}>
            <AdminField label="New password" hint="At least 8 characters">
              <input type="password" value={newPassword} onChange={(e) => setNewPassword(e.target.value)}
                autoComplete="new-password" required minLength={8} style={adminInputStyle} disabled={bootstrapping || !supabaseReady} />
            </AdminField>
            <AdminField label="Confirm new password">
              <input type="password" value={confirm} onChange={(e) => setConfirm(e.target.value)}
                autoComplete="new-password" required minLength={8} style={adminInputStyle} disabled={bootstrapping || !supabaseReady} />
            </AdminField>
            <Btn variant="primary" full type="submit" disabled={loading || bootstrapping || !newPassword} icon="check">
              {loading ? 'Saving…' : 'Update password'}
            </Btn>
          </form>
        )}

        {mode !== 'forgot' && mode !== 'reset' && (
          <div style={{ textAlign: 'center', marginTop: 20 }}>
            <a href={WWPaths.program()} style={{ fontSize: 13, color: T.muted, textDecoration: 'none' }}>← Back to program site</a>
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { AdminLogin });
