// auth-modal.jsx — Login + Signup modal (student role only here).
// Instructor signup uses the BecomeInstructor page for the longer form.

const AuthModal = ({ mode: initialMode = 'login', onClose, onSuccess, openBecomeInstructor }) => {
  const [mode, setMode] = React.useState(initialMode); // 'login' | 'signup'
  const [email, setEmail] = React.useState('');
  const [password, setPassword] = React.useState('');
  const [fullName, setFullName] = React.useState('');
  const [city, setCity] = React.useState('');
  const [state, setState] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [success, setSuccess] = React.useState(null);
  const captcha = window.useCaptcha ? window.useCaptcha() : { token: null, widget: null, required: false };

  const submit = async (e) => {
    e.preventDefault();
    setError(null); setSuccess(null); setBusy(true);
    try {
      if (captcha.required) { setError('Please complete the captcha.'); return; }
      if (mode === 'login') {
        const { error } = await window.AUTH.signIn({ email, password, captchaToken: captcha.token });
        captcha.reset && captcha.reset();
        if (error) { setError(window.friendlyError(error)); return; }
        onSuccess && onSuccess();
        onClose();
      } else {
        if (!fullName.trim()) { setError('Please enter your name.'); return; }
        const { error } = await window.AUTH.signUpStudent({ email, password, fullName, city, state, captchaToken: captcha.token });
        captcha.reset && captcha.reset();
        if (error) { setError(window.friendlyError(error)); return; }
        setSuccess('Account created! Check your email to confirm, then log in.');
        setMode('login');
      }
    } finally {
      setBusy(false);
    }
  };

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(15,20,40,0.55)',
      backdropFilter: 'blur(6px)', zIndex: 1000,
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 20,
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: '100%', maxWidth: 440, background: '#fff', borderRadius: 18,
        padding: 36, boxShadow: '0 20px 60px rgba(0,0,0,0.25)',
        fontFamily: "'Plus Jakarta Sans', sans-serif",
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 20 }}>
          <div>
            <div style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 12, fontWeight: 700, letterSpacing: '0.14em', color: 'oklch(72% 0.17 80)', textTransform: 'uppercase', marginBottom: 6 }}>
              {mode === 'login' ? 'Welcome back' : 'Join Coaching'}
            </div>
            <h2 style={{ fontFamily: "'Cormorant Garamond', serif", fontSize: 28, fontWeight: 600, color: 'oklch(22% 0.06 265)', lineHeight: 1.15 }}>
              {mode === 'login' ? 'Sign in to your account' : 'Create your account'}
            </h2>
          </div>
          <button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'oklch(55% 0.03 265)', fontSize: 24, lineHeight: 1 }}>×</button>
        </div>

        <form onSubmit={submit}>
          {mode === 'signup' && (
            <Field label="Full name">
              <input type="text" required value={fullName} onChange={e => setFullName(e.target.value)} style={inputStyle} placeholder="Jane Doe" />
            </Field>
          )}
          <Field label="Email">
            <input type="email" required value={email} onChange={e => setEmail(e.target.value)} style={inputStyle} placeholder="you@example.com" />
          </Field>
          <Field label="Password">
            <input type="password" required minLength={6} value={password} onChange={e => setPassword(e.target.value)} style={inputStyle} placeholder="at least 6 characters" />
          </Field>
          {mode === 'signup' && (
            <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 12 }}>
              <Field label="City (optional)">
                <input type="text" value={city} onChange={e => setCity(e.target.value)} style={inputStyle} placeholder="Austin" />
              </Field>
              <Field label="State">
                <input type="text" value={state} onChange={e => setState(e.target.value)} style={inputStyle} placeholder="TX" maxLength={2} />
              </Field>
            </div>
          )}

          {captcha.widget}

          {error && <div style={errorBox}>{error}</div>}
          {success && <div style={successBox}>{success}</div>}

          <button type="submit" disabled={busy || captcha.required} style={{
            width: '100%', background: 'oklch(22% 0.06 265)', color: '#fff',
            border: 'none', borderRadius: 10, padding: '13px 0',
            fontWeight: 600, fontSize: 15, cursor: busy ? 'wait' : 'pointer',
            fontFamily: "'Plus Jakarta Sans', sans-serif",
            opacity: busy ? 0.7 : 1, marginTop: 8,
          }}>
            {busy ? 'Please wait…' : mode === 'login' ? 'Sign In' : 'Create Account'}
          </button>
        </form>

        <div style={{ textAlign: 'center', marginTop: 20, fontSize: 13, color: 'oklch(48% 0.03 265)' }}>
          {mode === 'login' ? (
            <>New to Coaching? <button type="button" onClick={() => { setMode('signup'); setError(null); setSuccess(null); }} style={linkBtn}>Create an account</button></>
          ) : (
            <>Already have an account? <button type="button" onClick={() => { setMode('login'); setError(null); setSuccess(null); }} style={linkBtn}>Sign in</button></>
          )}
        </div>

        <div style={{ borderTop: '1px solid oklch(92% 0.01 265)', marginTop: 20, paddingTop: 16, textAlign: 'center', fontSize: 13, color: 'oklch(48% 0.03 265)' }}>
          Want to teach on Coaching?{' '}
          <button type="button" onClick={() => { onClose(); openBecomeInstructor && openBecomeInstructor(); }} style={linkBtn}>
            Become an instructor
          </button>
        </div>
      </div>
    </div>
  );
};

const Field = ({ label, children }) => (
  <div style={{ marginBottom: 14 }}>
    <label style={{ display: 'block', fontSize: 12, fontWeight: 600, color: 'oklch(38% 0.04 265)', marginBottom: 6, letterSpacing: '0.02em' }}>{label}</label>
    {children}
  </div>
);

const inputStyle = {
  width: '100%', padding: '11px 14px',
  border: '1.5px solid oklch(88% 0.01 265)', borderRadius: 10,
  fontSize: 14, fontFamily: "'Plus Jakarta Sans', sans-serif",
  outline: 'none', transition: 'border-color 0.15s',
};

const errorBox = {
  background: 'oklch(96% 0.03 25)', color: 'oklch(40% 0.15 25)',
  padding: '10px 14px', borderRadius: 8, fontSize: 13, marginBottom: 12,
  border: '1px solid oklch(88% 0.06 25)',
};

const successBox = {
  background: 'oklch(96% 0.04 158)', color: 'oklch(32% 0.1 155)',
  padding: '10px 14px', borderRadius: 8, fontSize: 13, marginBottom: 12,
  border: '1px solid oklch(88% 0.06 155)',
};

const linkBtn = {
  background: 'none', border: 'none', cursor: 'pointer',
  color: 'oklch(22% 0.06 265)', fontWeight: 600, textDecoration: 'underline',
  fontFamily: "'Plus Jakarta Sans', sans-serif", fontSize: 13, padding: 0,
};

window.AuthModal = AuthModal;
