// Login screen: first-run main-admin setup, plus Sign In / Sign Up tabs. Themed via CSS variables.
function LoginScreen({ accounts, onAuth, churchName }){
  const firstRun = !accounts;
  const [mode, setMode] = React.useState('login'); // 'login' | 'signup'
  const [name, setName] = React.useState('');
  const [email, setEmail] = React.useState(firstRun ? window.SUPER_ADMIN_EMAIL : '');
  const [pw, setPw] = React.useState('');
  const [pw2, setPw2] = React.useState('');
  const [err, setErr] = React.useState('');

  const signup = !firstRun && mode === 'signup';

  function submit(e){
    e.preventDefault();
    setErr('');

    if(firstRun){
      if(pw.length < 4){ setErr('Choose a password of at least 4 characters.'); return; }
      if(pw !== pw2){ setErr('Passwords do not match.'); return; }
      const a = window.initAccounts(pw);
      window.setSession(a.users[0].email);
      onAuth(a, a.users[0]);
      return;
    }

    if(signup){
      const em = email.trim().toLowerCase();
      if(!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(em)){ setErr('Enter a valid email address.'); return; }
      if(window.findUser(accounts, em)){ setErr('An account with that email already exists. Please sign in.'); return; }
      if(pw.length < 4){ setErr('Choose a password of at least 4 characters.'); return; }
      if(pw !== pw2){ setErr('Passwords do not match.'); return; }
      const newUser = { email: em, name: name.trim() || em.split('@')[0], role: 'user', password: pw };
      const next = { ...accounts, users: [...accounts.users, newUser] };
      window.saveAccounts(next);
      window.setSession(em);
      onAuth(next, newUser);
      return;
    }

    // login
    const u = window.verifyLogin(accounts, email, pw);
    if(!u){ setErr('Incorrect email or password.'); return; }
    window.setSession(u.email);
    onAuth(accounts, u);
  }

  return (
    <div className="login-wrap">
      <form className="login-card" onSubmit={submit}>
        <div className="login-mark"><img src="app/sbbm-seal-small.png" alt="Shalom Bible Baptist Church" /></div>
        <h1 className="login-church">{churchName || 'Worship Management'}</h1>
        <p className="login-sub">
          {firstRun ? 'Set up the main administrator account'
            : signup ? 'Create your member account' : 'Sign in to continue'}
        </p>

        {!firstRun && (
          <div className="login-tabs">
            <button type="button" className={!signup?'on':''} onClick={()=>{ setMode('login'); setErr(''); }}>Sign In</button>
            <button type="button" className={signup?'on':''} onClick={()=>{ setMode('signup'); setErr(''); }}>Sign Up</button>
          </div>
        )}

        {firstRun && (
          <div className="login-note">
            This is the first launch. Create a password for the main admin account
            <b> {window.SUPER_ADMIN_EMAIL}</b>. You can add more users afterwards.
          </div>
        )}

        {signup && (
          <React.Fragment>
            <label className="login-lbl">Full name</label>
            <input className="field" value={name} onChange={e=>setName(e.target.value)} placeholder="Your name" autoFocus />
          </React.Fragment>
        )}

        <label className="login-lbl">Email</label>
        <input className="field" type="email" value={email} disabled={firstRun}
          onChange={e=>setEmail(e.target.value)} placeholder="you@email.com" autoFocus={!firstRun && !signup} />

        <label className="login-lbl">{firstRun||signup ? 'Create password' : 'Password'}</label>
        <input className="field" type="password" value={pw} onChange={e=>setPw(e.target.value)}
          placeholder="Password" autoFocus={firstRun} />

        {(firstRun || signup) && (
          <React.Fragment>
            <label className="login-lbl">Confirm password</label>
            <input className="field" type="password" value={pw2} onChange={e=>setPw2(e.target.value)} placeholder="Re-enter password" />
          </React.Fragment>
        )}

        {err && <div className="login-err">{err}</div>}

        <button className="pill login-btn" type="submit">
          {firstRun ? 'Create & Sign In' : signup ? 'Create Account' : 'Sign In'}
        </button>

        {signup && (
          <div className="login-hint">New sign-ups join as <b>Members (User)</b>. An admin can upgrade you to Admin later.</div>
        )}
      </form>
      <div className="login-foot">Worship Management · {churchName || 'Your Church'}</div>
    </div>
  );
}
window.LoginScreen = LoginScreen;
