// Biertje — Public Screens: Landing, Auth, Onboarding, ProfileSetup
const { useState } = React;

// ── Beer Mug SVG ──────────────────────────────────────────────────
function BeerMugHero({ size = 220 }) {
  return (
    <svg width={size} height={size * 1.17} viewBox="0 0 120 140" fill="none" xmlns="http://www.w3.org/2000/svg">
      <rect x="10" y="32" width="82" height="96" rx="12" fill="#F5A623"/>
      <path d="M92 52 Q118 52 118 80 Q118 108 92 108" stroke="#C7831A" strokeWidth="10" strokeLinecap="round" fill="none"/>
      <rect x="10" y="60" width="82" height="68" fill="#E08C0A"/>
      <rect x="10" y="14" width="82" height="28" rx="8" fill="#FFFBF0"/>
      <circle cx="28" cy="18" r="10" fill="#FFFBF0"/>
      <circle cx="50" cy="14" r="13" fill="#FFFBF0"/>
      <circle cx="72" cy="18" r="10" fill="#FFFBF0"/>
      <rect x="22" y="64" width="8" height="44" rx="4" fill="rgba(255,255,255,0.22)"/>
      <circle cx="55" cy="92" r="4" fill="rgba(255,255,255,0.28)"/>
      <circle cx="74" cy="102" r="3" fill="rgba(255,255,255,0.22)"/>
      <circle cx="44" cy="118" r="5" fill="rgba(255,255,255,0.18)"/>
      <circle cx="66" cy="122" r="3" fill="rgba(255,255,255,0.20)"/>
    </svg>
  );
}

// ── Landing Screen ────────────────────────────────────────────────
function LandingScreen({ onGetStarted, onLogin }) {
  const isMobile = useIsMobile();
  const p = isMobile ? '0 16px' : '0 48px';

  return (
    <div style={{ minHeight: '100vh', background: T.cream }}>

      {/* Nav */}
      <nav style={{
        display: 'flex', alignItems: 'center', padding: p, height: isMobile ? 56 : 66,
        background: 'rgba(255,251,240,0.95)', borderBottom: `1px solid rgba(245,166,35,0.15)`,
        backdropFilter: 'blur(8px)', position: 'sticky', top: 0, zIndex: 50,
        boxShadow: '0 2px 8px rgba(61,43,31,0.05)',
      }}>
        <div style={{ fontFamily: "'Fredoka', sans-serif", fontSize: isMobile ? 22 : 28, fontWeight: 700, color: T.brown, flex: 1 }}>🍺 Drankmaatje</div>
        <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
          <Button variant="ghost" size="sm" onClick={onLogin}>Log in</Button>
          <Button variant="primary" size="sm" onClick={onGetStarted}>{isMobile ? 'Start →' : 'Aan de slag →'}</Button>
        </div>
      </nav>

      {/* Hero */}
      <div style={{ background: T.brown, padding: isMobile ? '0 16px' : '0 48px' }}>
        <div style={{
          maxWidth: 1180, margin: '0 auto',
          display: 'flex', flexDirection: isMobile ? 'column' : 'row',
          alignItems: 'center', gap: isMobile ? 0 : 60,
          minHeight: isMobile ? 'auto' : 560,
          padding: isMobile ? '40px 0 36px' : '60px 0',
        }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, background: 'rgba(245,166,35,0.14)', border: '1px solid rgba(245,166,35,0.28)', borderRadius: 9999, padding: '5px 14px', marginBottom: 20 }}>
              <span style={{ fontSize: 12, fontWeight: 700, color: T.amber, letterSpacing: '0.08em', textTransform: 'uppercase', fontFamily: "'Nunito', sans-serif" }}>Nu in Beta 🎉</span>
            </div>
            <h1 style={{ fontFamily: "'Fredoka', sans-serif", fontSize: isMobile ? 40 : 64, fontWeight: 700, color: T.foam, lineHeight: 1.08, letterSpacing: '-0.02em', marginBottom: 16 }}>
              Log bieren.<br />
              Versla je vrienden.<br />
              <span style={{ color: T.amber }}>Verdien eer. 🏆</span>
            </h1>
            <p style={{ fontSize: isMobile ? 15 : 17, color: 'rgba(255,251,240,0.70)', lineHeight: 1.7, marginBottom: 28, maxWidth: 460, fontFamily: "'Nunito', sans-serif" }}>
              Drankmaatje is het platform waar jij en je vrienden drankjes loggen, op de leaderboard strijden en achievements unlocken.
            </p>
            <div style={{ display: 'flex', flexDirection: isMobile ? 'column' : 'row', gap: 10, marginBottom: isMobile ? 0 : 44 }}>
              <Button variant="primary" size={isMobile ? 'md' : 'lg'} onClick={onGetStarted} fullWidth={isMobile}>Maak gratis account →</Button>
              <Button variant="ghost-light" size={isMobile ? 'md' : 'lg'} onClick={onLogin} fullWidth={isMobile}>Log in</Button>
            </div>
          </div>

          {/* Floating illustration — hide on mobile */}
          {!isMobile && (
            <div style={{ flexShrink: 0, position: 'relative', width: 380, height: 420, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <div style={{ animation: 'floatBeer 3.2s ease-in-out infinite' }}>
                <BeerMugHero size={230} />
              </div>
              <div style={{
                position: 'absolute', left: -16, bottom: 48,
                background: T.foam, borderRadius: 16, padding: '16px 18px',
                boxShadow: T.shadowLg, border: `1.5px solid rgba(245,166,35,0.20)`,
                animation: 'floatCard1 4.2s ease-in-out infinite', minWidth: 168,
              }}>
                <div style={{ fontSize: 10, fontWeight: 700, letterSpacing: '0.09em', color: T.brownLight, marginBottom: 10, fontFamily: "'Nunito', sans-serif", textTransform: 'uppercase' }}>Leaderboard</div>
                {[['🥇 Sander', 42], ['🥈 Joris', 38], ['🥉 Mila', 31]].map(([name, score]) => (
                  <div key={name} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 6 }}>
                    <span style={{ fontSize: 13, fontWeight: 600, color: T.brown, fontFamily: "'Nunito', sans-serif" }}>{name}</span>
                    <span style={{ fontSize: 14, fontWeight: 700, color: T.amber, fontFamily: "'Fredoka', sans-serif" }}>{score}</span>
                  </div>
                ))}
              </div>
              <div style={{
                position: 'absolute', right: -8, top: 52,
                background: T.brown, borderRadius: 14, padding: '14px 18px',
                boxShadow: `${T.shadowLg}, ${T.shadowAmber}`, border: '2px solid rgba(245,166,35,0.30)',
                textAlign: 'center', animation: 'floatCard2 3.6s ease-in-out infinite',
              }}>
                <div style={{ fontSize: 10, fontWeight: 700, color: T.amber, letterSpacing: '0.09em', textTransform: 'uppercase', fontFamily: "'Nunito', sans-serif", marginBottom: 6 }}>Unlocked!</div>
                <div style={{ fontSize: 32 }}>🔥</div>
                <div style={{ fontSize: 14, fontWeight: 700, color: T.foam, fontFamily: "'Fredoka', sans-serif", marginTop: 6 }}>On a Roll</div>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Features */}
      <div style={{ padding: isMobile ? '48px 16px' : '80px 48px', maxWidth: 1180, margin: '0 auto' }}>
        <div style={{ textAlign: 'center', marginBottom: isMobile ? 32 : 52 }}>
          <h2 style={{ fontFamily: "'Fredoka', sans-serif", fontSize: isMobile ? 28 : 42, fontWeight: 700, color: T.brown, marginBottom: 10 }}>Alles wat je crew nodig heeft</h2>
          <p style={{ fontSize: isMobile ? 14 : 17, color: T.brownLight, maxWidth: 440, margin: '0 auto', lineHeight: 1.6, fontFamily: "'Nunito', sans-serif" }}>Één app. Vijf vrienden. Eindeloos veel rondes.</p>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(3, 1fr)', gap: isMobile ? 14 : 24 }}>
          {[
            { icon: '📊', title: 'Groepsleaderboard', desc: 'Zie wie er wint. Geanimeerde charts, echte data, goede trash talk.', bg: T.amberLight },
            { icon: '📱', title: 'Activiteitenfeed', desc: 'Realtime updates als je vrienden bieren loggen. Ratings en locaties.', bg: T.skyBg },
            { icon: '🏆', title: 'Achievements', desc: 'Unlock trofeeën voor mijlpalen. Wie verzamelt ze het snelst?', bg: T.grapeBg },
          ].map(f => (
            <div key={f.title}
              style={{ background: T.foam, borderRadius: 20, padding: isMobile ? '22px 18px' : '32px 26px', border: `1.5px solid rgba(245,166,35,0.13)`, boxShadow: T.shadow, transition: 'all 220ms ease', display: 'flex', alignItems: isMobile ? 'center' : 'flex-start', gap: isMobile ? 16 : 0, flexDirection: isMobile ? 'row' : 'column' }}
              onMouseEnter={e => { e.currentTarget.style.transform = 'translateY(-5px)'; e.currentTarget.style.boxShadow = T.shadowLg; }}
              onMouseLeave={e => { e.currentTarget.style.transform = ''; e.currentTarget.style.boxShadow = T.shadow; }}
            >
              <div style={{ width: isMobile ? 48 : 60, height: isMobile ? 48 : 60, background: f.bg, borderRadius: 14, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: isMobile ? 24 : 30, marginBottom: isMobile ? 0 : 20, flexShrink: 0 }}>{f.icon}</div>
              <div>
                <div style={{ fontFamily: "'Fredoka', sans-serif", fontSize: isMobile ? 18 : 22, fontWeight: 700, color: T.brown, marginBottom: 6 }}>{f.title}</div>
                <p style={{ fontSize: 13, color: T.brownLight, lineHeight: 1.6, margin: 0, fontFamily: "'Nunito', sans-serif" }}>{f.desc}</p>
              </div>
            </div>
          ))}
        </div>
      </div>

      {/* How it works */}
      <div style={{ background: T.chalk, padding: isMobile ? '48px 16px' : '72px 48px' }}>
        <div style={{ maxWidth: 860, margin: '0 auto', textAlign: 'center' }}>
          <h2 style={{ fontFamily: "'Fredoka', sans-serif", fontSize: isMobile ? 26 : 38, fontWeight: 700, color: T.brown, marginBottom: isMobile ? 28 : 48 }}>In 3 stappen klaar</h2>
          <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(3, 1fr)', gap: isMobile ? 24 : 32, textAlign: 'left' }}>
            {[
              { step: '01', icon: '✍️', title: 'Maak een account', desc: 'In 30 seconden aangemeld. Geen creditcard nodig.' },
              { step: '02', icon: '👥', title: 'Maak een groep',   desc: 'Geef je groep een naam en nodig vrienden uit met een code.' },
              { step: '03', icon: '🍺', title: 'Start met loggen', desc: 'Log bieren, beoordeel ze en bekijk wie er bovenaan staat.' },
            ].map(s => (
              <div key={s.step} style={{ display: 'flex', gap: 16, alignItems: 'flex-start' }}>
                <div style={{ flexShrink: 0, width: 48, height: 48, background: T.amberLight, borderRadius: 14, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 24 }}>{s.icon}</div>
                <div style={{ textAlign: 'left' }}>
                  <div style={{ fontFamily: "'Fredoka', sans-serif", fontSize: 11, fontWeight: 700, letterSpacing: '0.12em', color: T.amber, marginBottom: 4 }}>{s.step}</div>
                  <div style={{ fontFamily: "'Fredoka', sans-serif", fontSize: 18, fontWeight: 700, color: T.brown, marginBottom: 4 }}>{s.title}</div>
                  <div style={{ fontSize: 13, color: T.brownLight, lineHeight: 1.6, fontFamily: "'Nunito', sans-serif" }}>{s.desc}</div>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>

      {/* CTA */}
      <div style={{ background: T.brown, padding: isMobile ? '56px 20px' : '80px 48px', textAlign: 'center' }}>
        <div style={{ fontSize: isMobile ? 48 : 60, marginBottom: 14 }}>🍺</div>
        <h2 style={{ fontFamily: "'Fredoka', sans-serif", fontSize: isMobile ? 28 : 44, fontWeight: 700, color: T.foam, marginBottom: 12 }}>Klaar om slim te drinken?</h2>
        <p style={{ fontSize: isMobile ? 14 : 17, color: 'rgba(255,251,240,0.60)', marginBottom: 28, lineHeight: 1.6, fontFamily: "'Nunito', sans-serif" }}>Maak je groep in 60 seconden. Altijd gratis.</p>
        <Button variant="primary" size={isMobile ? 'lg' : 'xl'} onClick={onGetStarted} fullWidth={isMobile}>Maak je groep →</Button>
      </div>

      {/* Footer */}
      <div style={{ background: T.brown, borderTop: '1px solid rgba(245,166,35,0.10)', padding: isMobile ? '20px 16px' : '24px 48px', display: 'flex', flexDirection: isMobile ? 'column' : 'row', justifyContent: 'space-between', alignItems: 'center', gap: 8 }}>
        <div style={{ fontFamily: "'Fredoka', sans-serif", fontSize: 20, fontWeight: 700, color: T.amber }}>🍺 Drankmaatje</div>
        <div style={{ fontSize: 12, color: 'rgba(255,251,240,0.35)', fontFamily: "'Nunito', sans-serif", textAlign: 'center' }}>Gemaakt met ❤️ en 🍺 in Nederland · © 2026</div>
      </div>

      <style>{`
        @keyframes floatBeer  { 0%,100%{ transform:translateY(0); } 50%{ transform:translateY(-14px); } }
        @keyframes floatCard1 { 0%,100%{ transform:translateY(0) rotate(-1.5deg); } 50%{ transform:translateY(-9px) rotate(1deg); } }
        @keyframes floatCard2 { 0%,100%{ transform:translateY(0) rotate(1.5deg); } 50%{ transform:translateY(-11px) rotate(-1deg); } }
      `}</style>
    </div>
  );
}

// ── Auth Screen ───────────────────────────────────────────────────
function AuthScreen({ onBack, onAuth }) {
  const [tab, setTab]           = useState('signup');
  const [name, setName]         = useState('');
  const [email, setEmail]       = useState('');
  const [password, setPassword] = useState('');
  const [loading, setLoading]   = useState(false);
  const [error, setError]       = useState('');
  const [confirmMsg, setConfirmMsg] = useState(false);

  const handleSubmit = async () => {
    setError('');
    if (!email || !password) { setError('Vul e-mail en wachtwoord in.'); return; }
    if (tab === 'signup' && !name.trim()) { setError('Vul je naam in.'); return; }
    if (password.length < 6) { setError('Wachtwoord moet minimaal 6 tekens zijn.'); return; }

    setLoading(true);

    if (tab === 'signup') {
      const { data, error: err } = await db.auth.signUp({
        email: email.trim(),
        password,
        options: { data: { display_name: name.trim() } },
      });
      if (err) { setError(err.message); setLoading(false); return; }
      if (data.session) {
        onAuth(data.user.id, data.session);
      } else {
        setConfirmMsg(true);
        setLoading(false);
      }
    } else {
      const { data, error: err } = await db.auth.signInWithPassword({ email: email.trim(), password });
      if (err) { setError('Onjuist e-mailadres of wachtwoord.'); setLoading(false); return; }
      onAuth(data.user.id, data.session);
    }
  };

  if (confirmMsg) return (
    <div style={{ minHeight: '100vh', background: T.brown, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}>
      <div style={{ background: T.foam, borderRadius: 24, padding: '40px', width: '100%', maxWidth: 420, textAlign: 'center', boxShadow: '0 32px 64px rgba(0,0,0,0.30)' }}>
        <div style={{ fontSize: 56, marginBottom: 16 }}>📬</div>
        <div style={{ fontFamily: "'Fredoka', sans-serif", fontSize: 26, fontWeight: 700, color: T.brown, marginBottom: 10 }}>Check je e-mail!</div>
        <p style={{ fontSize: 14, color: T.brownLight, lineHeight: 1.65, fontFamily: "'Nunito', sans-serif", marginBottom: 24 }}>
          We hebben een bevestigingslink gestuurd naar <strong>{email}</strong>. Klik op de link om je account te activeren.
        </p>
        <Button variant="ghost" size="md" onClick={() => setConfirmMsg(false)}>← Terug</Button>
      </div>
    </div>
  );

  return (
    <div style={{ minHeight: '100vh', background: T.brown, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24, position: 'relative' }}>
      <button onClick={onBack} style={{ position: 'absolute', top: 28, left: 28, background: 'transparent', border: 'none', color: 'rgba(255,251,240,0.55)', cursor: 'pointer', fontFamily: "'Nunito', sans-serif", fontSize: 14, display: 'flex', alignItems: 'center', gap: 6 }}>← Terug</button>

      <div style={{ background: T.foam, borderRadius: 24, padding: '40px 40px 36px', width: '100%', maxWidth: 420, boxShadow: '0 32px 64px rgba(0,0,0,0.30)', animation: 'authPop 350ms cubic-bezier(0.34,1.56,0.64,1)' }}>
        <div style={{ textAlign: 'center', marginBottom: 28 }}>
          <div style={{ fontSize: 46, marginBottom: 4 }}>🍺</div>
          <div style={{ fontFamily: "'Fredoka', sans-serif", fontSize: 28, fontWeight: 700, color: T.brown }}>Drankmaatje</div>
          <div style={{ fontSize: 13, color: T.brownLight, fontFamily: "'Nunito', sans-serif", marginTop: 4 }}>
            {tab === 'login' ? 'Welkom terug! 👋' : 'Word lid van de crew 🎉'}
          </div>
        </div>

        <div style={{ display: 'flex', background: T.chalk, borderRadius: 12, padding: 4, marginBottom: 26 }}>
          {[['login','Log in'], ['signup','Aanmelden']].map(([id, label]) => (
            <button key={id} onClick={() => { setTab(id); setError(''); }} style={{
              flex: 1, padding: '9px', borderRadius: 9, border: 'none', cursor: 'pointer',
              background: tab === id ? T.foam : 'transparent',
              color: tab === id ? T.brown : T.brownLight,
              fontFamily: "'Nunito', sans-serif", fontWeight: 700, fontSize: 14,
              boxShadow: tab === id ? T.shadow : 'none', transition: 'all 200ms ease',
            }}>{label}</button>
          ))}
        </div>

        {tab === 'signup' && <Input label="Naam" placeholder="Joris" value={name} onChange={setName} icon="👤" />}
        <Input label="E-mail" placeholder="joris@example.com" value={email} onChange={setEmail} icon="✉️" type="email" />
        <Input label="Wachtwoord" placeholder="••••••••" value={password} onChange={setPassword} icon="🔒" type="password" hint={tab === 'signup' ? 'Minimaal 6 tekens' : ''} />

        {error && <div style={{ background: '#FFF0F3', border: '1.5px solid rgba(232,62,90,0.25)', borderRadius: 8, padding: '8px 12px', marginBottom: 14, fontSize: 13, color: T.berry, fontFamily: "'Nunito', sans-serif" }}>{error}</div>}

        <Button variant="primary" size="lg" onClick={handleSubmit} fullWidth disabled={loading} style={{ marginTop: 4, marginBottom: 20 }}>
          {loading ? '⏳ Even wachten...' : tab === 'login' ? 'Log in →' : 'Account aanmaken →'}
        </Button>

        <div style={{ textAlign: 'center', fontSize: 13, color: T.brownLight, fontFamily: "'Nunito', sans-serif" }}>
          {tab === 'login' ? 'Nog geen account? ' : 'Al een account? '}
          <button onClick={() => { setTab(tab === 'login' ? 'signup' : 'login'); setError(''); }} style={{ background: 'none', border: 'none', color: T.amberDark, fontWeight: 700, cursor: 'pointer', fontFamily: "'Nunito', sans-serif", fontSize: 13 }}>
            {tab === 'login' ? 'Gratis aanmelden' : 'Log in'}
          </button>
        </div>
      </div>
      <style>{`@keyframes authPop { from{transform:scale(0.88) translateY(20px);opacity:0} to{transform:scale(1) translateY(0);opacity:1} }`}</style>
    </div>
  );
}

// ── Profile Setup (fallback if trigger didn't fire) ───────────────
function ProfileSetupScreen({ userId, onDone }) {
  const { useEffect } = React;
  const [name, setName]     = useState('');
  const [loading, setLoading] = useState(false);
  const [error, setError]   = useState('');

  // Zodra dit scherm toont, kan de trigger inmiddels al klaar zijn.
  // Controleer direct of er al een profiel is en sla de form dan over.
  useEffect(() => {
    db.from('profiles').select('*').eq('id', userId).single()
      .then(({ data }) => { if (data) onDone(data); });
  }, [userId]);

  const handleCreate = async () => {
    if (!name.trim()) { setError('Vul je naam in.'); return; }
    setLoading(true);
    const username = name.trim().toLowerCase().replace(/[^a-z0-9]/g, '_');
    // UPSERT op id: als de database-trigger het profiel al aanmaakte (timing-race),
    // updaten we gewoon de naam i.p.v. een foutmelding te geven.
    const { data, error: err } = await db.from('profiles').upsert(
      { id: userId, display_name: name.trim(), username },
      { onConflict: 'id' }
    ).select().single();
    if (err) {
      // Enige mogelijke fout nu: username al bezet door ander account
      const msg = err.code === '23505'
        ? 'Die naam is al bezet, probeer een andere.'
        : 'Er ging iets mis. Probeer het opnieuw.';
      setError(msg); setLoading(false); return;
    }
    onDone(data);
  };

  return (
    <div style={{ minHeight: '100vh', background: T.brown, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}>
      <div style={{ background: T.foam, borderRadius: 24, padding: '40px', width: '100%', maxWidth: 420, boxShadow: '0 32px 64px rgba(0,0,0,0.30)' }}>
        <div style={{ textAlign: 'center', marginBottom: 28 }}>
          <div style={{ fontSize: 46, marginBottom: 4 }}>👤</div>
          <div style={{ fontFamily: "'Fredoka', sans-serif", fontSize: 26, fontWeight: 700, color: T.brown }}>Hoe heet je?</div>
          <p style={{ fontSize: 14, color: T.brownLight, fontFamily: "'Nunito', sans-serif", marginTop: 8 }}>Dit zien je vrienden op de leaderboard.</p>
        </div>
        <Input label="Jouw naam" placeholder="Joris" value={name} onChange={setName} icon="👤" />
        {error && <div style={{ color: T.berry, fontSize: 13, marginBottom: 12, fontFamily: "'Nunito', sans-serif" }}>{error}</div>}
        <Button variant="primary" size="lg" onClick={handleCreate} fullWidth disabled={loading || !name.trim()}>
          {loading ? '⏳ Even wachten...' : 'Doorgaan →'}
        </Button>
      </div>
    </div>
  );
}

// ── Onboarding Screen ─────────────────────────────────────────────
function OnboardingScreen({ userId, profile, onComplete }) {
  const [step, setStep]         = useState(1);
  const [choice, setChoice]     = useState(null);
  const [groupName, setGroupName] = useState('');
  const [emoji, setEmoji]       = useState('🍺');
  const [inviteCode, setInviteCode] = useState('');
  const [loading, setLoading]   = useState(false);
  const [error, setError]       = useState('');
  const [createdCode, setCreatedCode] = useState('');
  const EMOJIS = ['🍺','🏆','🔥','🎉','👑','⚡','🌍','🤘','🍻','🎸'];

  const handleCreate = async () => {
    if (!groupName.trim()) { setError('Geef je groep een naam.'); return; }
    setLoading(true); setError('');

    // Genereer groep-ID client-side zodat we geen .select() na INSERT nodig hebben.
    // (SELECT vereist lidmaatschap via RLS, dat bestaat nog niet op dat moment.)
    const groupId = crypto.randomUUID();
    let code = generateInviteCode();

    const { error: err } = await db.from('groups').insert({
      id: groupId, name: groupName.trim(), emoji, invite_code: code, created_by: userId,
    });

    if (err && err.code === '23505') {
      // Invite code collision — probeer opnieuw met nieuwe code
      code = generateInviteCode();
      const { error: retryErr } = await db.from('groups').insert({
        id: groupId, name: groupName.trim(), emoji, invite_code: code, created_by: userId,
      });
      if (retryErr) { setError('Er ging iets mis. Probeer opnieuw.'); setLoading(false); return; }
    } else if (err) {
      setError('Er ging iets mis. Probeer opnieuw.'); setLoading(false); return;
    }

    // Voeg maker toe als eigenaar — hierna werkt de SELECT-policy wel
    const { error: memberErr } = await db.from('group_members').insert({
      group_id: groupId, user_id: userId, role: 'owner',
    });
    if (memberErr) { setError('Er ging iets mis. Probeer opnieuw.'); setLoading(false); return; }

    // Nu lidmaatschap bestaat, kan de groep gewoon opgehaald worden
    const { data: group } = await db.from('groups').select('*').eq('id', groupId).single();

    setCreatedCode(code);
    setStep(3);
    setLoading(false);
    setTimeout(() => onComplete(group), 2200);
  };

  const handleJoin = async () => {
    if (inviteCode.trim().length < 4) { setError('Vul een geldige uitnodigingscode in.'); return; }
    setLoading(true); setError('');

    // Gebruik een database-functie die de groep opzoekt én lidmaatschap aanmaakt
    // in één stap (SECURITY DEFINER, dus geen RLS-probleem).
    const { data, error: err } = await db.rpc('join_group_by_invite_code', {
      p_invite_code: inviteCode.trim().toUpperCase(),
    });

    if (err || !data || !data.success) {
      const msg = data && data.error === 'not_found'
        ? 'Code niet gevonden. Controleer de code en probeer opnieuw.'
        : 'Er ging iets mis. Probeer opnieuw.';
      setError(msg); setLoading(false); return;
    }

    const group = data.group;
    setStep(3);
    setLoading(false);
    setTimeout(() => onComplete(group), 1800);
  };

  if (step === 3) return (
    <div style={{ minHeight: '100vh', background: T.brown, display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column', textAlign: 'center', padding: 40 }}>
      <div style={{ fontSize: 88, marginBottom: 18, display: 'inline-block', animation: 'successBounce 700ms cubic-bezier(0.34,1.56,0.64,1)' }}>🎉</div>
      <div style={{ fontFamily: "'Fredoka', sans-serif", fontSize: 42, fontWeight: 700, color: T.foam, marginBottom: 12 }}>
        {choice === 'create' ? `${emoji} ${groupName} is live!` : 'Je bent in de groep!'}
      </div>
      {choice === 'create' && createdCode && (
        <p style={{ fontSize: 16, color: 'rgba(255,251,240,0.65)', marginBottom: 16, maxWidth: 400, fontFamily: "'Nunito', sans-serif", lineHeight: 1.6 }}>
          Deel deze uitnodigingscode met je vrienden:
          <span style={{ fontFamily: "'Fredoka', sans-serif", fontSize: 34, color: T.amber, letterSpacing: 5, display: 'block', marginTop: 14 }}>{createdCode}</span>
        </p>
      )}
      <div style={{ fontSize: 14, color: 'rgba(255,251,240,0.50)', fontFamily: "'Nunito', sans-serif" }}>Laden...</div>
      <style>{`@keyframes successBounce { from{transform:scale(0) rotate(-20deg);opacity:0} 65%{transform:scale(1.25) rotate(6deg)} to{transform:scale(1) rotate(0);opacity:1} }`}</style>
    </div>
  );

  return (
    <div style={{ minHeight: '100vh', background: T.brown, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24 }}>
      <div style={{ background: T.foam, borderRadius: 24, padding: '40px', width: '100%', maxWidth: 520, boxShadow: '0 32px 64px rgba(0,0,0,0.28)' }}>

        <div style={{ display: 'flex', gap: 6, marginBottom: 28 }}>
          {[1,2].map(s => (
            <div key={s} style={{ flex: 1, height: 4, borderRadius: 9999, background: step >= s ? T.amber : T.brownBorder, transition: 'background 300ms ease' }} />
          ))}
        </div>

        {step === 1 && (
          <>
            <div style={{ fontFamily: "'Fredoka', sans-serif", fontSize: 30, fontWeight: 700, color: T.brown, marginBottom: 6 }}>Hey {profile ? profile.display_name : ''}! 🎉</div>
            <p style={{ fontSize: 15, color: T.brownLight, marginBottom: 28, fontFamily: "'Nunito', sans-serif", lineHeight: 1.6 }}>Maak een nieuwe groep met je vrienden, of join er een met een uitnodigingscode.</p>
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              {[
                { id: 'create', icon: '✨', title: 'Groep maken', desc: 'Begin fresh, nodig je vrienden uit' },
                { id: 'join',   icon: '🔑', title: 'Groep joinen', desc: 'Voer een uitnodigingscode in' },
              ].map(o => (
                <div key={o.id} onClick={() => { setChoice(o.id); setStep(2); }}
                  style={{ background: T.cream, border: `2px solid ${T.brownBorder}`, borderRadius: 16, padding: '28px 20px', cursor: 'pointer', textAlign: 'center', transition: 'all 180ms ease' }}
                  onMouseEnter={e => { e.currentTarget.style.borderColor = T.amber; e.currentTarget.style.background = T.amberLight; }}
                  onMouseLeave={e => { e.currentTarget.style.borderColor = T.brownBorder; e.currentTarget.style.background = T.cream; }}
                >
                  <div style={{ fontSize: 42, marginBottom: 12 }}>{o.icon}</div>
                  <div style={{ fontFamily: "'Fredoka', sans-serif", fontSize: 20, fontWeight: 700, color: T.brown, marginBottom: 5 }}>{o.title}</div>
                  <div style={{ fontSize: 13, color: T.brownLight, fontFamily: "'Nunito', sans-serif" }}>{o.desc}</div>
                </div>
              ))}
            </div>
          </>
        )}

        {step === 2 && choice === 'create' && (
          <>
            <button onClick={() => setStep(1)} style={{ background: 'none', border: 'none', color: T.brownLight, cursor: 'pointer', fontFamily: "'Nunito', sans-serif", fontSize: 14, marginBottom: 20, padding: 0, display: 'flex', alignItems: 'center', gap: 4 }}>← Terug</button>
            <div style={{ fontFamily: "'Fredoka', sans-serif", fontSize: 28, fontWeight: 700, color: T.brown, marginBottom: 6 }}>Noem je groep</div>
            <p style={{ fontSize: 14, color: T.brownLight, marginBottom: 22, fontFamily: "'Nunito', sans-serif", lineHeight: 1.6 }}>Iets waar je crew trots op is.</p>
            <div style={{ marginBottom: 18 }}>
              <div style={{ fontSize: 12, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', color: T.brownLight, marginBottom: 10, fontFamily: "'Nunito', sans-serif" }}>Kies een emoji</div>
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                {EMOJIS.map(e => (
                  <button key={e} onClick={() => setEmoji(e)} style={{ width: 44, height: 44, fontSize: 22, background: emoji === e ? T.amberLight : T.chalk, border: `2px solid ${emoji === e ? T.amber : T.brownBorder}`, borderRadius: 10, cursor: 'pointer', transition: 'all 140ms ease' }}>{e}</button>
                ))}
              </div>
            </div>
            <Input label="Groepsnaam" placeholder="The Lads, Friday Crew, Bierboys..." value={groupName} onChange={setGroupName} icon={emoji} />
            {error && <div style={{ color: T.berry, fontSize: 13, marginBottom: 12, fontFamily: "'Nunito', sans-serif" }}>{error}</div>}
            <Button variant="primary" size="lg" onClick={handleCreate} fullWidth disabled={loading || !groupName.trim()}>
              {loading ? '⏳ Bezig...' : 'Groep aanmaken →'}
            </Button>
          </>
        )}

        {step === 2 && choice === 'join' && (
          <>
            <button onClick={() => setStep(1)} style={{ background: 'none', border: 'none', color: T.brownLight, cursor: 'pointer', fontFamily: "'Nunito', sans-serif", fontSize: 14, marginBottom: 20, padding: 0, display: 'flex', alignItems: 'center', gap: 4 }}>← Terug</button>
            <div style={{ fontFamily: "'Fredoka', sans-serif", fontSize: 28, fontWeight: 700, color: T.brown, marginBottom: 6 }}>Voer uitnodigingscode in</div>
            <p style={{ fontSize: 14, color: T.brownLight, marginBottom: 22, fontFamily: "'Nunito', sans-serif", lineHeight: 1.6 }}>Vraag je vriend om de groepscode en plak hem hieronder.</p>
            <Input label="Uitnodigingscode" placeholder="BRTJE-XXXX" value={inviteCode} onChange={v => setInviteCode(v.toUpperCase())} icon="🔑" hint="Codes zien er zo uit: BRTJE-X3K9" />
            {error && <div style={{ color: T.berry, fontSize: 13, marginBottom: 12, fontFamily: "'Nunito', sans-serif" }}>{error}</div>}
            <Button variant="primary" size="lg" onClick={handleJoin} fullWidth disabled={loading || inviteCode.trim().length < 4}>
              {loading ? '⏳ Bezig...' : 'Groep joinen →'}
            </Button>
          </>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { LandingScreen, AuthScreen, ProfileSetupScreen, OnboardingScreen });
