/* ========== Auth gate ==========
 * Wraps the main App. Shows a loading screen on boot while we
 * check Supabase auth state; renders <LoginScreen/> if not signed in,
 * or the app once the data store has loaded.
 */

function AuthGate({ children }) {
  const [phase, setPhase] = useState('loading'); // loading | login | app
  const [err, setErr] = useState('');

  useEffect(() => {
    let cancelled = false;
    (async () => {
      const user = await window.PVStore.init();
      if (cancelled) return;
      setPhase(user ? 'app' : 'login');
    })();
    return () => { cancelled = true; };
  }, []);

  const handleSignIn = async (email, password) => {
    setErr('');
    const res = await window.PVStore.signIn(email, password);
    if (!res.ok) setErr(res.error || 'Sign in failed');
    else setPhase('app');
  };

  if (phase === 'loading') {
    return <CenteredCard><Spinner/> <span style={{ marginLeft: 10 }}>Loading…</span></CenteredCard>;
  }
  if (phase === 'login') {
    return <LoginScreen onSignIn={handleSignIn} error={err}/>;
  }
  return children;
}

function LoginScreen({ onSignIn, error }) {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [busy, setBusy] = useState(false);

  const submit = async (e) => {
    e.preventDefault();
    if (!email || !password) return;
    setBusy(true);
    await onSignIn(email, password);
    setBusy(false);
  };

  return (
    <div style={{
      minHeight: '100vh',
      display: 'grid', placeItems: 'center',
      background: 'linear-gradient(135deg, var(--navy-900), var(--navy-700))',
      padding: 24,
    }}>
      <div style={{
        width: '100%', maxWidth: 380,
        background: '#fff', borderRadius: 14, padding: 32,
        boxShadow: '0 20px 60px rgba(0,0,0,0.35)',
      }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 20 }}>
          <div style={{ width: 44, height: 44, borderRadius: 8, background: 'var(--navy-700)',
                        display: 'grid', placeItems: 'center' }}>
            <PrimeLogo size={44}/>
          </div>
          <div>
            <div style={{ fontFamily: 'var(--font-display)', fontSize: 20, fontWeight: 700, color: 'var(--ink-900)' }}>
              Prime Ops
            </div>
            <div style={{ fontSize: 11, color: 'var(--ink-500)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>
              Visa &amp; Translation
            </div>
          </div>
        </div>

        <h2 style={{ fontFamily: 'var(--font-display)', fontSize: 18, fontWeight: 600,
                     margin: '0 0 18px', color: 'var(--ink-900)' }}>
          Sign in to your account
        </h2>

        <form onSubmit={submit}>
          <div className="field" style={{ marginBottom: 12 }}>
            <label>Email</label>
            <input type="email" autoComplete="email" required autoFocus
              value={email} onChange={e=>setEmail(e.target.value)}/>
          </div>
          <div className="field" style={{ marginBottom: 14 }}>
            <label>Password</label>
            <input type="password" autoComplete="current-password" required
              value={password} onChange={e=>setPassword(e.target.value)}/>
          </div>

          {error && (
            <div style={{
              background: 'var(--red-100)', color: 'var(--red-600)',
              padding: '8px 12px', borderRadius: 7, fontSize: 12, marginBottom: 12,
            }}>{error}</div>
          )}

          <button type="submit" className="btn primary" disabled={busy}
            style={{ width: '100%', padding: '10px 14px', justifyContent: 'center' }}>
            {busy ? 'Signing in…' : 'Sign in'}
          </button>
        </form>

        <div style={{ fontSize: 11, color: 'var(--ink-500)', marginTop: 16, textAlign: 'center' }}>
          New accounts can only be created from the Supabase dashboard.
        </div>
      </div>
    </div>
  );
}

function CenteredCard({ children }) {
  return (
    <div style={{
      minHeight: '100vh', display: 'grid', placeItems: 'center',
      background: 'var(--ink-50)', color: 'var(--ink-700)',
      fontSize: 14,
    }}>
      <div style={{ display: 'flex', alignItems: 'center' }}>{children}</div>
    </div>
  );
}

function Spinner() {
  return (
    <div style={{
      width: 18, height: 18,
      border: '2px solid var(--ink-200)',
      borderTopColor: 'var(--navy-700)',
      borderRadius: '50%',
      animation: 'pv-spin 0.8s linear infinite',
    }}>
      <style>{`@keyframes pv-spin { to { transform: rotate(360deg); } }`}</style>
    </div>
  );
}

window.AuthGate = AuthGate;
window.LoginScreen = LoginScreen;
