// login.jsx — workspace sign-in / sign-up gate (Firebase Authentication)

// friendly messages for the common Firebase auth error codes
function prettyAuthError(e) {
  const code = (e && e.code) || '';
  switch (code) {
    case 'auth/invalid-email':         return 'That email address looks invalid.';
    case 'auth/user-disabled':         return 'This account has been disabled.';
    case 'auth/user-not-found':
    case 'auth/invalid-credential':
    case 'auth/wrong-password':        return 'Incorrect email or password.';
    case 'auth/email-already-in-use':  return 'An account already exists for that email — try signing in.';
    case 'auth/weak-password':         return 'Password is too weak (use at least 6 characters).';
    case 'auth/too-many-requests':     return 'Too many attempts. Please wait a moment and try again.';
    case 'auth/network-request-failed':return 'Network error — check your connection and try again.';
    default:                           return (e && e.message) || 'Something went wrong. Please try again.';
  }
}

// loading screen shown while the workspace data is fetched after sign-in
function Splash() {
  return (
    <div className="login-stage">
      <div className="login-orb" />
      <div style={{ position: 'relative', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 16 }}>
        <span className="brand-mark" style={{ width: 48, height: 48, borderRadius: 13 }}>
          <window.Icon name="bolt" size={26} stroke={2.2} />
        </span>
        <div style={{ fontSize: 14, fontWeight: 650, color: 'var(--text-dim)' }}>Loading your workspace…</div>
      </div>
    </div>
  );
}

function Login() {
  const { useState } = React;
  const [mode, setMode] = useState('signin');   // 'signin' | 'signup'
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [pw, setPw] = useState('');
  const [show, setShow] = useState(false);
  const [err, setErr] = useState('');
  const [busy, setBusy] = useState(false);

  const isSignup = mode === 'signup';

  const submit = async (e) => {
    if (e) e.preventDefault();
    setErr('');
    if (isSignup && !name.trim()) { setErr('Please enter your name.'); return; }
    if (!email.trim()) { setErr('Please enter your email address.'); return; }
    if (pw.length < 6) { setErr('Password must be at least 6 characters.'); return; }

    setBusy(true);
    try {
      if (isSignup) {
        await window.fb.signUp({ name: name.trim(), email: email.trim(), password: pw });
      } else {
        await window.fb.signIn({ email: email.trim(), password: pw });
      }
      // onAuthStateChanged in App takes over from here (loads the workspace).
      // keep `busy` true so the card stays disabled through the transition.
    } catch (e2) {
      setErr(prettyAuthError(e2));
      setBusy(false);
    }
  };

  const swap = () => { setMode(isSignup ? 'signin' : 'signup'); setErr(''); };

  return (
    <div className="login-stage">
      <div className="login-orb" />
      <div className={'login-card' + (busy ? ' busy' : '')}>
        <div className="login-brand">
          <span className="brand-mark"><window.Icon name="bolt" size={19} stroke={2.2} /></span>
          <span className="brand-name">Idea<span style={{ color: 'var(--primary)' }}>Pipeline</span>
            <span className="login-brand-sub">System</span></span>
        </div>

        <h1 className="login-title">{isSignup ? 'Create your account' : 'Sign in to your workspace'}</h1>
        <p className="login-sub">
          {isSignup
            ? 'Set up your member profile to join the workspace.'
            : 'Welcome back — pick up where your team left off.'}
        </p>

        <form className="login-form" onSubmit={submit}>
          {isSignup && (
            <>
              <label className="lbl">Full name</label>
              <input className="mini-input big" type="text" autoComplete="name" value={name}
                onChange={(e) => { setName(e.target.value); setErr(''); }} placeholder="Anjana Perera" />
            </>
          )}

          <label className="lbl">Email address</label>
          <input className="mini-input big" type="email" autoComplete="username" value={email}
            onChange={(e) => { setEmail(e.target.value); setErr(''); }} placeholder="you@company.com" />

          <label className="lbl">Password</label>
          <div className="pw-wrap">
            <input className="mini-input big" type={show ? 'text' : 'password'}
              autoComplete={isSignup ? 'new-password' : 'current-password'}
              value={pw} onChange={(e) => { setPw(e.target.value); setErr(''); }} placeholder="••••••••" />
            <button type="button" className="pw-toggle" onClick={() => setShow((s) => !s)}>{show ? 'Hide' : 'Show'}</button>
          </div>

          {err && <div className="login-err"><window.Icon name="flag" size={13} stroke={2.4} />{err}</div>}

          <button className="btn-primary login-btn" type="submit" disabled={busy}>
            {busy
              ? (isSignup ? 'Creating account…' : 'Signing in…')
              : <>{isSignup ? 'Create account' : 'Sign in'} <window.Icon name="arrow" size={17} /></>}
          </button>
        </form>

        <div className="login-divider"><span>{isSignup ? 'already have an account?' : 'new to the workspace?'}</span></div>
        <button className="btn-ghost" style={{ width: '100%', justifyContent: 'center' }} onClick={swap} disabled={busy}>
          {isSignup ? 'Sign in instead' : 'Create a new account'}
        </button>

        <p className="login-demo">Protected by Firebase Authentication. The first account created becomes the workspace Owner.</p>
      </div>
    </div>
  );
}

window.Login = Login;
window.Splash = Splash;
