// Member login + Federation admin password reset / forgot-password flow.
function LoginPage() {
  const { go } = CTSCShell.useNav();
  const { data, actions } = CTSCStore.useStore();
  const [role, setRole] = React.useState('federation');
  const [fedId, setFedId] = React.useState(data.federations[0].id);
  // mode: signin | forgot | sent | reset | done
  const [mode, setMode] = React.useState('signin');
  const [resetFedId, setResetFedId] = React.useState(data.federations[0].id);
  const [email, setEmail] = React.useState('');
  const [pw, setPw] = React.useState('');
  const [pw2, setPw2] = React.useState('');
  const [signinPw, setSigninPw] = React.useState('demo1234');
  const [err, setErr] = React.useState('');

  const fedEmail = (f) => f.secretaryEmail || f.presidentEmail || ('admin@' + (f.abbr || 'fed').toLowerCase().replace(/[^a-z0-9]/g, '') + '.org.za');

  const submit = () => {
    if (role === 'council') actions.login({ role: 'council', name: 'Council Administrator', fedId: null });
    else {
      const f = data.federations.find(x => x.id === fedId);
      const contact = f.president || f.secretary || 'Administrator';
      actions.login({ role: 'federation', name: contact + ' · ' + f.name, fedId });
    }
    go('admin');
  };

  // start forgot flow — prefill the federation currently selected on the sign-in form
  const startForgot = () => {
    const f = data.federations.find(x => x.id === fedId) || data.federations[0];
    setResetFedId(f.id); setEmail(fedEmail(f)); setErr(''); setMode('forgot');
  };
  const sendLink = () => {
    if (!email.trim() || !/^\S+@\S+\.\S+$/.test(email.trim())) { setErr('Enter a valid email address.'); return; }
    setErr(''); setMode('sent');
  };
  const savePassword = () => {
    if (pw.length < 8) { setErr('Password must be at least 8 characters.'); return; }
    if (pw !== pw2) { setErr('Passwords do not match.'); return; }
    actions.setPassword(resetFedId, pw);
    setSigninPw(pw); setErr(''); setMode('done');
  };
  const backToSignin = () => { setRole('federation'); setFedId(resetFedId); setPw(''); setPw2(''); setErr(''); setMode('signin'); };

  const resetFed = data.federations.find(x => x.id === resetFedId) || data.federations[0];
  const errBox = err ? <div style={{ background: '#fdecea', border: '1px solid #f3c5bd', color: '#b4452f', fontSize: 13, fontWeight: 700, padding: '9px 12px', borderRadius: 6, marginBottom: 14 }}>{err}</div> : null;
  const backLink = (
    <button onClick={() => { setErr(''); setMode('signin'); }} style={{ fontSize: 13, fontWeight: 700, color: 'var(--ocean)', marginTop: 18 }}>← Back to sign in</button>
  );

  // ---- right-panel content by mode ----
  let panel;
  if (mode === 'signin') {
    panel = (
      <>
        <div className="field">
          <label>Sign in as</label>
          <div style={{ display: 'flex', gap: 8 }}>
            <button className={'chip' + (role === 'federation' ? ' active' : '')} style={{ flex: 1, justifyContent: 'center', padding: 11 }} onClick={() => setRole('federation')}>Federation Admin</button>
            <button className={'chip' + (role === 'council' ? ' active' : '')} style={{ flex: 1, justifyContent: 'center', padding: 11 }} onClick={() => setRole('council')}>Council Admin</button>
          </div>
        </div>
        {role === 'federation' && (
          <div className="field">
            <label>Your federation</label>
            <select value={fedId} onChange={e => setFedId(e.target.value)}>
              {data.federations.map(f => <option key={f.id} value={f.id}>{f.name}</option>)}
            </select>
          </div>
        )}
        <div className="field"><label>Email</label><input defaultValue={role === 'council' ? 'admin@ctsc.org.za' : 'admin@federation.org.za'} /></div>
        <div className="field" style={{ marginBottom: 6 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <label>Password</label>
            {role === 'federation' && <button onClick={startForgot} style={{ fontSize: 12, fontWeight: 700, color: 'var(--ocean)' }}>Forgot password?</button>}
          </div>
          <input type="password" value={signinPw} onChange={e => setSigninPw(e.target.value)} />
        </div>
        <button className="btn btn-gold btn-lg" style={{ width: '100%', justifyContent: 'center', marginTop: 12 }} onClick={submit}>Sign in →</button>
        <p style={{ fontSize: 12.5, color: 'var(--muted)', textAlign: 'center', marginTop: 16 }}>
          {role === 'council' ? 'Council admins approve submissions from all federations.' : 'Federation admins manage their own content; submissions go to the council for approval.'}
        </p>
      </>
    );
  } else if (mode === 'forgot') {
    panel = (
      <>
        <h3 style={{ fontSize: 22, fontWeight: 900, margin: '0 0 6px', color: 'var(--navy)' }}>Reset your password</h3>
        <p style={{ fontSize: 13.5, color: 'var(--muted)', lineHeight: 1.55, margin: '0 0 20px' }}>Choose your federation and confirm the email on file — we'll send a secure password-reset link.</p>
        {errBox}
        <div className="field">
          <label>Your federation</label>
          <select value={resetFedId} onChange={e => { const f = data.federations.find(x => x.id === e.target.value); setResetFedId(e.target.value); setEmail(fedEmail(f)); }}>
            {data.federations.map(f => <option key={f.id} value={f.id}>{f.name}</option>)}
          </select>
        </div>
        <div className="field"><label>Account email</label><input type="email" value={email} onChange={e => setEmail(e.target.value)} placeholder="you@federation.org.za" /></div>
        <button className="btn btn-gold btn-lg" style={{ width: '100%', justifyContent: 'center', marginTop: 6 }} onClick={sendLink}>Send reset link →</button>
        {backLink}
      </>
    );
  } else if (mode === 'sent') {
    panel = (
      <>
        <div style={{ width: 54, height: 54, borderRadius: '50%', background: 'var(--sky-tint)', border: '1px solid var(--sky-soft)', display: 'grid', placeItems: 'center', fontSize: 26, color: 'var(--ocean)', marginBottom: 16 }}>✉</div>
        <h3 style={{ fontSize: 22, fontWeight: 900, margin: '0 0 6px', color: 'var(--navy)' }}>Check your email</h3>
        <p style={{ fontSize: 13.5, color: 'var(--muted)', lineHeight: 1.6, margin: '0 0 8px' }}>
          We've sent a password-reset link to <b style={{ color: 'var(--navy)' }}>{email}</b> for <b style={{ color: 'var(--navy)' }}>{resetFed.name}</b>. The link expires in 60 minutes.
        </p>
        <p style={{ fontSize: 12, color: 'var(--muted2)', lineHeight: 1.5, margin: '0 0 22px' }}>Didn't get it? Check spam, or resend from the previous step.</p>
        <button className="btn btn-gold btn-lg" style={{ width: '100%', justifyContent: 'center' }} onClick={() => { setErr(''); setMode('reset'); }}>Open reset link →</button>
        <p style={{ fontSize: 11.5, color: 'var(--muted2)', textAlign: 'center', marginTop: 12 }}>Prototype — the emailed link opens the reset form below.</p>
        {backLink}
      </>
    );
  } else if (mode === 'reset') {
    const strength = pw.length === 0 ? null : pw.length < 8 ? 'weak' : pw.length < 12 ? 'good' : 'strong';
    panel = (
      <>
        <h3 style={{ fontSize: 22, fontWeight: 900, margin: '0 0 6px', color: 'var(--navy)' }}>Set a new password</h3>
        <p style={{ fontSize: 13.5, color: 'var(--muted)', lineHeight: 1.55, margin: '0 0 20px' }}>Create a new password for <b style={{ color: 'var(--navy)' }}>{resetFed.name}</b> ({email}).</p>
        {errBox}
        <div className="field"><label>New password</label><input type="password" value={pw} onChange={e => setPw(e.target.value)} placeholder="At least 8 characters" /></div>
        {strength && <div style={{ display: 'flex', alignItems: 'center', gap: 8, margin: '-8px 0 14px' }}>
          <div style={{ flex: 1, height: 6, background: 'var(--line2)', borderRadius: 4, overflow: 'hidden' }}>
            <div style={{ width: strength === 'weak' ? '33%' : strength === 'good' ? '66%' : '100%', height: '100%', background: strength === 'weak' ? '#b4452f' : strength === 'good' ? 'var(--warn)' : 'var(--ok)' }} />
          </div>
          <span style={{ fontSize: 11.5, fontWeight: 700, color: strength === 'weak' ? '#b4452f' : strength === 'good' ? 'var(--warn)' : 'var(--ok)', textTransform: 'capitalize' }}>{strength}</span>
        </div>}
        <div className="field"><label>Confirm new password</label><input type="password" value={pw2} onChange={e => setPw2(e.target.value)} placeholder="Re-enter password" /></div>
        <button className="btn btn-gold btn-lg" style={{ width: '100%', justifyContent: 'center', marginTop: 6 }} onClick={savePassword}>Update password</button>
        {backLink}
      </>
    );
  } else { // done
    panel = (
      <>
        <div style={{ width: 54, height: 54, borderRadius: '50%', background: '#e6f4ec', border: '1px solid #bfe3cd', display: 'grid', placeItems: 'center', fontSize: 26, color: 'var(--ok)', marginBottom: 16 }}>✓</div>
        <h3 style={{ fontSize: 22, fontWeight: 900, margin: '0 0 6px', color: 'var(--navy)' }}>Password updated</h3>
        <p style={{ fontSize: 13.5, color: 'var(--muted)', lineHeight: 1.6, margin: '0 0 22px' }}>
          The password for <b style={{ color: 'var(--navy)' }}>{resetFed.name}</b> has been changed. You can now sign in with your new password.
        </p>
        <button className="btn btn-gold btn-lg" style={{ width: '100%', justifyContent: 'center' }} onClick={backToSignin}>← Back to sign in</button>
      </>
    );
  }

  return (
    <div className="fade-in" style={{ minHeight: '70vh', display: 'grid', placeItems: 'center', padding: '50px 32px' }}>
      <div style={{ width: 'min(960px,100%)', display: 'grid', gridTemplateColumns: '1fr 1fr', borderRadius: 14, overflow: 'hidden', boxShadow: 'var(--shadow-lg)', background: '#fff' }}>
        <div style={{ background: 'linear-gradient(160deg,var(--navy),var(--navy2))', color: '#fff', padding: 40, position: 'relative', overflow: 'hidden' }}>
          <div style={{ position: 'absolute', bottom: 0, left: 0, right: 0, height: '40%', background: '#08315f', clipPath: 'polygon(0 60%,20% 30%,42% 52%,68% 18%,100% 46%,100% 100%,0 100%)', opacity: .5 }}></div>
          <CTSCShell.LogoMark size={52} />
          <h2 style={{ fontSize: 28, fontWeight: 900, margin: '24px 0 12px', lineHeight: 1.15, position: 'relative' }}>Member Portal</h2>
          <p style={{ fontSize: 15, color: '#bcd0de', lineHeight: 1.6, position: 'relative' }}>Manage your federation's heroes, events, coaching, fundraising, transformation reporting and news — with a council approval workflow.</p>
          <div style={{ position: 'relative', marginTop: 28, fontSize: 12.5, color: '#8fb0c4', fontWeight: 600 }}>Prototype — no real password needed.</div>
        </div>
        <div style={{ padding: 40 }}>{panel}</div>
      </div>
    </div>
  );
}
window.LoginPage = LoginPage;
