// MODIBU - Screens (Landing, Lobby, TeacherPanel, Results)
const { useState: useStateS, useEffect: useEffectS } = React;

const PLAYER_COLORS = ['#FF6B6B', '#4DABF7', '#51CF66', '#FFD93D']; // Red, Blue, Green, Yellow
const PLAYER_ICONS = ['/car.png', '/cruise.png', '/motorbike.png', '/train.png'];
const PLAYER_NAMES_ID = ['Merah', 'Biru', 'Hijau', 'Kuning'];

// ============ Landing ============
function LandingScreen({ onPickRole, onReset }) {
  return (
    <div style={{ position: 'relative', minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', padding: '40px 0 140px', overflow: 'hidden' }}>
      <CloudBG /><Skyline />
      <div style={{ position: 'relative', zIndex: 2, textAlign: 'center', maxWidth: 620, padding: '0 24px' }}>
        <div style={{ display: 'flex', justifyContent: 'center', gap: 8, marginBottom: 18 }}>
          <Chip color="#FF6B6B" label="Anti-Cyberbullying" />
          <Chip color="#4DABF7" label="Bimbingan Konseling" />
        </div>
        <div style={{ marginBottom: 16 }}><ModibuLogo size={48} withTagline={true} /></div>
        <p style={{ color: 'var(--ink-soft)', fontSize: 15, lineHeight: 1.6, maxWidth: 460, margin: '20px auto 36px' }}>
          Belajar mengenali, mencegah, dan melawan cyberbullying melalui permainan papan digital yang seru — bersama teman dan Guru BK.
        </p>
        <div style={{ display: 'flex', gap: 16, justifyContent: 'center', flexWrap: 'wrap', marginBottom: 40 }}>
          <RoleCard color="orange" icon="🎲" title="Mulai sebagai Siswa" desc="Masukkan nama 4 pemain dan mulai bermain" onClick={() => onPickRole('siswa')} />
          <RoleCard color="blue" icon="🎓" title="Mulai sebagai Guru BK" desc="Buat sesi, pantau, dan nilai jawaban siswa" onClick={() => onPickRole('guru')} />
        </div>
        {/* {onReset && (
          <button onClick={onReset} style={{ background:'transparent', border:'none', color:'var(--ink-soft)', textDecoration:'underline', cursor:'pointer', fontSize:13 }}>
            🔄 Reset Permainan (Hapus Data Sesi)
          </button>
        )} */}
      </div>
    </div>
  );
}

function RoleCard({ color, icon, title, desc, onClick }) {
  const accent = color === 'orange' ? '#FFA94D' : '#4DABF7';
  const accentDeep = color === 'orange' ? '#E8852C' : '#1971C2';
  return (
    <button onClick={onClick} style={{ background: 'white', border: `4px solid ${accent}`, borderRadius: 24, padding: '24px 28px', width: 260, cursor: 'pointer', textAlign: 'left', fontFamily: 'inherit', boxShadow: `0 6px 0 ${accentDeep}, 0 10px 24px rgba(0,0,0,0.10)`, transition: 'transform 0.1s' }}
      onMouseDown={e => e.currentTarget.style.transform = 'translateY(2px)'}
      onMouseUp={e => e.currentTarget.style.transform = ''}
      onMouseLeave={e => e.currentTarget.style.transform = ''}>
      <div style={{ width: 56, height: 56, borderRadius: '50%', background: accent, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 30, marginBottom: 10, border: '3px solid white', boxShadow: `0 4px 0 ${accentDeep}` }}>{icon}</div>
      <div className="h-title" style={{ fontSize: 18, marginBottom: 4 }}>{title}</div>
      <div style={{ color: 'var(--ink-soft)', fontSize: 13.5, lineHeight: 1.5 }}>{desc}</div>
    </button>
  );
}

// ============ Lobby ============
function LobbyScreen({ role, sessionCode, onStart, onBack }) {
  const [names, setNames] = useStateS(['', '', '', '']);
  const allFilled = names.every(n => n.trim().length >= 2);

  const handleStart = () => {
    if (allFilled) onStart(names.map(n => n.trim()));
  };

  return (
    <div style={{ position: 'relative', minHeight: '100vh', padding: '32px 0 100px', overflow: 'hidden' }}>
      <CloudBG /><Skyline />

      {onBack && (
        <div style={{ position: 'absolute', top: 24, left: 24, zIndex: 10 }}>
          <button
            onClick={onBack}
            style={{
              background: 'white',
              border: '3px solid #4DABF7',
              borderRadius: '20px',
              padding: '10px 18px',
              display: 'flex',
              alignItems: 'center',
              gap: 8,
              fontSize: '15px',
              fontFamily: 'Fredoka',
              fontWeight: 700,
              color: '#4DABF7',
              cursor: 'pointer',
              boxShadow: '0 5px 0 #4DABF788',
              transition: 'all 0.15s ease',
              textTransform: 'uppercase',
              letterSpacing: '0.05em'
            }}
            onMouseEnter={e => {
              e.currentTarget.style.transform = 'translateY(-2px)';
              e.currentTarget.style.boxShadow = '0 7px 0 #4DABF788';
            }}
            onMouseLeave={e => {
              e.currentTarget.style.transform = 'translateY(0)';
              e.currentTarget.style.boxShadow = '0 5px 0 #4DABF788';
            }}
            onMouseDown={e => {
              e.currentTarget.style.transform = 'translateY(3px)';
              e.currentTarget.style.boxShadow = '0 2px 0 #4DABF788';
            }}
            onMouseUp={e => {
              e.currentTarget.style.transform = 'translateY(-2px)';
              e.currentTarget.style.boxShadow = '0 7px 0 #4DABF788';
            }}
          >
            <span style={{ fontSize: 20 }}>←</span>
            <span>Kembali</span>
          </button>
        </div>
      )}

      <div style={{ position: 'relative', zIndex: 2, maxWidth: 720, margin: '0 auto', padding: '0 24px' }}>
        <div style={{ textAlign: 'center', marginBottom: 28 }}>
          <div className="chip" style={{ background: 'white', fontSize: 12, marginBottom: 8 }}>
            <span className="chip-dot" style={{ background: role === 'guru' ? '#4DABF7' : '#FFA94D' }} />
            {role === 'guru' ? 'Mode Guru BK' : 'Mode Siswa'}
          </div>
          <h1 className="h-title" style={{ fontSize: 32, margin: '4px 0 6px' }}>Ruang Tunggu</h1>
          <p style={{ color: 'var(--ink-soft)', fontSize: 14.5, margin: 0 }}>
            {role === 'guru' ? 'Masukkan nama 4 siswa untuk memulai sesi' : 'Masukkan nama 4 pemain untuk memulai permainan'}
          </p>
        </div>

        <div style={{ textAlign: 'center', marginBottom: 32 }}>
          <div className="session-code">{sessionCode}</div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 14, marginBottom: 28 }}>
          {names.map((name, idx) => (
            <div key={idx} style={{ background: 'white', border: '3px solid white', borderRadius: 18, padding: '16px 18px', display: 'flex', alignItems: 'center', gap: 14, boxShadow: '0 4px 12px rgba(0,0,0,0.06)', minHeight: 88 }}>
              <Avatar color={PLAYER_COLORS[idx]} label={PLAYER_ICONS[idx]} size={56} />
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 12.5, color: 'var(--ink-soft)', textTransform: 'capitalize', marginBottom: 4 }}>
                  Pion {PLAYER_NAMES_ID[idx]}
                </div>
                <input
                  type="text" value={name}
                  onChange={e => { const n = [...names]; n[idx] = e.target.value; setNames(n); }}
                  placeholder={`Nama pemain ${idx + 1}`}
                  style={{ width: '100%', border: '2px solid #E5EEF4', borderRadius: 10, padding: '8px 12px', fontSize: 15, fontFamily: 'Fredoka', fontWeight: 600, color: 'var(--ink)', outline: 'none' }}
                  onFocus={e => e.target.style.borderColor = '#FFA94D'}
                  onBlur={e => e.target.style.borderColor = '#E5EEF4'}
                />
              </div>
              {name.trim().length >= 2 && (
                <div style={{ background: '#EBFBEE', color: '#2F9E44', padding: '3px 9px', borderRadius: 999, fontFamily: 'Fredoka', fontWeight: 700, fontSize: 10 }}>● SIAP</div>
              )}
            </div>
          ))}
        </div>

        <div style={{ textAlign: 'center' }}>
          <button className="btn btn-primary btn-lg" onClick={handleStart} disabled={!allFilled} style={{ opacity: allFilled ? 1 : 0.5 }}>
            🎲 Mulai Permainan
          </button>
          <div style={{ marginTop: 10, fontSize: 12, color: 'var(--ink-soft)' }}>
            {allFilled ? 'Semua pemain siap!' : 'Isi nama minimal 2 huruf untuk setiap pemain'}
          </div>
        </div>
      </div>
    </div>
  );
}

// ============ Teacher Panel ============
function TeacherPanel({ players, currentTurnIdx, sessionCode, round, gradingQueue, gameLog, onGrade, onBack, onEndGame, onManualPoints, onTriggerMaterial, onReset }) {
  const [tab, setTab] = useStateS('antrian');
  return (
    <div style={{ position: 'relative', minHeight: '100vh', padding: '24px 0' }}>
      <CloudBG density="sparse" />
      <div style={{ position: 'relative', zIndex: 2, maxWidth: 1100, margin: '0 auto', padding: '0 24px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20, flexWrap: 'wrap', gap: 12 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <button className="icon-btn orange" onClick={onBack}>←</button>
            <div>
              <div className="h-title" style={{ fontSize: 26 }}>Panel Guru BK</div>
              <div style={{ color: 'var(--ink-soft)', fontSize: 13 }}>Sesi <strong>{sessionCode}</strong> · 4 pemain · Ronde {round}</div>
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            {/* <button className="btn btn-ghost btn-sm" onClick={onReset}>Reset</button> */}
            <button className="btn btn-red btn-sm" onClick={onEndGame}>Akhiri Sesi</button>
          </div>
        </div>

        <div style={{ display: 'flex', gap: 8, marginBottom: 18, flexWrap: 'wrap' }}>
          {[
            { id: 'antrian', label: '📥 Antrian Nilai', badge: gradingQueue.length },
            { id: 'monitor', label: '🎮 Monitor Papan' },
            { id: 'poin', label: '➕ Set Poin' },
            { id: 'materi', label: '💡 Trigger Materi' },
          ].map(t => (
            <button key={t.id} onClick={() => setTab(t.id)} className="btn btn-sm"
              style={{ background: tab === t.id ? 'var(--ink)' : 'white', color: tab === t.id ? 'white' : 'var(--ink)', boxShadow: tab === t.id ? '0 4px 0 #000' : '0 3px 0 rgba(0,0,0,0.06)', border: tab === t.id ? '3px solid white' : '2px solid #E5EEF4', position: 'relative' }}>
              {t.label}
              {t.badge > 0 && <span style={{ marginLeft: 8, background: '#FF6B6B', color: 'white', padding: '2px 8px', borderRadius: 999, fontSize: 11, fontWeight: 800 }}>{t.badge}</span>}
            </button>
          ))}
        </div>

        {tab === 'antrian' && <GradingQueuePanel queue={gradingQueue} onGrade={onGrade} />}
        {tab === 'monitor' && <BoardMonitorPanel players={players} currentTurnIdx={currentTurnIdx} gameLog={gameLog} />}
        {tab === 'poin' && <ManualPointsPanelReal players={players} onManualPoints={onManualPoints} />}
        {tab === 'materi' && <MaterialTriggerPanel onTrigger={onTriggerMaterial} />}
      </div>
    </div>
  );
}

function GradingQueuePanel({ queue, onGrade }) {
  if (queue.length === 0) {
    return (
      <div className="card" style={{ textAlign: 'center', padding: '60px 24px' }}>
        <div className="h-title" style={{ fontSize: 20 }}>Semua jawaban sudah dinilai!</div>
        <div style={{ color: 'var(--ink-soft)', fontSize: 14, marginTop: 4 }}>Tunggu giliran pemain berikutnya.</div>
      </div>
    );
  }
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      {queue.map(s => (
        <div key={s.id} className="card" style={{ padding: 22 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 12 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <Avatar color={s.player.color} label={s.player.icon} size={42} />
              <div>
                <div style={{ fontFamily: 'Fredoka', fontWeight: 700, fontSize: 16 }}>{s.player.name}</div>
                <div style={{ fontSize: 12, color: 'var(--ink-soft)' }}>{s.type === 'tantangan' ? 'Tantangan' : 'Refleksi'}</div>
              </div>
            </div>
            <Chip color={s.type === 'tantangan' ? 'var(--c-tantangan)' : 'var(--c-refleksi)'} label={s.type.toUpperCase()} />
          </div>
          <div style={{ background: '#F8F9FA', borderRadius: 14, padding: 14, fontSize: 13, color: 'var(--ink-soft)', marginBottom: 10, lineHeight: 1.5 }}>
            <strong style={{ color: 'var(--ink)' }}>Soal:</strong> {s.question}
          </div>
          <div style={{ background: 'white', border: '2px solid #E5EEF4', borderRadius: 14, padding: 14, fontSize: 14.5, lineHeight: 1.6, marginBottom: 14 }}>{s.answer}</div>
          <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
            <button className="btn btn-green btn-sm" onClick={() => onGrade(s.id, 20)}>✓ Benar (+20)</button>
            <button className="btn btn-blue btn-sm" onClick={() => onGrade(s.id, 10)}>◐ Cukup (+10)</button>
            <button className="btn btn-red btn-sm" onClick={() => onGrade(s.id, 0)}>✗ Salah (+0)</button>
          </div>
        </div>
      ))}
    </div>
  );
}

function BoardMonitorPanel({ players, currentTurnIdx, gameLog }) {
  return (
    <div className="card" style={{ padding: 22 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 18 }}>
        <div className="h-title" style={{ fontSize: 20 }}>Monitor Permainan</div>
        <Chip color="#51CF66" label="Real-time · 4/4" />
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 12 }}>
        {players.map((p, idx) => (
          <div key={p.id} style={{ border: '2px solid #E5EEF4', borderRadius: 16, padding: 14, display: 'flex', alignItems: 'center', gap: 12 }}>
            <Avatar color={p.color} label={p.icon} size={44} active={idx === currentTurnIdx} />
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: 'Fredoka', fontWeight: 700, fontSize: 15 }}>{p.name}</div>
              <div style={{ fontSize: 11.5, color: 'var(--ink-soft)' }}>Kotak #{p.position} · {p.score} poin{p.isInJail ? ' · 🔒 Penjara' : ''}</div>
            </div>
            {idx === currentTurnIdx && <span style={{ background: '#FFA94D', color: 'white', padding: '3px 9px', borderRadius: 999, fontSize: 10, fontFamily: 'Fredoka', fontWeight: 700 }}>GILIRAN</span>}
          </div>
        ))}
      </div>
      <div style={{ marginTop: 18, padding: 14, background: '#F8F9FA', borderRadius: 14, fontSize: 13, lineHeight: 1.5, maxHeight: 200, overflowY: 'auto' }}>
        <strong>Log aktivitas:</strong>
        <div style={{ marginTop: 6, color: 'var(--ink-soft)' }}>
          {gameLog.slice(0, 10).map((l, i) => <div key={i}>• {l.time} — {l.msg}</div>)}
          {gameLog.length === 0 && <div>Belum ada aktivitas.</div>}
        </div>
      </div>
    </div>
  );
}

function ManualPointsPanelReal({ players, onManualPoints }) {
  const [selectedPlayer, setSelectedPlayer] = useStateS(0);
  const [amount, setAmount] = useStateS(5);
  return (
    <div className="card" style={{ padding: 22 }}>
      <div className="h-title" style={{ fontSize: 20, marginBottom: 14 }}>Atur Poin Manual</div>
      <div style={{ fontSize: 13.5, color: 'var(--ink-soft)', marginBottom: 18 }}>Tambah atau kurangi poin untuk situasi khusus.</div>
      <div style={{ marginBottom: 16 }}>
        <div style={{ fontFamily: 'Fredoka', fontWeight: 700, fontSize: 13, marginBottom: 8, color: 'var(--ink-soft)' }}>PILIH PEMAIN</div>
        <div style={{ display: 'flex', gap: 10, flexWrap: 'wrap' }}>
          {players.map((p, i) => (
            <button key={p.id} onClick={() => setSelectedPlayer(i)} style={{
              background: selectedPlayer === i ? `var(--p-${p.color === 'red' ? 'merah' : p.color === 'blue' ? 'biru' : p.color === 'green' ? 'hijau' : 'kuning'})` : 'white',
              border: selectedPlayer === i ? '3px solid var(--ink)' : '3px solid #E5EEF4',
              borderRadius: 18, padding: 12, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 10,
              color: selectedPlayer === i ? 'white' : 'var(--ink)', fontFamily: 'inherit', fontWeight: 600
            }}>
              <Avatar color={p.color} label={p.icon} size={32} />
              <span style={{ fontFamily: 'Fredoka', fontSize: 14 }}>{p.name}</span>
            </button>
          ))}
        </div>
      </div>
      <div style={{ marginBottom: 18 }}>
        <div style={{ fontFamily: 'Fredoka', fontWeight: 700, fontSize: 13, marginBottom: 8, color: 'var(--ink-soft)' }}>JUMLAH POIN</div>
        <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
          {[-10, -5, -2, +2, +5, +10, +20].map(v => (
            <button key={v} onClick={() => setAmount(v)} className={`btn btn-sm ${amount === v ? (v < 0 ? 'btn-red' : 'btn-green') : 'btn-ghost'}`} style={{ minWidth: 64 }}>
              {v > 0 ? '+' : ''}{v}
            </button>
          ))}
        </div>
      </div>
      <button className="btn btn-primary" onClick={() => onManualPoints(selectedPlayer, amount)}>
        Terapkan {amount > 0 ? '+' : ''}{amount} ke {players[selectedPlayer]?.name}
      </button>
    </div>
  );
}

function MaterialTriggerPanel({ onTrigger }) {
  const materials = [
    { id: 1, title: 'Apa itu Cyberbullying?', icon: '📱', color: '#51CF66' },
    { id: 2, title: 'Dampak Psikologis', icon: '💔', color: '#FF6B6B' },
    { id: 3, title: 'Cara Melapor', icon: '📋', color: '#4DABF7' },
    { id: 4, title: 'Empati Digital', icon: '💡', color: '#9775FA' },
    { id: 5, title: 'UU ITE Singkat', icon: '⚖️', color: '#FFA94D' },
    { id: 6, title: 'Tips Aman Medsos', icon: '🛡️', color: '#FF8FAB' },
  ];
  return (
    <div className="card" style={{ padding: 22 }}>
      <div className="h-title" style={{ fontSize: 20, marginBottom: 6 }}>Trigger Popup Materi</div>
      <div style={{ fontSize: 13.5, color: 'var(--ink-soft)', marginBottom: 18 }}>Tampilkan materi edukasi singkat di layar semua pemain.</div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 12 }}>
        {materials.map(m => (
          <button key={m.id} onClick={onTrigger} style={{ background: 'white', border: `3px solid ${m.color}`, borderRadius: 18, padding: 16, cursor: 'pointer', fontFamily: 'inherit', display: 'flex', alignItems: 'center', gap: 12, textAlign: 'left', boxShadow: `0 4px 0 ${m.color}55` }}>
            <div style={{ width: 44, height: 44, borderRadius: '50%', background: m.color, display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontSize: 22 }}>{m.icon}</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: 'Fredoka', fontWeight: 700, fontSize: 14.5 }}>{m.title}</div>
              <div style={{ fontSize: 11.5, color: 'var(--ink-soft)' }}>Tampilkan ke semua pemain</div>
            </div>
          </button>
        ))}
      </div>
    </div>
  );
}

// ============ Results ============
function ResultsScreen({ role, players, sessionCode, onPlayAgain, onHome, onReset }) {
  const ranked = [...(players || [])]
    .sort((a, b) => (b?.score || 0) - (a?.score || 0))
    .map((p, i) => ({ ...p, rank: i + 1 }));

  if (!ranked.length) {
    return (
      <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'white', fontFamily: 'Fredoka' }}>
        Memuat hasil...
      </div>
    );
  }

  return (
    <div style={{ position: 'relative', minHeight: '100vh', padding: '32px 0 100px', overflow: 'hidden' }}>
      <CloudBG /><Skyline />
      <ConfettiBackdrop />
      <div style={{ position: 'relative', zIndex: 2, maxWidth: 900, margin: '0 auto', padding: '0 24px' }}>
        <div style={{ textAlign: 'center', marginBottom: 28 }}>
          <Chip color="#FFA94D" label={`Sesi Selesai · ${sessionCode}`} />
          <h1 className="h-title" style={{ fontSize: 40, margin: '8px 0 6px' }}>Selamat! 🎉</h1>
          <p style={{ color: 'var(--ink-soft)', fontSize: 15, margin: 0 }}>Permainan selesai. Berikut hasil dan refleksi sesi kalian.</p>
        </div>

        {ranked.length >= 3 && (
          <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'center', gap: 18, marginBottom: 38, flexWrap: 'wrap' }}>
            {ranked[1] && <PodiumStep player={ranked[1]} height={140} accent="#ADB5BD" medal="🥈" />}
            {ranked[0] && <PodiumStep player={ranked[0]} height={180} accent="#FFD93D" medal="🥇" winner />}
            {ranked[2] && <PodiumStep player={ranked[2]} height={110} accent="#E8985C" medal="🥉" />}
          </div>
        )}

        <div className="card" style={{ padding: 22, marginBottom: 22 }}>
          <div className="h-title" style={{ fontSize: 18, marginBottom: 14 }}>Detail Skor</div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {ranked.map(p => (
              <div key={p.id} style={{ display: 'flex', alignItems: 'center', gap: 14, padding: 12, background: p.rank === 1 ? '#FFF8EB' : '#F8F9FA', border: p.rank === 1 ? '2.5px solid #FFD93D' : '2px solid transparent', borderRadius: 14 }}>
                <div style={{ width: 36, height: 36, borderRadius: '50%', background: 'white', border: '2.5px solid #E5EEF4', display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'Fredoka', fontWeight: 800, fontSize: 16 }}>{p.rank}</div>
                <Avatar color={p.color} label={p.icon} size={40} />
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: 'Fredoka', fontWeight: 700, fontSize: 15 }}>{p.name || 'Pemain'}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--ink-soft)' }}>
                    Edukasi: {p.stats?.edukasi || 0} · Fakta: {p.stats?.fakta || 0} · Tantangan: {p.stats?.tantangan || 0} · Refleksi: {p.stats?.refleksi || 0}
                  </div>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end' }}>
                  <div style={{ fontFamily: 'Fredoka', fontWeight: 700, fontSize: 20 }}>{p.score || 0}</div>
                  <div style={{ fontSize: 10.5, color: 'var(--ink-soft)' }}>poin</div>
                </div>
              </div>
            ))}
          </div>
        </div>

        <div style={{ background: 'linear-gradient(135deg, #FFF8EB 0%, #FFE5D9 100%)', border: '3px solid #FFA94D', borderRadius: 22, padding: 22, marginBottom: 22 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
            <span style={{ fontSize: 32 }}>💭</span>
            <div className="h-title" style={{ fontSize: 18 }}>Refleksi Bersama</div>
          </div>
          <p style={{ margin: 0, fontSize: 14.5, lineHeight: 1.6 }}>
            Cyberbullying bisa terjadi pada siapa saja, tapi kita semua punya kekuatan untuk menghentikannya.
            Mulai hari ini, mari jadi <strong>upstander</strong> — bukan sekadar bystander.
          </p>
        </div>

        <div style={{ textAlign: 'center', display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
          {role === 'guru' ? (
            <>
              <button className="btn btn-primary" onClick={onPlayAgain}>🎲 Main Lagi</button>
              <button className="btn btn-ghost" onClick={onReset}>🗑️ Hapus Sesi</button>
            </>
          ) : (
            <button className="btn btn-blue" onClick={onHome}>🏠 Kembali ke Beranda</button>
          )}
        </div>
      </div>
    </div>
  );
}

function PodiumStep({ player, height, accent, medal, winner }) {
  if (!player) return null;
  return (
    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', width: 180 }}>
      <div style={{ marginBottom: 8, fontSize: winner ? 44 : 32 }}>{medal}</div>
      <Avatar color={player.color} label={player.icon} size={winner ? 72 : 56} />
      <div style={{ fontFamily: 'Fredoka', fontWeight: 700, fontSize: winner ? 18 : 15, marginTop: 8, marginBottom: 4 }}>{player.name || 'Pemain'}</div>
      <div style={{ fontFamily: 'Fredoka', fontWeight: 700, fontSize: winner ? 26 : 20, color: accent, marginBottom: 10 }}>
        {player.score || 0} <span style={{ fontSize: 12, color: 'var(--ink-soft)' }}>poin</span>
      </div>
      <div style={{ width: '100%', height, background: `linear-gradient(180deg, ${accent} 0%, ${accent}99 100%)`, borderRadius: '18px 18px 0 0', display: 'flex', alignItems: 'flex-start', justifyContent: 'center', paddingTop: 16, color: 'white', fontFamily: 'Fredoka', fontWeight: 800, fontSize: winner ? 48 : 36, border: '3px solid white', boxShadow: `0 6px 0 ${accent}99` }}>
        {player.rank || '?'}
      </div>
    </div>
  );
}

function ConfettiBackdrop() {
  const dots = Array.from({ length: 24 }).map((_, i) => ({
    left: (i * 4.3 + (i % 3) * 12) % 100,
    top: (i * 7) % 90,
    color: ['#FF6B6B', '#4DABF7', '#FFD93D', '#51CF66', '#FF8FAB', '#9775FA'][i % 6],
    size: 10 + (i % 3) * 4,
    rot: i * 15
  }));
  return (
    <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none', zIndex: 1 }}>
      {dots.map((d, i) => (
        <div key={i} style={{
          position: 'absolute',
          left: `${d.left}%`,
          top: `${d.top}%`,
          width: d.size,
          height: d.size * 0.4,
          background: d.color,
          borderRadius: 2,
          transform: `rotate(${d.rot}deg)`,
          opacity: 0.7
        }} />
      ))}
    </div>
  );
}


// ============ Room Code Entry (Siswa) ============
function RoomCodeEntryScreen({ onBack, onJoin }) {
  const [code, setCode] = useStateS('');
  const [loading, setLoading] = useStateS(false);
  const [error, setError] = useStateS('');

  const handleJoin = async () => {
    const trimmed = code.trim().toUpperCase();
    if (trimmed.length < 3) return;
    setLoading(true);
    setError('');
    try {
      const res = await window.RoomAPI.getRoom(trimmed);
      if (res.success) {
        if (res.room.status === 'finished') {
          setError('Sesi ini sudah selesai. Minta kode baru dari Guru BK.');
        } else if (res.room.status === 'playing') {
          setError('Permainan sudah dimulai. Terlambat bergabung.');
        } else {
          onJoin(res.room);
        }
      } else {
        setError(res.message || 'Kode ruangan tidak ditemukan.');
      }
    } catch {
      setError('Tidak bisa terhubung ke server. Periksa koneksi internet.');
    }
    setLoading(false);
  };

  return (
    <div style={{ position: 'relative', minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', overflow: 'hidden' }}>
      <CloudBG /><Skyline />
      {onBack && (
        <div style={{ position: 'absolute', top: 24, left: 24, zIndex: 10 }}>
          <button onClick={onBack} style={{ background: 'white', border: '3px solid #4DABF7', borderRadius: '20px', padding: '10px 18px', display: 'flex', alignItems: 'center', gap: 8, fontSize: '15px', fontFamily: 'Fredoka', fontWeight: 700, color: '#4DABF7', cursor: 'pointer', boxShadow: '0 5px 0 #4DABF788' }}>
            <span style={{ fontSize: 20 }}>{'←'}</span><span>Kembali</span>
          </button>
        </div>
      )}
      <div style={{ position: 'relative', zIndex: 2, textAlign: 'center', maxWidth: 480, padding: '0 24px', width: '100%', display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
        <div style={{ marginBottom: 20, width: '100%' }}><ModibuLogo size={64} /></div>
        <div style={{ background: 'white', borderRadius: 28, padding: '36px 32px', boxShadow: '0 12px 40px rgba(0,0,0,0.12)', border: '4px solid #FFA94D' }}>
          <div style={{ width: 72, height: 72, borderRadius: '50%', background: 'linear-gradient(135deg,#FFA94D,#FF6B6B)', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 36, margin: '0 auto 16px', boxShadow: '0 6px 0 #E8852C', border: '4px solid white' }}>{'🎲'}</div>
          <h2 style={{ fontFamily: 'Fredoka', fontWeight: 700, fontSize: 26, margin: '0 0 6px', color: 'var(--ink)' }}>Masukkan Kode Ruangan</h2>
          <p style={{ color: 'var(--ink-soft)', fontSize: 14, margin: '0 0 24px' }}>Minta kode MDB-XXX dari Guru BK kamu</p>
          <input
            type="text" value={code}
            onChange={e => { setCode(e.target.value.toUpperCase()); setError(''); }}
            onKeyDown={e => e.key === 'Enter' && handleJoin()}
            placeholder="Contoh: MDB-X7K"
            maxLength={8}
            style={{ width: '100%', padding: '16px 20px', fontSize: 26, fontFamily: 'Fredoka', fontWeight: 700, textAlign: 'center', letterSpacing: '0.15em', border: '3px solid #E5EEF4', borderRadius: 16, outline: 'none', boxSizing: 'border-box', color: 'var(--ink)', background: '#F8FAFE' }}
            onFocus={e => e.target.style.borderColor = '#FFA94D'}
            onBlur={e => e.target.style.borderColor = '#E5EEF4'}
          />
          {error && (
            <div style={{ marginTop: 12, background: '#FFF5F5', border: '2px solid #FF6B6B', borderRadius: 12, padding: '10px 14px', color: '#C92A2A', fontFamily: 'Fredoka', fontSize: 13.5, fontWeight: 600 }}>{'❌'} {error}</div>
          )}
          <button onClick={handleJoin} disabled={loading || code.length < 3} className="btn btn-primary btn-lg" style={{ marginTop: 20, width: '100%', opacity: (loading || code.length < 3) ? 0.5 : 1 }}>
            {loading ? '⏳ Memeriksa...' : '🚀 Masuk Ruangan'}
          </button>
        </div>
      </div>
    </div>
  );
}

// ============ Student Lobby ============
function StudentLobbyScreen({ room: initialRoom, onBack, onGameStart }) {
  const [room, setRoom] = useStateS(initialRoom);
  const [names, setNames] = useStateS(['', '', '', '']);
  const [saving, setSaving] = useStateS(false);
  const [saved, setSaved] = useStateS(false);
  const allFilled = names.every(n => n.trim().length >= 2);

  useEffectS(() => {
    if (!window.EchoInstance) return;
    window.EchoInstance.on('room.' + room.code, 'room.updated', (data) => {
      setRoom(data);
      if (data.status === 'playing' || data.status === 'finished') onGameStart(data);
    });
    return () => { if (room && window.EchoInstance) window.EchoInstance.leave('room.' + room.code); };
  }, [room.code]);

  const handleSave = async () => {
    if (!allFilled) return;
    setSaving(true);
    try {
      const res = await window.RoomAPI.setPlayers(room.code, names.map(n => n.trim()));
      if (res.success) {
        setRoom(res.room);
        setSaved(true);
      }
    } catch (err) {
      alert('Gagal menyimpan nama. Periksa koneksi server.');
    }
    setSaving(false);
  };

  const filledSlots = (room.players || []).filter(p => p.name).length;

  return (
    <div style={{ position: 'relative', minHeight: '100vh', padding: '80px 0 60px', overflow: 'hidden' }}>
      <CloudBG /><Skyline />
      <div style={{ position: 'absolute', top: 24, left: 24, zIndex: 10 }}>
        <button onClick={onBack} style={{ background: 'white', border: '3px solid #4DABF7', borderRadius: '20px', padding: '10px 18px', display: 'flex', alignItems: 'center', gap: 8, fontSize: '15px', fontFamily: 'Fredoka', fontWeight: 700, color: '#4DABF7', cursor: 'pointer', boxShadow: '0 5px 0 #4DABF788' }}>
          <span style={{ fontSize: 20 }}>{'←'}</span><span>Kembali</span>
        </button>
      </div>
      <div style={{ position: 'relative', zIndex: 2, maxWidth: 680, margin: '0 auto', padding: '0 24px' }}>
        {/* Header Vertikal */}
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', marginBottom: 40 }}>
          {/* 1. Label Mode Siswa */}
          <div className="chip" style={{ background: 'white', fontSize: 13, padding: '6px 14px', marginBottom: 24, boxShadow: '0 4px 10px rgba(0,0,0,0.05)' }}>
            <span className="chip-dot" style={{ background: '#FFA94D' }} /> Mode Siswa
          </div>
          
          {/* 2. Area Kode Ruangan (Vertikal) */}
          <div style={{ marginBottom: 28, display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
            <span style={{ 
              fontFamily: 'Fredoka', 
              fontWeight: 700, 
              fontSize: 12, 
              color: 'var(--ink-soft)', 
              letterSpacing: '0.2em', 
              textTransform: 'uppercase',
              marginBottom: 8
            }}>Kode Ruangan</span>
            <div style={{ 
              background: 'white', 
              borderRadius: 20, 
              padding: '12px 36px', 
              boxShadow: '0 8px 24px rgba(0,0,0,0.06)', 
              border: '3px solid #E5EEF4' 
            }}>
              <span style={{ 
                fontFamily: 'Fredoka', 
                fontWeight: 800, 
                fontSize: 42, 
                color: '#1971C2', 
                letterSpacing: '0.1em' 
              }}>{room.code}</span>
            </div>
          </div>

          {/* 3. Judul & Deskripsi */}
          <h1 className="h-title" style={{ fontSize: 34, margin: '0 0 10px', color: 'var(--ink)' }}>Ruang Tunggu Siswa</h1>
          <p style={{ color: 'var(--ink-soft)', fontSize: 16, maxWidth: 450, lineHeight: 1.6 }}>Silakan isi nama 4 pion di bawah ini, lalu tunggu Guru BK memulai sesi permainan</p>
        </div>

        {!saved ? (
          <div style={{ background: 'white', borderRadius: 24, padding: '24px', boxShadow: '0 4px 16px rgba(0,0,0,0.08)', marginBottom: 20 }}>
            <div style={{ fontFamily: 'Fredoka', fontWeight: 700, fontSize: 13, color: 'var(--ink-soft)', marginBottom: 14 }}>NAMA 4 PEMAIN</div>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 12, marginBottom: 20 }}>
              {names.map((name, idx) => (
                <div key={idx} style={{ background: '#F8FAFE', border: '2.5px solid #E5EEF4', borderRadius: 14, padding: '12px 14px', display: 'flex', alignItems: 'center', gap: 10 }}>
                  <Avatar color={PLAYER_COLORS[idx]} label={PLAYER_ICONS[idx]} size={44} />
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 11, color: 'var(--ink-soft)', marginBottom: 3, fontFamily: 'Fredoka', fontWeight: 600 }}>Pion {PLAYER_NAMES_ID[idx]}</div>
                    <input type="text" value={name} onChange={e => { const n = [...names]; n[idx] = e.target.value; setNames(n); }} placeholder={'Nama pemain ' + (idx + 1)} style={{ width: '100%', border: 'none', background: 'transparent', fontSize: 14, fontFamily: 'Fredoka', fontWeight: 700, color: 'var(--ink)', outline: 'none' }} />
                  </div>
                  {name.trim().length >= 2 && <span style={{ background: '#EBFBEE', color: '#2F9E44', padding: '2px 8px', borderRadius: 999, fontSize: 10, fontWeight: 700, fontFamily: 'Fredoka' }}>{'✓'}</span>}
                </div>
              ))}
            </div>
            <button className="btn btn-primary" onClick={handleSave} disabled={!allFilled || saving} style={{ width: '100%', opacity: allFilled ? 1 : 0.5 }}>
              {saving ? '⏳ Menyimpan...' : 'Simpan Nama Pemain'}
            </button>
          </div>
        ) : (
          <div style={{ background: 'white', borderRadius: 24, padding: '28px', boxShadow: '0 4px 16px rgba(0,0,0,0.08)', marginBottom: 20, textAlign: 'center' }}>
            <div style={{ fontFamily: 'Fredoka', fontWeight: 700, fontSize: 20, color: '#2F9E44', marginBottom: 4 }}>Nama tersimpan!</div>
            <div style={{ fontSize: 13.5, color: 'var(--ink-soft)' }}>Menunggu Guru BK memulai permainan...</div>
          </div>
        )}


        <div style={{ textAlign: 'center', marginTop: 18, color: 'var(--ink-soft)', fontSize: 13 }}>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, background: 'white', padding: '10px 20px', borderRadius: 999, boxShadow: '0 2px 8px rgba(0,0,0,0.06)' }}>
            {'⏳'} Menunggu Guru BK memulai sesi...
          </div>
        </div>
      </div>
    </div>
  );
}

// ============ Teacher Lobby ============
function TeacherLobbyScreen({ onBack, onGameStart }) {
  const [room, setRoom] = useStateS(null);
  const [loading, setLoading] = useStateS(true);
  const [error, setError] = useStateS('');
  const [starting, setStarting] = useStateS(false);

  const createRoom = async () => {
    if (!window.RoomAPI) {
      setError('Sistem API belum siap. Silakan refresh halaman.');
      return;
    }
    setLoading(true);
    setError('');
    try {
      const res = await window.RoomAPI.createRoom();
      if (res.success) {
        setRoom(res.room);
      } else {
        setError(res.message || 'Gagal membuat ruangan.');
      }
    } catch (err) {
      setError('Koneksi server bermasalah: ' + (err.message || 'Unknown error'));
    }
    setLoading(false);
  };

  useEffectS(() => {
    createRoom();
  }, []);

  useEffectS(() => {
    if (!room || !window.EchoInstance) return;
    window.EchoInstance.on('room.' + room.code, 'room.updated', (data) => {
      setRoom(data);
      if (data.status === 'playing' || data.status === 'finished') onGameStart(data);
    });
    return () => { if (room && window.EchoInstance) window.EchoInstance.leave('room.' + room.code); };
  }, [room ? room.code : null]);

  const handleStart = async () => {
    if (!room || !room.is_full) return;
    setStarting(true);
    await window.RoomAPI.startGame(room.code);
    setStarting(false);
  };

  if (loading) {
    return (
      <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column', gap: 16 }}>
        <div style={{ fontSize: 48 }}>{'⏳'}</div>
        <div style={{ fontFamily: 'Fredoka', fontSize: 18, color: 'var(--ink-soft)' }}>Membuat ruangan...</div>
      </div>
    );
  }

  if (error) {
    return (
      <div style={{ minHeight: '100vh', display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column', gap: 20, padding: 20, textAlign: 'center' }}>
        <div style={{ fontSize: 48 }}>{'❌'}</div>
        <div style={{ fontFamily: 'Fredoka', fontSize: 18, color: '#C92A2A', maxWidth: 400 }}>{error}</div>
        <div style={{ display: 'flex', gap: 12 }}>
          <button className="btn btn-secondary" onClick={onBack}>Kembali</button>
          <button className="btn btn-primary" onClick={createRoom}>Coba Lagi</button>
        </div>
      </div>
    );
  }

  if (!room) return null;

  const filledSlots = (room.players || []).filter(p => p.name).length;

  return (
    <div style={{ position: 'relative', minHeight: '100vh', padding: '80px 0 60px', overflow: 'hidden' }}>
      <CloudBG density="sparse" /><Skyline />
      <div style={{ position: 'absolute', top: 24, left: 24, zIndex: 10 }}>
        <button onClick={onBack} style={{ background: 'white', border: '3px solid #4DABF7', borderRadius: '20px', padding: '10px 18px', display: 'flex', alignItems: 'center', gap: 8, fontSize: '15px', fontFamily: 'Fredoka', fontWeight: 700, color: '#4DABF7', cursor: 'pointer', boxShadow: '0 5px 0 #4DABF788' }}>
          <span style={{ fontSize: 20 }}>{'←'}</span><span>Kembali</span>
        </button>
      </div>
      <div style={{ position: 'relative', zIndex: 2, maxWidth: 680, margin: '0 auto', padding: '0 24px' }}>
        <div style={{ textAlign: 'center', marginBottom: 28 }}>
          <div className="chip" style={{ background: 'white', fontSize: 12, marginBottom: 8 }}><span className="chip-dot" style={{ background: '#4DABF7' }} /> Mode Guru BK</div>
          <h1 className="h-title" style={{ fontSize: 30, margin: '4px 0 6px' }}>Ruang Tunggu Guru BK</h1>
          <p style={{ color: 'var(--ink-soft)', fontSize: 14 }}>Bagikan kode ini ke siswa, lalu tunggu semua pion terisi</p>
        </div>

        <div style={{ background: 'linear-gradient(135deg,#4DABF7,#1971C2)', borderRadius: 24, padding: '28px 24px', textAlign: 'center', marginBottom: 20, boxShadow: '0 8px 24px rgba(77,171,247,0.4)', border: '4px solid white' }}>
          <div style={{ fontFamily: 'Fredoka', fontWeight: 700, fontSize: 11, color: 'rgba(255,255,255,0.8)', letterSpacing: '0.12em', marginBottom: 8 }}>KODE RUANGAN — BAGIKAN KE SISWA</div>
          <div style={{ fontFamily: 'Fredoka', fontWeight: 800, fontSize: 52, color: 'white', letterSpacing: '0.18em', textShadow: '0 4px 0 rgba(0,0,0,0.2)', margin: '4px 0' }}>{room.code}</div>
          <div style={{ fontFamily: 'Fredoka', fontWeight: 600, fontSize: 12, color: 'rgba(255,255,255,0.75)' }}>Siswa ketik kode ini di halaman "Mulai sebagai Siswa"</div>
        </div>

        <div style={{ background: 'white', borderRadius: 22, padding: '20px', boxShadow: '0 4px 16px rgba(0,0,0,0.08)', marginBottom: 20 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 14 }}>
            <div style={{ fontFamily: 'Fredoka', fontWeight: 700, fontSize: 13, color: 'var(--ink-soft)' }}>STATUS PION (LIVE)</div>
            <div style={{ background: filledSlots === 4 ? '#EBFBEE' : '#FFF8EB', color: filledSlots === 4 ? '#2F9E44' : '#E8590C', padding: '4px 12px', borderRadius: 999, fontFamily: 'Fredoka', fontWeight: 700, fontSize: 11 }}>
              {filledSlots === 4 ? '🎉 Semua Siap!' : filledSlots + '/4 Siap'}
            </div>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2,1fr)', gap: 10 }}>
            {(room.players || []).map((p, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '12px 14px', background: p.name ? '#F0FFF4' : '#F8FAFE', borderRadius: 14, border: '2.5px solid ' + (p.name ? '#51CF66' : '#DEE2E6') }}>
                <Avatar color={PLAYER_COLORS[i]} label={PLAYER_ICONS[i]} size={44} />
                <div style={{ flex: 1 }}>
                  <div style={{ fontFamily: 'Fredoka', fontWeight: 700, fontSize: 15, color: p.name ? 'var(--ink)' : '#ADB5BD' }}>{p.name || 'Belum bergabung'}</div>
                  <div style={{ fontSize: 11, color: 'var(--ink-soft)' }}>Pion {PLAYER_NAMES_ID[i]}</div>
                </div>
                <span style={{ fontSize: 18 }}>{p.name ? '✅' : '⏳'}</span>
              </div>
            ))}
          </div>
        </div>

        <div style={{ textAlign: 'center' }}>
          <button className="btn btn-primary btn-lg" onClick={handleStart} disabled={!room.is_full || starting} style={{ opacity: room.is_full ? 1 : 0.4, fontSize: 18, padding: '16px 40px' }}>
            {starting ? '⏳ Memulai...' : room.is_full ? '🎮 Mulai Permainan!' : '⏳ Menunggu ' + (4 - filledSlots) + ' pemain lagi...'}
          </button>
          {!room.is_full && <div style={{ marginTop: 10, fontSize: 12, color: 'var(--ink-soft)', fontFamily: 'Fredoka', fontWeight: 600 }}>Tombol aktif saat semua 4 pion terisi</div>}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  LandingScreen, RoleCard, LobbyScreen,
  RoomCodeEntryScreen, StudentLobbyScreen, TeacherLobbyScreen,
  TeacherPanel, GradingQueuePanel, BoardMonitorPanel, ManualPointsPanelReal, MaterialTriggerPanel,
  ResultsScreen, PodiumStep, ConfettiBackdrop,
});
