// screen-more-auth.jsx — Lainnya menu + Login + Onboarding

// ─── LAINNYA / MORE MENU ─────────────────────────────────────────
function ScreenMore({ theme, accent, scenario, onNavigate, onLogout, auth }) {
  const isAuth = !!(auth && auth.family);
  const [members, setMembers] = React.useState(null);
  const familyId = auth && auth.family && auth.family.id;
  React.useEffect(function() {
    if (!familyId || !window.sbGetMembers) return;
    sbGetMembers(familyId).then(function(r){ if(!r.error) setMembers(r.data||[]); });
  }, [familyId]);
  const realMembers = members || (auth && auth.profile ? [auth.profile] : null);
  const me = isAuth && auth.profile
    ? { name: auth.profile.full_name||'Kamu', short: (auth.profile.full_name||'').split(' ')[0]||'Kamu', color:'#10b981' }
    : scenario.members[0];
  return (
    <div style={{ background: theme.bg, paddingBottom: 100 }}>
      <div style={{ padding: '56px 20px 16px' }}>
        <h1 style={{ margin: 0, fontSize: 28, fontWeight: 800,
                     letterSpacing: '-0.025em', color: theme.fg1 }}>Lainnya</h1>
      </div>

      {/* Family card */}
      <div style={{ padding: '0 20px 16px' }}>
        <Card theme={theme} padding={18}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{
              width: 52, height: 52, borderRadius: 18,
              background: `linear-gradient(135deg, ${accent.grad[0]}, ${accent.grad[1]})`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              flexShrink: 0,
            }}>
              <Icon name="users-round" size={26} color="#fff" stroke={1.85} />
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 15, fontWeight: 700, color: theme.fg1,
                            letterSpacing: '-0.01em' }}>{isAuth ? auth.family.name : scenario.family.name}</div>
              <div style={{ fontSize: 12, color: theme.fg3, fontWeight: 500,
                            fontFamily: 'JetBrains Mono, monospace', marginTop: 2 }}>
                {isAuth ? auth.family.invite_code : scenario.family.code}
              </div>
            </div>
            <button style={{
              appearance: 'none', border: 0, background: theme.surfaceAlt,
              padding: '6px 12px', borderRadius: 10, cursor: 'pointer',
              fontSize: 12, fontWeight: 700, color: theme.fg1,
            }}>Undang</button>
          </div>
          <div style={{
            marginTop: 14, paddingTop: 14,
            borderTop: `0.5px dashed ${theme.border}`,
            display: 'flex', alignItems: 'center', gap: 10,
          }}>
            <AvatarStack members={(isAuth ? (realMembers||[auth.profile]).filter(Boolean) : scenario.members).map(function(m){ return Object.assign({}, m, {name: m.full_name||m.name||m.short||'?'}); })} size={26} ringColor={theme.surface} max={5} />
            <div style={{ fontSize: 12, color: theme.fg2, fontWeight: 600 }}>
              {isAuth ? (realMembers||[me]).length : scenario.members.length} anggota aktif
            </div>
          </div>
        </Card>
      </div>

      {/* Grouped menu */}
      <MenuGroup theme={theme} title="Keuangan">
        <MenuItem theme={theme} accent={accent}
                  icon="target" label="Budget"     hint="Rencana per kategori"
                  color="#3b82f6" onClick={() => onNavigate('budget')} />
        <MenuItem theme={theme} accent={accent}
                  icon="piggy-bank" label="Tabungan" hint={scenario.goals.length + ' tujuan'}
                  color="#10b981" onClick={() => onNavigate('goals')} />
        <MenuItem theme={theme} accent={accent}
                  icon="hand-coins" label="Hutang & Piutang"
                  hint={scenario.debts.length + ' catatan aktif'}
                  color="#f43f5e" onClick={() => onNavigate('debts')} />
        <MenuItem theme={theme} accent={accent} last
                  icon="folder-tree" label="Kategori"
                  hint={Object.keys(CATEGORIES).length + ' kategori'}
                  color="#8b5cf6" />
      </MenuGroup>

      <MenuGroup theme={theme} title="Tools">
        <MenuItem theme={theme} accent={accent}
                  icon="flame" label="FIRE Calculator"
                  hint="Kapan bisa pensiun?"
                  color="#f97316" onClick={() => onNavigate('fire')} />
        <MenuItem theme={theme} accent={accent} last
                  icon="scan" label="Scan Struk"
                  hint="Foto → AI → catat otomatis"
                  color="#8b5cf6" onClick={() => onNavigate('receipt')} />
      </MenuGroup>

      <MenuGroup theme={theme} title="Keluarga">
        <MenuItem theme={theme} accent={accent}
                  icon="users" label="Anggota keluarga"
                  hint={(isAuth ? (realMembers||[me]).length : scenario.members.length) + ' orang'} color="#0d9488" />
        <MenuItem theme={theme} accent={accent} last
                  icon="bell" label="Notifikasi" hint="3 aktif" color="#f59e0b" />
      </MenuGroup>

      <MenuGroup theme={theme} title="Pengaturan">
        <MenuItem theme={theme} accent={accent}
                  icon="user-circle" label="Akun saya" hint={me.name} color="#64748b" onClick={() => onNavigate('profile')} />
        <MenuItem theme={theme} accent={accent}
                  icon="piggy-bank" label="Rekening & Investasi" hint="Saldo & kekayaan bersih" color="#8b5cf6" onClick={() => onNavigate('accounts')} />
        <MenuItem theme={theme} accent={accent}
                  icon="shield-check" label="Keamanan & PIN" hint="Ubah password" color="#10b981" onClick={() => onNavigate('security')} />
        <MenuItem theme={theme} accent={accent}
                  icon="download" label="Export data" hint="CSV / PDF" color="#3b82f6" onClick={() => onNavigate('export')} />
        <MenuItem theme={theme} accent={accent} last
                  icon="circle-help" label="Bantuan" color="#94a3b8" onClick={() => onNavigate('help')} />
      </MenuGroup>

      <div style={{ padding: '20px 20px 12px' }}>
        <button onClick={onLogout} style={{
          width: '100%', appearance: 'none', border: 0, cursor: 'pointer',
          padding: '14px', borderRadius: 14,
          background: theme.surface,
          border: `0.5px solid ${theme.border}`,
          color: theme.danger, fontSize: 14, fontWeight: 700,
          letterSpacing: '-0.005em',
          display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          boxShadow: theme.shadow1,
        }}>
          <Icon name="log-out" size={16} stroke={2} />
          Keluar
        </button>
      </div>

      <div style={{ textAlign: 'center', padding: '6px 20px',
                    fontSize: 11, color: theme.fg4, fontWeight: 500 }}>
        INDIECASH v0.4 · made by INDIE Group
      </div>
    </div>
  );
}

function MenuGroup({ theme, title, children }) {
  return (
    <div style={{ marginBottom: 16 }}>
      <div style={{
        padding: '0 24px 6px', fontSize: 11, fontWeight: 700, color: theme.fg3,
        textTransform: 'uppercase', letterSpacing: '0.06em',
      }}>{title}</div>
      <div style={{ padding: '0 20px' }}>
        <Card theme={theme} padding={0} radius={16}>
          {children}
        </Card>
      </div>
    </div>
  );
}

function MenuItem({ theme, accent, icon, label, hint, color, last, onClick }) {
  return (
    <button onClick={onClick} style={{
      width: '100%', appearance: 'none', border: 0, cursor: 'pointer',
      background: 'transparent',
      display: 'flex', alignItems: 'center', gap: 14,
      padding: '12px 14px',
      borderBottom: last ? 'none' : `0.5px solid ${theme.border}`,
      textAlign: 'left',
    }}>
      <div style={{
        width: 36, height: 36, borderRadius: 11,
        background: (color || accent[500]) + '1a',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        flexShrink: 0,
      }}>
        <Icon name={icon} size={18} color={color || accent[500]} stroke={1.85} />
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 600, color: theme.fg1,
                      letterSpacing: '-0.005em' }}>{label}</div>
        {hint && <div style={{ fontSize: 11, color: theme.fg3, fontWeight: 500, marginTop: 1 }}>
          {hint}
        </div>}
      </div>
      <Icon name="chevron-right" size={18} color={theme.fg4} stroke={1.8} />
    </button>
  );
}

// ─── LOGIN ───────────────────────────────────────────────────────
function ScreenLogin({ theme, accent, onContinue, auth }) {
  const T = theme;
  const [mode, setMode]     = React.useState('main');  // main | password | magic
  const [email, setEmail]   = React.useState('');
  const [password, setPass] = React.useState('');
  const [isSignup, setIsSignup] = React.useState(false);
  const [sent, setSent]     = React.useState(false);
  const [loading, setLoading] = React.useState(false);
  const [err, setErr]       = React.useState('');
  const [showPass, setShowPass] = React.useState(false);

  const validEmail = email.includes('@') && email.includes('.');
  const realAuth   = auth || {};

  function reset() { setErr(''); setLoading(false); }

  async function handlePassword(e) {
    e && e.preventDefault();
    if (!validEmail || password.length < 6) return;
    setLoading(true); setErr('');
    if (!window.SB) { setErr('Koneksi belum siap'); setLoading(false); return; }
    try {
      if (isSignup) {
        var r = await window.SB.auth.signUp({
          email, password,
          options: { emailRedirectTo: window.location.origin }
        });
        if (r.error) throw r.error;
        // Jika email confirm OFF → user langsung punya session
        if (r.data && r.data.session) {
          // Langsung masuk — useAuth akan detect via onAuthStateChange
          setLoading(false); return;
        }
        // Jika email confirm ON → tampilkan pesan cek email
        setSent(true); setLoading(false); return;
      } else {
        var r = await window.SB.auth.signInWithPassword({ email, password });
        if (r.error) throw r.error;
        // Login sukses — App detect session change otomatis
      }
    } catch(e) {
      var msg = e.message || 'Gagal login';
      if (msg.includes('Invalid login credentials')) msg = 'Email atau password salah';
      if (msg.includes('Email not confirmed'))       msg = 'Email belum diverifikasi — cek inbox kamu';
      if (msg.includes('User already registered'))   msg = 'Email sudah terdaftar — coba login';
      setErr(msg); setLoading(false);
    }
  }

  async function handleMagicLink(e) {
    e && e.preventDefault();
    if (!validEmail) return;
    setLoading(true); setErr('');
    try {
      var r = await window.SB.auth.signInWithOtp({
        email, options: { emailRedirectTo: window.location.origin }
      });
      if (r.error) throw r.error;
      setSent(true); setLoading(false);
    } catch(e) {
      var msg = e.message || 'Gagal';
      if (msg.includes('rate limit')) msg = 'Terlalu banyak percobaan, tunggu beberapa menit';
      setErr(msg); setLoading(false);
    }
  }

  async function handleGoogle() {
    setLoading(true); setErr('');
    try {
      if (!window.SB) throw new Error('Koneksi belum siap');
      var r = await window.SB.auth.signInWithOAuth({
        provider: 'google',
        options: { redirectTo: window.location.origin },
      });
      if (r.error) throw r.error;
    } catch(e) {
      setErr(e.message || 'Gagal login dengan Google'); setLoading(false);
    }
  }

  // ── Sent confirmation ───────────────────────────────────────────
  if (sent) return (
    <div style={{ background: T.bg, minHeight:'100%', display:'flex', flexDirection:'column',
                  alignItems:'center', justifyContent:'center', padding:'40px 28px', textAlign:'center' }}>
      <div style={{ width:72, height:72, borderRadius:24, background:accent.tint,
                    display:'flex', alignItems:'center', justifyContent:'center', marginBottom:20 }}>
        <span style={{ fontSize:36 }}>{isSignup ? '🎉' : '✉️'}</span>
      </div>
      <div style={{ fontSize:20, fontWeight:800, color:T.fg1, letterSpacing:'-0.02em', marginBottom:8 }}>
        {isSignup ? 'Cek email kamu!' : 'Link terkirim!'}
      </div>
      <div style={{ fontSize:14, color:T.fg2, lineHeight:1.6, marginBottom:24 }}>
        {isSignup
          ? <>Kami kirim link verifikasi ke <strong>{email}</strong>. Klik link tersebut lalu kembali ke sini untuk login.</>
          : <>Kami kirim magic link ke <strong>{email}</strong>. Klik link di email untuk masuk.</>
        }
      </div>
      <button onClick={() => { setSent(false); setMode('main'); reset(); }}
        style={{ color:accent[500], fontSize:14, fontWeight:600, background:'none', border:'none', cursor:'pointer' }}>
        ← Kembali ke login
      </button>
    </div>
  );

  // ── Shared styles ───────────────────────────────────────────────
  const inputStyle = {
    width:'100%', height:50, borderRadius:12, border:`1.5px solid ${T.border}`,
    background:T.bg, color:T.fg1, fontSize:15, fontWeight:500,
    padding:'0 14px', outline:'none', fontFamily:'inherit',
    transition:'border-color 0.15s',
  };
  const btnPrimary = (active) => ({
    width:'100%', height:52, borderRadius:14, border:0,
    cursor: active && !loading ? 'pointer' : 'not-allowed',
    background: active ? `linear-gradient(135deg,${accent.grad[0]},${accent.grad[1]})` : T.surfaceAlt,
    color: active ? '#fff' : T.fg4,
    fontSize:15, fontWeight:700, letterSpacing:'-0.005em',
    boxShadow: active ? `0 6px 20px ${accent[500]}44` : 'none',
    display:'flex', alignItems:'center', justifyContent:'center', gap:8,
    opacity: loading ? 0.7 : 1, transition:'all 0.15s',
  });
  const spinner = (
    <div style={{width:18,height:18,border:'2.5px solid rgba(255,255,255,0.35)',
                 borderTopColor:'#fff',borderRadius:'50%',animation:'spin 0.7s linear infinite'}}/>
  );

  // ── Main screen ─────────────────────────────────────────────────
  if (mode === 'main') return (
    <div style={{ background:T.bg, minHeight:'100%', display:'flex', flexDirection:'column',
                  padding:'80px 28px 40px' }}>
      {/* Brand */}
      <div style={{ display:'flex', flexDirection:'column', alignItems:'center', marginBottom:40 }}>
        <CashBadge size={68} accent={accent} />
        <div style={{ marginTop:12 }}><CashWordmark size={24} color={T.fg1} /></div>
        <div style={{ marginTop:5, fontSize:12, color:T.fg3, fontWeight:500, letterSpacing:'0.02em' }}>
          Catatan keuangan keluarga
        </div>
      </div>

      <h1 style={{ fontSize:24, fontWeight:800, color:T.fg1, letterSpacing:'-0.025em',
                   marginBottom:6, textAlign:'center' }}>
        Selamat datang
      </h1>
      <p style={{ fontSize:13, color:T.fg3, textAlign:'center', marginBottom:28, lineHeight:1.5 }}>
        Masuk atau daftar untuk mulai catat keuangan keluarga
      </p>

      <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
        {/* Google */}
        <button onClick={handleGoogle} disabled={loading} style={{
          height:52, borderRadius:14, border:`1.5px solid ${T.border}`,
          background:T.surface, cursor:'pointer',
          display:'flex', alignItems:'center', justifyContent:'center', gap:10,
          fontSize:15, fontWeight:700, color:T.fg1,
          boxShadow:`0 2px 8px rgba(0,0,0,0.06)`, opacity:loading?0.6:1,
        }}>
          <svg width="20" height="20" viewBox="0 0 48 48">
            <path fill="#EA4335" d="M24 9.5c3.5 0 6.6 1.2 9.1 3.2l6.8-6.8C35.8 2.4 30.2 0 24 0 14.8 0 7 5.4 3.2 13.2l7.9 6.2C13 13.4 18.1 9.5 24 9.5z"/>
            <path fill="#4285F4" d="M46.5 24.5c0-1.6-.1-3.2-.4-4.7H24v9h12.7c-.6 3-2.3 5.5-4.8 7.2l7.6 5.9c4.5-4.1 7-10.2 7-17.4z"/>
            <path fill="#FBBC05" d="M11.1 28.6A14.7 14.7 0 0 1 9.5 24c0-1.6.3-3.2.7-4.6l-7.9-6.2A23.9 23.9 0 0 0 0 24c0 3.9.9 7.5 2.5 10.8l8.6-6.2z"/>
            <path fill="#34A853" d="M24 48c6.2 0 11.4-2 15.2-5.5l-7.6-5.9c-2 1.4-4.7 2.2-7.6 2.2-5.9 0-10.9-3.9-12.7-9.2l-8.6 6.2C7 42.6 14.8 48 24 48z"/>
          </svg>
          Lanjut dengan Google
        </button>

        {/* Email + Password */}
        <button onClick={() => { setMode('password'); setIsSignup(false); reset(); }} style={{
          height:52, borderRadius:14,
          background:`linear-gradient(135deg,${accent.grad[0]},${accent.grad[1]})`,
          border:0, cursor:'pointer',
          display:'flex', alignItems:'center', justifyContent:'center', gap:10,
          fontSize:15, fontWeight:700, color:'#fff',
          boxShadow:`0 6px 20px ${accent[500]}44`,
        }}>
          🔑 Masuk dengan Password
        </button>

        {/* Magic link */}
        <button onClick={() => { setMode('magic'); reset(); }} style={{
          height:52, borderRadius:14, border:`1.5px solid ${T.border}`,
          background:'transparent', cursor:'pointer',
          fontSize:14, fontWeight:600, color:T.fg2,
        }}>
          ✉️ Kirim Magic Link
        </button>
      </div>

      {/* Divider + demo */}
      <div style={{ flex:1 }}/>
      <button onClick={onContinue} style={{
        marginTop:20, width:'100%', height:40, borderRadius:12,
        border:`1px solid ${T.border}`, background:'transparent',
        color:T.fg4, fontSize:12, fontWeight:500, cursor:'pointer',
      }}>
        Lihat demo dulu →
      </button>
    </div>
  );

  // ── Password mode ───────────────────────────────────────────────
  if (mode === 'password') return (
    <div style={{ background:T.bg, minHeight:'100%', display:'flex', flexDirection:'column',
                  padding:'60px 28px 40px' }}>
      <button onClick={() => { setMode('main'); reset(); }}
        style={{ background:'none', border:'none', cursor:'pointer', color:T.fg3,
                 fontSize:14, fontWeight:600, textAlign:'left', marginBottom:28, padding:0 }}>
        ← Kembali
      </button>

      <h2 style={{ fontSize:22, fontWeight:800, color:T.fg1, letterSpacing:'-0.025em', marginBottom:4 }}>
        {isSignup ? 'Buat akun baru' : 'Masuk dengan password'}
      </h2>
      <p style={{ fontSize:13, color:T.fg3, marginBottom:24, lineHeight:1.5 }}>
        {isSignup ? 'Daftar dengan email dan password' : 'Masuk ke akun INDIECASH kamu'}
      </p>

      <form onSubmit={handlePassword} style={{ display:'flex', flexDirection:'column', gap:12 }}>
        <div>
          <div style={{ fontSize:12, fontWeight:600, color:T.fg3, marginBottom:6,
                        textTransform:'uppercase', letterSpacing:'0.05em' }}>Email</div>
          <input type="email" value={email} onChange={e => setEmail(e.target.value)}
            placeholder="kamu@email.com" autoFocus
            style={inputStyle} />
        </div>
        <div>
          <div style={{ fontSize:12, fontWeight:600, color:T.fg3, marginBottom:6,
                        textTransform:'uppercase', letterSpacing:'0.05em' }}>Password</div>
          <div style={{ position:'relative' }}>
            <input type={showPass ? 'text' : 'password'} value={password}
              onChange={e => setPass(e.target.value)}
              placeholder={isSignup ? 'Minimal 6 karakter' : 'Password kamu'}
              style={{ ...inputStyle, paddingRight:44 }} />
            <button type="button" onClick={() => setShowPass(v => !v)}
              style={{ position:'absolute', right:12, top:'50%', transform:'translateY(-50%)',
                       background:'none', border:'none', cursor:'pointer', color:T.fg4,
                       fontSize:16, padding:4 }}>
              {showPass ? '🙈' : '👁'}
            </button>
          </div>
          {isSignup && password.length > 0 && password.length < 6 && (
            <div style={{ fontSize:11, color:'#f59e0b', marginTop:4 }}>Minimal 6 karakter</div>
          )}
        </div>

        {err && (
          <div style={{ background:'rgba(239,68,68,0.08)', border:'1px solid rgba(239,68,68,0.2)',
                        borderRadius:10, padding:'10px 12px', fontSize:13, color:'#ef4444' }}>
            {err}
          </div>
        )}

        <button type="submit" disabled={!validEmail || password.length < 6 || loading}
          style={btnPrimary(validEmail && password.length >= 6)}>
          {loading ? spinner : (isSignup ? '🎉 Buat Akun' : '🔑 Masuk')}
        </button>
      </form>

      {/* Toggle signup/login */}
      <div style={{ textAlign:'center', marginTop:20, fontSize:13, color:T.fg3 }}>
        {isSignup ? (
          <>Sudah punya akun?{' '}
            <button onClick={() => { setIsSignup(false); reset(); }}
              style={{ color:accent[500], fontWeight:700, background:'none', border:'none',
                       cursor:'pointer', fontSize:13 }}>
              Masuk di sini
            </button>
          </>
        ) : (
          <>Belum punya akun?{' '}
            <button onClick={() => { setIsSignup(true); reset(); }}
              style={{ color:accent[500], fontWeight:700, background:'none', border:'none',
                       cursor:'pointer', fontSize:13 }}>
              Daftar gratis
            </button>
          </>
        )}
      </div>

      {/* Forgot password placeholder */}
      {!isSignup && (
        <div style={{ textAlign:'center', marginTop:10 }}>
          <button onClick={() => { setMode('magic'); setErr(''); }}
            style={{ color:T.fg4, fontSize:12, background:'none', border:'none',
                     cursor:'pointer', textDecoration:'underline' }}>
            Lupa password? Kirim magic link →
          </button>
        </div>
      )}
    </div>
  );

  // ── Magic link mode ─────────────────────────────────────────────
  return (
    <div style={{ background:T.bg, minHeight:'100%', display:'flex', flexDirection:'column',
                  padding:'60px 28px 40px' }}>
      <button onClick={() => { setMode('main'); reset(); }}
        style={{ background:'none', border:'none', cursor:'pointer', color:T.fg3,
                 fontSize:14, fontWeight:600, textAlign:'left', marginBottom:28, padding:0 }}>
        ← Kembali
      </button>

      <h2 style={{ fontSize:22, fontWeight:800, color:T.fg1, letterSpacing:'-0.025em', marginBottom:4 }}>
        Kirim Magic Link
      </h2>
      <p style={{ fontSize:13, color:T.fg3, marginBottom:24, lineHeight:1.5 }}>
        Kami kirim link login ke email kamu — tanpa perlu password.
      </p>

      <form onSubmit={handleMagicLink} style={{ display:'flex', flexDirection:'column', gap:12 }}>
        <div>
          <div style={{ fontSize:12, fontWeight:600, color:T.fg3, marginBottom:6,
                        textTransform:'uppercase', letterSpacing:'0.05em' }}>Email</div>
          <input type="email" value={email} onChange={e => setEmail(e.target.value)}
            placeholder="kamu@email.com" autoFocus style={inputStyle} />
        </div>

        {err && (
          <div style={{ background:'rgba(239,68,68,0.08)', border:'1px solid rgba(239,68,68,0.2)',
                        borderRadius:10, padding:'10px 12px', fontSize:13, color:'#ef4444' }}>
            {err}
          </div>
        )}

        <button type="submit" disabled={!validEmail || loading}
          style={btnPrimary(validEmail)}>
          {loading ? spinner : '✉️ Kirim Magic Link'}
        </button>
      </form>
    </div>
  );
}

// ─── ONBOARDING ───────────────────────────────────────────────────
function ScreenOnboarding({ theme, accent, onPick, auth }) {
  const T = theme;
  const [step, setStep]           = React.useState('choice');
  const [familyName, setFamilyName] = React.useState('');
  const [inviteCode, setInviteCode] = React.useState('');
  const [loading, setLoading]     = React.useState(false);
  const [err, setErr]             = React.useState('');
  const realAuth = auth || {};

  async function handleCreate() {
    if (!familyName.trim()) return;
    setLoading(true); setErr('');
    if (realAuth.createFamily && realAuth.user) {
      var r = await realAuth.createFamily(familyName.trim(), realAuth.user.id);
      if (r.error) { setErr(r.error.message || 'Gagal membuat keluarga'); setLoading(false); return; }
    }
    onPick('create'); setLoading(false);
  }

  async function handleJoin() {
    if (inviteCode.length < 6) return;
    setLoading(true); setErr('');
    if (realAuth.joinFamily && realAuth.user) {
      var r = await realAuth.joinFamily(inviteCode, realAuth.user.id);
      if (r.error) { setErr(r.error.message || 'Kode tidak valid'); setLoading(false); return; }
    }
    onPick('join'); setLoading(false);
  }

  const spinner = (
    <div style={{width:18,height:18,border:'2.5px solid rgba(255,255,255,0.35)',
                 borderTopColor:'#fff',borderRadius:'50%',animation:'spin 0.7s linear infinite'}}/>
  );

  return (
    <div style={{ background:T.bg, minHeight:'100%', padding:'64px 24px 32px',
                  display:'flex', flexDirection:'column' }}>
      <div style={{ marginBottom: 18 }}>
        <CashBadge size={48} accent={accent} />
      </div>
      <h1 style={{ margin:0, fontSize:28, fontWeight:800, letterSpacing:'-0.03em',
                   lineHeight:1.15, color:T.fg1 }}>
        Mulai catat<br/>bareng keluarga
      </h1>
      <p style={{ margin:'10px 0 28px', fontSize:14, color:T.fg2, lineHeight:1.55 }}>
        Buat keluarga baru, atau gabung pakai kode dari pasangan/anggota lain.
      </p>

      <div style={{ display:'flex', flexDirection:'column', gap:12 }}>
        {/* Card: Buat baru */}
        <button onClick={() => { setStep('create'); setErr(''); }} style={{
          appearance:'none', border:`1px solid ${T.border}`,
          background:T.surface, padding:18, borderRadius:18, cursor:'pointer',
          textAlign:'left', boxShadow:T.shadow2, position:'relative', overflow:'hidden',
        }}>
          <div style={{ position:'absolute', top:-20, right:-20, width:110, height:110,
                        borderRadius:'50%', background:accent.tint }} />
          <div style={{ position:'relative' }}>
            <div style={{ width:44, height:44, borderRadius:14, marginBottom:12,
                          background:`linear-gradient(135deg,${accent.grad[0]},${accent.grad[1]})`,
                          display:'flex', alignItems:'center', justifyContent:'center' }}>
              <span style={{fontSize:22}}>🏠</span>
            </div>
            <div style={{ fontSize:16, fontWeight:800, color:T.fg1, letterSpacing:'-0.015em' }}>
              Buat keluarga baru
            </div>
            <div style={{ fontSize:12, color:T.fg2, fontWeight:500, marginTop:4, lineHeight:1.5 }}>
              Mulai dari nol — kamu jadi admin, undang anggota lewat kode.
            </div>
            <div style={{ marginTop:10, fontSize:12, fontWeight:700, color:accent[600] }}>
              Mulai sekarang →
            </div>
          </div>
        </button>

        {/* Card: Gabung */}
        <button onClick={() => { setStep('join'); setErr(''); }} style={{
          appearance:'none', border:`1px solid ${T.border}`,
          background:T.surface, padding:18, borderRadius:18, cursor:'pointer',
          textAlign:'left', boxShadow:T.shadow1,
        }}>
          <div style={{ width:44, height:44, borderRadius:14, marginBottom:12,
                        background:T.surfaceAlt,
                        display:'flex', alignItems:'center', justifyContent:'center' }}>
            <span style={{fontSize:22}}>🎟️</span>
          </div>
          <div style={{ fontSize:16, fontWeight:800, color:T.fg1, letterSpacing:'-0.015em' }}>
            Gabung pakai kode
          </div>
          <div style={{ fontSize:12, color:T.fg2, fontWeight:500, marginTop:4, lineHeight:1.5 }}>
            Sudah dapat kode dari keluarga? Masukkan di sini.
          </div>
        </button>
      </div>

      {/* Create family sheet */}
      {step === 'create' && (
        <div style={{ position:'fixed', inset:0, zIndex:99, background:'rgba(0,0,0,0.5)',
                      display:'flex', alignItems:'flex-end', justifyContent:'center' }}
          onClick={e => { if(e.target===e.currentTarget) setStep('choice'); }}>
          <div style={{ background:T.surface, borderRadius:'24px 24px 0 0',
                        padding:'24px 20px 48px', width:'100%', maxWidth:480 }}>
            <div style={{ width:40, height:4, background:T.border, borderRadius:99,
                          margin:'0 auto 20px' }}/>
            <div style={{ fontSize:18, fontWeight:800, color:T.fg1, marginBottom:16 }}>
              Nama Keluarga
            </div>
            <input type="text" placeholder="Misal: Keluarga Kristofer"
              value={familyName} onChange={e => setFamilyName(e.target.value)}
              autoFocus
              onKeyDown={e => e.key==='Enter' && handleCreate()}
              style={{ width:'100%', border:`1.5px solid ${T.border}`, borderRadius:12,
                       padding:'12px 14px', fontSize:15, fontFamily:'inherit',
                       background:T.bg, color:T.fg1, outline:'none', marginBottom:12 }}/>
            {err && <div style={{color:'#ef4444',fontSize:12,marginBottom:8}}>{err}</div>}
            <button onClick={handleCreate} disabled={!familyName.trim() || loading}
              style={{ width:'100%', height:50, borderRadius:14, border:0, cursor:'pointer',
                       background: familyName.trim() && !loading
                         ? `linear-gradient(135deg,${accent.grad[0]},${accent.grad[1]})` : '#ccc',
                       color:'#fff', fontSize:15, fontWeight:700,
                       display:'flex', alignItems:'center', justifyContent:'center', gap:8 }}>
              {loading ? spinner : '🏠 Buat Keluarga'}
            </button>
          </div>
        </div>
      )}

      {/* Join family sheet */}
      {step === 'join' && (
        <div style={{ position:'fixed', inset:0, zIndex:99, background:'rgba(0,0,0,0.5)',
                      display:'flex', alignItems:'flex-end', justifyContent:'center' }}
          onClick={e => { if(e.target===e.currentTarget) setStep('choice'); }}>
          <div style={{ background:T.surface, borderRadius:'24px 24px 0 0',
                        padding:'24px 20px 48px', width:'100%', maxWidth:480 }}>
            <div style={{ width:40, height:4, background:T.border, borderRadius:99,
                          margin:'0 auto 20px' }}/>
            <div style={{ fontSize:18, fontWeight:800, color:T.fg1, marginBottom:4 }}>
              Masukkan Kode
            </div>
            <div style={{ fontSize:13, color:T.fg3, marginBottom:16 }}>
              Minta kode undangan dari admin keluarga kamu
            </div>
            <input type="text" placeholder="Contoh: A1B2C3D4"
              value={inviteCode} onChange={e => setInviteCode(e.target.value.toUpperCase())}
              maxLength={8} autoFocus
              onKeyDown={e => e.key==='Enter' && handleJoin()}
              style={{ width:'100%', border:`1.5px solid ${T.border}`, borderRadius:12,
                       padding:'12px 14px', fontSize:22, fontWeight:800,
                       fontFamily:'monospace', letterSpacing:'0.25em', textAlign:'center',
                       background:T.bg, color:T.fg1, outline:'none', marginBottom:12 }}/>
            {err && <div style={{color:'#ef4444',fontSize:12,marginBottom:8}}>{err}</div>}
            <button onClick={handleJoin} disabled={inviteCode.length<6 || loading}
              style={{ width:'100%', height:50, borderRadius:14, border:0, cursor:'pointer',
                       background: inviteCode.length>=6 && !loading
                         ? `linear-gradient(135deg,${accent.grad[0]},${accent.grad[1]})` : '#ccc',
                       color:'#fff', fontSize:15, fontWeight:700,
                       display:'flex', alignItems:'center', justifyContent:'center', gap:8 }}>
              {loading ? spinner : '🎟️ Gabung'}
            </button>
          </div>
        </div>
      )}

      <div style={{ flex:1 }} />
      <div style={{ marginTop:24, padding:14, borderRadius:14, background:accent.tint,
                    display:'flex', alignItems:'flex-start', gap:10 }}>
        <span style={{fontSize:16, flexShrink:0}}>💡</span>
        <div style={{ fontSize:12, color:T.fg2, fontWeight:500, lineHeight:1.5 }}>
          <strong style={{color:T.fg1}}>Kenapa keluarga?</strong> Semua anggota lihat
          saldo & transaksi yang sama — nggak ada lagi "lupa kasih tahu pasangan."
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { ScreenMore, ScreenLogin, ScreenOnboarding });
