// iceland-auth.jsx — Google-login gate. Loads the trip data from Firestore (readable
// only by allow-listed crew), builds MAP, then renders App. Needs firebase compat SDK,
// FIREBASE_CONFIG, GL, buildMAP, App. This is the last script in index.html.
const { useState: useSA, useEffect: useEA } = React;

firebase.initializeApp(window.FIREBASE_CONFIG);
const _auth = firebase.auth();
const _db = firebase.firestore();

function Centered({ children }) {
  return (
    <div className="app">
      <div style={{ height: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center',
        justifyContent: 'center', textAlign: 'center', padding: '0 30px', background: GL.bg }}>
        {children}
      </div>
    </div>
  );
}

function Splash() {
  return (
    <Centered>
      <div style={{ fontFamily: GL.mono, fontSize: 11, letterSpacing: 2, color: GL.mut }}>EVEN GEDULD…</div>
    </Centered>
  );
}

function LoginScreen({ onGoogle, busy, error }) {
  return (
    <Centered>
      <div style={{ fontFamily: GL.display, fontSize: 70, lineHeight: 0.82, textTransform: 'uppercase', color: GL.text }}>IJsland</div>
      <div style={{ fontFamily: GL.display, fontSize: 17, letterSpacing: 3, textTransform: 'uppercase', color: GL.glacier, marginTop: 10 }}>Mannentrip 2026</div>
      <p style={{ fontFamily: GL.body, fontSize: 14, color: GL.mut, lineHeight: 1.55, margin: '24px 0 28px', maxWidth: 300 }}>
        Deze reisgids bevat onze boekingsgegevens en is privé. Log in met je Google-account om verder te gaan.
      </p>
      <button onClick={onGoogle} disabled={busy} style={{
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 11, width: '100%', maxWidth: 300,
        padding: '15px 18px', borderRadius: 13, cursor: busy ? 'default' : 'pointer', opacity: busy ? 0.6 : 1,
        background: GL.text, color: GL.bg, border: 'none', fontFamily: GL.body, fontWeight: 700, fontSize: 15 }}>
        <svg width="18" height="18" viewBox="0 0 18 18"><path fill="#4285F4" d="M17.6 9.2c0-.6-.05-1.18-.16-1.74H9v3.48h4.84a4.14 4.14 0 01-1.8 2.72v2.26h2.92c1.7-1.57 2.64-3.88 2.64-6.72z"/><path fill="#34A853" d="M9 18c2.43 0 4.47-.8 5.96-2.18l-2.92-2.26c-.8.54-1.84.86-3.04.86-2.34 0-4.32-1.58-5.03-3.7H.95v2.33A9 9 0 009 18z"/><path fill="#FBBC05" d="M3.97 10.72A5.4 5.4 0 013.68 9c0-.6.1-1.18.29-1.72V4.95H.95A9 9 0 000 9c0 1.45.35 2.82.95 4.05l3.02-2.33z"/><path fill="#EA4335" d="M9 3.58c1.32 0 2.5.45 3.44 1.35l2.58-2.59C13.47.89 11.43 0 9 0A9 9 0 00.95 4.95l3.02 2.33C4.68 5.16 6.66 3.58 9 3.58z"/></svg>
        {busy ? 'Bezig…' : 'Inloggen met Google'}
      </button>
      {error && <div style={{ fontFamily: GL.body, fontSize: 12.5, color: GL.warn, marginTop: 16, maxWidth: 300, lineHeight: 1.45 }}>{error}</div>}
    </Centered>
  );
}

function DeniedScreen({ email, onSignOut }) {
  return (
    <Centered>
      <div style={{ fontFamily: GL.display, fontSize: 30, textTransform: 'uppercase', color: GL.text }}>Geen toegang</div>
      <p style={{ fontFamily: GL.body, fontSize: 14, color: GL.mut, lineHeight: 1.55, margin: '16px 0 24px', maxWidth: 300 }}>
        <strong style={{ color: GL.text }}>{email}</strong> staat (nog) niet op de gastenlijst. Vraag Kees om je toe te voegen, of log in met een ander account.
      </p>
      <button onClick={onSignOut} style={{ padding: '13px 22px', borderRadius: 12, cursor: 'pointer',
        background: GL.surface, color: GL.text, border: `1px solid ${GL.line}`, fontFamily: GL.mono, fontSize: 12, letterSpacing: 0.5 }}>
        Uitloggen
      </button>
    </Centered>
  );
}

function Root() {
  const [phase, setPhase] = useSA('loading'); // loading | login | denied | ready
  const [email, setEmail] = useSA(null);
  const [busy, setBusy] = useSA(false);
  const [error, setError] = useSA(null);

  useEA(() => {
    // surface any redirect-login error
    _auth.getRedirectResult().catch(() => setError('Inloggen mislukt. Probeer het opnieuw.'));
    return _auth.onAuthStateChanged(async (user) => {
      if (!user) { setPhase('login'); return; }
      setEmail(user.email);
      try {
        const snap = await _db.collection('trip').doc('data').get();
        if (!snap.exists) throw new Error('no-data');
        window.TRIP = JSON.parse(snap.data().json);
        window.MAP = buildMAP();
        setPhase('ready');
      } catch (e) {
        // permission-denied (not allow-listed) or missing data
        setPhase('denied');
      }
    });
  }, []);

  const signIn = async () => {
    setError(null); setBusy(true);
    const provider = new firebase.auth.GoogleAuthProvider();
    try {
      // Popup on desktop; fall back to full-page redirect (more reliable on mobile).
      await _auth.signInWithPopup(provider);
    } catch (e) {
      if (e && /popup/i.test(e.code || e.message || '')) {
        try { await _auth.signInWithRedirect(provider); return; } catch (e2) {}
      }
      setError('Inloggen mislukt. Probeer het opnieuw.');
    }
    setBusy(false);
  };
  const signOut = () => _auth.signOut();

  if (phase === 'loading') return <Splash />;
  if (phase === 'login') return <LoginScreen onGoogle={signIn} busy={busy} error={error} />;
  if (phase === 'denied') return <DeniedScreen email={email} onSignOut={signOut} />;
  return <App onSignOut={signOut} />;
}

ReactDOM.createRoot(document.getElementById('root')).render(<Root />);
