// Signup flow — public onboarding (account + grade), then hand off to Keycloak sign-in.

const REGIONS = ['Addis Ababa', 'Oromia', 'Amhara', 'Tigray', 'SNNPR', 'Afar', 'Somali', 'Benishangul-Gumuz', 'Gambella', 'Harari', 'Dire Dawa'];
const STREAMS = [
  { value: 'natural', label: 'Natural' },
  { value: 'social', label: 'Social' },
];

const STEPS = ['Account', 'School & Grade'];

const EMAIL_RE = /^[^@\s]+@[^@\s]+\.[^@\s]+$/;

const SU_LABEL_STYLE = { fontSize: 12, fontWeight: 700, color: BRAND.muted, letterSpacing: 0.4, marginBottom: 5, display: 'block', textTransform: 'uppercase' };
const SU_FIELD_STYLE = { display: 'flex', flexDirection: 'column', gap: 4 };
const SU_ERR_STYLE = { fontSize: 11.5, color: '#c0392b', marginTop: 2, fontWeight: 600 };
const suInputStyle = (err) => ({
  width: '100%', padding: '11px 14px', borderRadius: 8,
  border: `1.5px solid ${err ? '#c0392b' : BRAND.border}`,
  fontFamily: 'Plus Jakarta Sans, sans-serif', fontSize: 14, outline: 'none',
  boxSizing: 'border-box', color: BRAND.text, background: '#fff',
});

// Module-level so its identity is stable across renders (nested components would
// remount the inputs on every keystroke and drop focus).
function SignupField({ label, error, children }) {
  return (
    <div style={SU_FIELD_STYLE}>
      <label style={SU_LABEL_STYLE}>{label}</label>
      {children}
      {error && <span style={SU_ERR_STYLE}>{error}</span>}
    </div>
  );
}

function Signup({
  navigate,
  onGoogle,
  onComplete,
  onSignIn,
  setEnrolledGrade,
  authBusy = false,
  authError = '',
  authFieldErrors = null,
  signupSuccess = false,
  openedxSync = null,
}) {
  const [step, setStep] = React.useState(0);
  const [form, setForm] = React.useState({
    firstName: '', lastName: '', email: '', phone: '',
    password: '', confirmPassword: '',
    school: '', region: '', grade: '', stream: '',
    subjects: [],
  });
  const [errors, setErrors] = React.useState({});

  const set = (key, val) => {
    setForm(f => ({ ...f, [key]: val }));
    // Clear a field's error as soon as the user edits it.
    setErrors(e => (e[key] ? { ...e, [key]: undefined } : e));
  };

  // Merge server-side field errors (e.g. "email already registered") with local ones.
  const fieldError = (key) => errors[key] || (authFieldErrors && authFieldErrors[key]) || '';
  const resetEmail = form.email.trim();
  const forgotPasswordHref = `${authUrl('/auth/forgot-password/keycloak')}${resetEmail ? `?login_hint=${encodeURIComponent(resetEmail)}` : ''}`;

  const validateStep = (current) => {
    const e = {};
    if (current === 0) {
      if (!form.firstName.trim()) e.firstName = 'First name is required.';
      if (!form.lastName.trim()) e.lastName = 'Last name is required.';
      if (!EMAIL_RE.test(form.email.trim())) e.email = 'Enter a valid email address.';
      const digits = form.phone.replace(/[^\d]/g, '');
      if (!form.phone.trim()) e.phone = 'Phone number is required.';
      else if (digits.length < 9) e.phone = 'Enter a valid phone number.';
      if (form.password.length < 8) e.password = 'Use at least 8 characters.';
      else if (!(/[A-Za-z]/.test(form.password) && /\d/.test(form.password))) e.password = 'Include both letters and numbers.';
      if (form.password !== form.confirmPassword) e.confirmPassword = 'Passwords do not match.';
    }
    if (current === 1) {
      if (!form.grade) e.grade = 'Select your grade.';
      if ((String(form.grade) === '11' || String(form.grade) === '12') && !form.stream) {
        e.stream = 'Select Natural or Social stream.';
      }
    }
    setErrors(e);
    return Object.keys(e).length === 0;
  };

  const submitProfile = async () => {
    if (!validateStep(1)) return;
    try {
      if (onComplete) await onComplete(form);
    } catch (err) {
      // App-level error (and any field errors) are surfaced via props.
    }
  };

  const next = () => {
    if (step === STEPS.length - 1) {
      submitProfile();
      return;
    }
    if (validateStep(step)) setStep(s => Math.min(s + 1, STEPS.length - 1));
  };
  const back = () => setStep(s => Math.max(s - 1, 0));

  const inputStyle = suInputStyle;

  // ---- Success state: shown briefly before the redirect to Keycloak sign-in ----
  if (signupSuccess) {
    return (
      <Card style={{ padding: '40px 30px', textAlign: 'center', maxWidth: 440, margin: '0 auto' }}>
        <div style={{ fontSize: 52, marginBottom: 12 }}>🎉</div>
        <h2 style={{ fontFamily: 'Playfair Display, Georgia, serif', fontSize: 24, margin: '0 0 8px', color: BRAND.dark }}>Account created!</h2>
        <p style={{ color: BRAND.muted, fontSize: 14, margin: '0 0 22px', lineHeight: 1.5 }}>
          Taking you to the secure sign-in to finish setting up your learning access&hellip;
        </p>
        <div style={{ display: 'flex', justifyContent: 'center' }}>
          <div style={{
            width: 26, height: 26, borderRadius: '50%',
            border: `3px solid ${BRAND.border}`, borderTopColor: BRAND.primary,
            animation: 'mm-spin 0.8s linear infinite',
          }} />
        </div>
        <style>{'@keyframes mm-spin { to { transform: rotate(360deg); } }'}</style>
      </Card>
    );
  }

  return (
    <div style={{ fontFamily: 'Plus Jakarta Sans, sans-serif', color: BRAND.text, maxWidth: 560, margin: '0 auto' }}>
      {/* Header */}
      <div style={{ textAlign: 'center', marginBottom: 22 }}>
        <h1 style={{ fontFamily: 'Playfair Display, Georgia, serif', fontSize: 28, margin: '0 0 6px', color: BRAND.dark }}>Create your account</h1>
        <p style={{ color: BRAND.muted, fontSize: 14, margin: 0 }}>Join thousands of Ethiopian students on MyMarian</p>
      </div>

      {/* Quick demo signup */}
      {step === 0 && onGoogle && (
        <Card style={{ padding: '18px 20px', marginBottom: 18 }}>
          <div style={{ fontWeight: 800, fontSize: 13.5, color: BRAND.dark, marginBottom: 8 }}>Just exploring?</div>
          <GoogleSignInButton onClick={() => onGoogle && onGoogle()} label="Try a demo account" />
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 14 }}>
            <div style={{ flex: 1, height: 1, background: BRAND.border }} />
            <span style={{ fontSize: 10, color: BRAND.muted, fontWeight: 700, letterSpacing: 1 }}>OR REGISTER</span>
            <div style={{ flex: 1, height: 1, background: BRAND.border }} />
          </div>
        </Card>
      )}

      {/* Step indicators */}
      <div style={{ display: 'flex', marginBottom: 28, position: 'relative' }}>
        <div style={{ position: 'absolute', top: 16, left: '25%', right: '25%', height: 2, background: BRAND.border, zIndex: 0 }} />
        <div style={{ position: 'absolute', top: 16, left: '25%', width: `${(step / (STEPS.length - 1)) * 50}%`, height: 2, background: BRAND.primary, zIndex: 1, transition: 'width 0.4s' }} />
        {STEPS.map((s, i) => (
          <div key={s} style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8, position: 'relative', zIndex: 2 }}>
            <div style={{
              width: 32, height: 32, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center',
              background: i <= step ? BRAND.primary : '#fff',
              border: `2px solid ${i <= step ? BRAND.primary : BRAND.border}`,
              color: i <= step ? '#fff' : BRAND.muted,
              fontWeight: 700, fontSize: 13, transition: 'all 0.3s',
            }}>
              {i < step ? '✓' : i + 1}
            </div>
            <span style={{ fontSize: 11.5, fontWeight: i === step ? 700 : 400, color: i === step ? BRAND.primary : BRAND.muted }}>{s}</span>
          </div>
        ))}
      </div>

      <Card style={{ padding: '28px 26px' }}>
        {/* Step 0: Account */}
        {step === 0 && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
            <h3 style={{ margin: '0 0 4px', fontFamily: 'Playfair Display, Georgia, serif', fontSize: 18 }}>Your details</h3>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              <SignupField label="First name" error={fieldError('firstName')}>
                <input style={inputStyle(fieldError('firstName'))} value={form.firstName} onChange={e => set('firstName', e.target.value)} placeholder="Selamawit" autoComplete="given-name" />
              </SignupField>
              <SignupField label="Last name" error={fieldError('lastName')}>
                <input style={inputStyle(fieldError('lastName'))} value={form.lastName} onChange={e => set('lastName', e.target.value)} placeholder="Tadesse" autoComplete="family-name" />
              </SignupField>
            </div>
            <SignupField label="Email address" error={fieldError('email')}>
              <input style={inputStyle(fieldError('email'))} type="email" value={form.email} onChange={e => set('email', e.target.value)} placeholder="selamawit@example.com" autoComplete="email" />
            </SignupField>
            <SignupField label="Phone number (TeleBirr / CBE)" error={fieldError('phone')}>
              <input style={inputStyle(fieldError('phone'))} value={form.phone} onChange={e => set('phone', e.target.value)} placeholder="+251 9XX XXX XXX" autoComplete="tel" />
            </SignupField>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              <SignupField label="Password" error={fieldError('password')}>
                <input style={inputStyle(fieldError('password'))} type="password" value={form.password} onChange={e => set('password', e.target.value)} placeholder="8+ letters & numbers" autoComplete="new-password" />
              </SignupField>
              <SignupField label="Confirm password" error={fieldError('confirmPassword')}>
                <input style={inputStyle(fieldError('confirmPassword'))} type="password" value={form.confirmPassword} onChange={e => set('confirmPassword', e.target.value)} placeholder="Repeat password" autoComplete="new-password" />
              </SignupField>
            </div>
          </div>
        )}

        {/* Step 1: School & Grade */}
        {step === 1 && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
            <h3 style={{ margin: '0 0 4px', fontFamily: 'Playfair Display, Georgia, serif', fontSize: 18 }}>School &amp; grade</h3>
            <SignupField label="Grade level" error={fieldError('grade')}>
              <div style={{ display: 'flex', gap: 10 }}>
                {[9, 10, 11, 12].map(g => (
                  <button
                    key={g}
                    type="button"
                    onClick={() => {
                      setForm(f => ({ ...f, grade: g, stream: (g === 11 || g === 12) ? f.stream : '' }));
                      setErrors(e => ({ ...e, grade: undefined }));
                      setEnrolledGrade && setEnrolledGrade(g);
                    }}
                    style={{
                      flex: 1, padding: '12px 8px', borderRadius: 8,
                      border: `2px solid ${form.grade === g ? BRAND.primary : BRAND.border}`,
                      background: form.grade === g ? `${BRAND.primary}10` : '#fff',
                      color: form.grade === g ? BRAND.primary : BRAND.muted,
                      fontFamily: 'Plus Jakarta Sans, sans-serif', fontWeight: 700, fontSize: 15, cursor: 'pointer',
                    }}
                  >G{g}</button>
                ))}
              </div>
            </SignupField>
            {(String(form.grade) === '11' || String(form.grade) === '12') && (
              <SignupField label="Academic stream" error={fieldError('stream')}>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                  {STREAMS.map(stream => {
                    const active = form.stream === stream.value;
                    return (
                      <button
                        key={stream.value}
                        type="button"
                        onClick={() => set('stream', stream.value)}
                        style={{
                          padding: '12px 10px', borderRadius: 8,
                          border: `2px solid ${active ? BRAND.primary : BRAND.border}`,
                          background: active ? `${BRAND.primary}10` : '#fff',
                          color: active ? BRAND.primary : BRAND.muted,
                          fontFamily: 'Plus Jakarta Sans, sans-serif', fontWeight: 700, fontSize: 14, cursor: 'pointer',
                        }}
                      >{stream.label}</button>
                    );
                  })}
                </div>
              </SignupField>
            )}
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              <SignupField label="School (optional)" error={fieldError('school')}>
                <input style={inputStyle(false)} value={form.school} onChange={e => set('school', e.target.value)} placeholder="e.g. Menelik II Secondary" />
              </SignupField>
              <SignupField label="Region (optional)" error={fieldError('region')}>
                <select style={inputStyle(false)} value={form.region} onChange={e => set('region', e.target.value)}>
                  <option value="">Select region&hellip;</option>
                  {REGIONS.map(r => <option key={r} value={r}>{r}</option>)}
                </select>
              </SignupField>
            </div>
            <div style={{ fontSize: 12, color: BRAND.muted, background: BRAND.cream, padding: '10px 14px', borderRadius: 8, lineHeight: 1.5 }}>
              <strong>Course access:</strong> Grade 9 and 10 get one course each. Grade 11 and 12 are assigned by Natural or Social stream.
            </div>
            {openedxSync && (
              <div style={{ fontSize: 12, color: BRAND.muted, background: '#f8fafc', border: `1px solid ${BRAND.border}`, padding: '10px 14px', borderRadius: 8, lineHeight: 1.5 }}>
                <strong>Open edX mode:</strong> {openedxSync.mode || 'mock'} · real LMS writes happen only when the backend is configured for them.
              </div>
            )}
          </div>
        )}

        {/* General (non-field) error */}
        {authError && (
          <div style={{ marginTop: 16, background: '#fff1f2', border: '1px solid #fecdd3', color: '#9f1239', borderRadius: 8, padding: '10px 12px', fontSize: 12.5, lineHeight: 1.45 }}>
            {authError}
          </div>
        )}

        {/* Navigation */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginTop: 26 }}>
          {step > 0
            ? <CTAButton variant="ghost" onClick={back} style={{ opacity: authBusy ? 0.5 : 1, pointerEvents: authBusy ? 'none' : 'auto' }}>← Back</CTAButton>
            : <div />}
          <CTAButton
            variant="primary"
            onClick={authBusy ? undefined : next}
            style={{ opacity: authBusy ? 0.75 : 1, cursor: authBusy ? 'wait' : 'pointer', display: 'inline-flex', alignItems: 'center', gap: 8 }}
          >
            {authBusy && (
              <span style={{
                width: 15, height: 15, borderRadius: '50%',
                border: '2px solid rgba(255,255,255,0.5)', borderTopColor: '#fff',
                display: 'inline-block', animation: 'mm-spin 0.8s linear infinite',
              }} />
            )}
            {authBusy
              ? 'Creating your account…'
              : step === STEPS.length - 1 ? 'Create account & sign in →' : 'Continue →'}
          </CTAButton>
        </div>
        <style>{'@keyframes mm-spin { to { transform: rotate(360deg); } }'}</style>
      </Card>

      <div style={{ textAlign: 'center', fontSize: 12.5, color: BRAND.muted, marginTop: 18, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', gap: 8 }}>
        <p style={{ margin: 0, display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 4 }}>
          <span>Already have an account?</span>
          <button onClick={() => onSignIn ? onSignIn() : navigate('dashboard')} style={{ background: 'none', border: 'none', color: BRAND.primary, fontWeight: 700, cursor: 'pointer', fontSize: 12.5, fontFamily: 'inherit', padding: 0 }}>Sign in</button>
        </p>
        <a href={forgotPasswordHref} style={{ color: BRAND.primary, fontWeight: 700, textDecoration: 'none' }}>
          Forgot password?
        </a>
      </div>
    </div>
  );
}

Object.assign(window, { Signup });
