<div class="container-fluid">
    <div class="row justify-content-center">
        <div class="col-md-10">
            <div class="card border-0 shadow-sm" style="border-radius: 15px;">
                <div class="card-header bg-white border-0 pt-4 px-4">
                    <h5 class="mb-0">Tambah Pertemuan Arisan</h5>
                    <p class="text-muted mb-0 mt-2">
                        <strong><?php echo $arisan->nama_arisan; ?></strong> - Pertemuan Ke-<?php echo $pertemuan_ke; ?>
                    </p>
                </div>
                <div class="card-body px-4 pb-4">
                    <?php echo validation_errors('<div class="alert alert-danger">', '</div>'); ?>
                    
                    <form action="" method="post" id="formPertemuan">
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Tanggal Pertemuan <span class="text-danger">*</span></label>
                                <input type="date" name="tanggal_pertemuan" class="form-control" required
                                       value="<?php echo set_value('tanggal_pertemuan', date('Y-m-d')); ?>">
                            </div>
                            
                            <div class="col-md-6 mb-3">
                                <label class="form-label">Status Pertemuan <span class="text-danger">*</span></label>
                                <select name="status_pertemuan" class="form-select" required>
                                    <option value="pending" <?php echo set_select('status_pertemuan', 'pending'); ?>>Pending (Belum Terlaksana)</option>
                                    <option value="terlaksana" <?php echo set_select('status_pertemuan', 'terlaksana', TRUE); ?>>Terlaksana</option>
                                    <option value="batal" <?php echo set_select('status_pertemuan', 'batal'); ?>>Batal</option>
                                </select>
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Tuan Rumah <span class="text-danger">*</span></label>
                            <select name="warga_id_tuan_rumah" class="form-select" required>
                                <option value="">-- Pilih Tuan Rumah --</option>
                                <?php foreach($peserta as $p): ?>
                                    <option value="<?php echo $p->warga_id; ?>">
                                        [<?php echo $p->nomor_urut; ?>] <?php echo $p->nama_lengkap; ?>
                                    </option>
                                <?php endforeach; ?>
                            </select>
                            <small class="text-muted">Rumah siapa pertemuan arisan dilaksanakan</small>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Alamat Tempat Pertemuan (Opsional)</label>
                            <input type="text" name="tempat_pertemuan" class="form-control" 
                                   placeholder="Contoh: Jl. Mawar No. 15 RT 05"
                                   value="<?php echo set_value('tempat_pertemuan'); ?>">
                        </div>

                        <hr class="my-4">

                        <h6 class="mb-3"><i class="bi bi-trophy-fill text-warning me-2"></i>Data Pemenang Undian</h6>

                        <!-- ROULETTE WHEEL SECTION -->
                        <div class="roulette-section mb-4">
                            <div class="text-center mb-3">
                                <button type="button" class="btn btn-roulette btn-lg px-5" id="btnSpin" 
                                        <?php echo empty($peserta_belum_dapat) ? 'disabled' : ''; ?>>
                                    <i class="bi bi-arrow-repeat me-2"></i>🎰 SPIN ROULETTE
                                </button>
                                <div class="mt-2">
                                    <small class="text-muted" id="infoPeserta">
                                        <?php if(empty($peserta_belum_dapat)): ?>
                                            <span class="text-danger">Semua peserta sudah pernah menang!</span>
                                        <?php else: ?>
                                            <span class="text-success"><?php echo count($peserta_belum_dapat); ?> peserta tersedia di roda</span>
                                        <?php endif; ?>
                                    </small>
                                </div>
                            </div>

                            <!-- Roulette Wheel Container -->
                            <div class="roulette-container" id="rouletteContainer" style="display: none;">
                                <div class="roulette-wrapper">
                                    <canvas id="rouletteCanvas" width="500" height="500"></canvas>
                                    <div class="roulette-pointer">▼</div>
                                    <div class="roulette-center">
                                        <div class="center-text">ARISAN</div>
                                    </div>
                                </div>
                                
                                <!-- Progress & Timer -->
                                <div class="roulette-progress mt-3">
                                    <div class="progress" style="height: 10px; background: rgba(0,0,0,0.3);">
                                        <div class="progress-bar progress-bar-striped progress-bar-animated bg-warning" 
                                             id="spinProgress" role="progressbar" style="width: 0%"></div>
                                    </div>
                                    <div class="text-center mt-2">
                                        <span class="badge bg-dark" id="spinTimer">30 detik</span>
                                    </div>
                                </div>

                                <!-- Winner Display -->
                                <div class="winner-display mt-3" id="winnerDisplay" style="display: none;">
                                    <div class="winner-card">
                                        <div class="winner-icon">🎉</div>
                                        <div class="winner-title">PEMENANG UNDIAN</div>
                                        <div class="winner-name" id="winnerName">-</div>
                                        <div class="winner-number" id="winnerNumber">Nomor: -</div>
                                        <div class="winner-actions mt-3">
                                            <button type="button" class="btn btn-success btn-sm me-2" onclick="confirmWinner()">
                                                <i class="bi bi-check-lg"></i> Pilih Pemenang
                                            </button>
                                            <button type="button" class="btn btn-outline-warning btn-sm" onclick="spinAgain()">
                                                <i class="bi bi-arrow-clockwise"></i> Spin Lagi
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-8 mb-3">
                                <label class="form-label">Pemenang (Opsional)</label>
                                <select name="pemenang_warga_id" class="form-select" id="selectPemenang">
                                    <option value="">-- Pilih Pemenang (Kosongkan jika belum diundi) --</option>
                                    <?php foreach($peserta_belum_dapat as $p): ?>
                                        <option value="<?php echo $p->warga_id; ?>" 
                                                data-nomor="<?php echo $p->nomor_urut; ?>"
                                                data-nama="<?php echo $p->nama_lengkap; ?>">
                                            [<?php echo $p->nomor_urut; ?>] <?php echo $p->nama_lengkap; ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                                <small class="text-muted">Hanya menampilkan peserta yang belum pernah dapat arisan</small>
                            </div>
                            
                            <div class="col-md-4 mb-3">
                                <label class="form-label">Nomor Undian</label>
                                <input type="number" name="nomor_undian" class="form-control" 
                                       id="inputNomorUndian" min="1" max="<?php echo count($peserta); ?>"
                                       placeholder="Auto dari pemenang"
                                       value="<?php echo set_value('nomor_undian'); ?>">
                            </div>
                        </div>

                        <div class="mb-3">
                            <label class="form-label">Keterangan (Opsional)</label>
                            <textarea name="keterangan" class="form-control" rows="3" 
                                      placeholder="Catatan tambahan tentang pertemuan ini..."><?php echo set_value('keterangan'); ?></textarea>
                        </div>

                        <!-- Info Dana -->
                        <div class="alert alert-success">
                            <div class="row text-center">
                                <div class="col-md-4">
                                    <small class="text-muted d-block">Total Peserta</small>
                                    <h5 class="mb-0"><?php echo count($peserta); ?> Orang</h5>
                                </div>
                                <div class="col-md-4">
                                    <small class="text-muted d-block">Iuran per Orang</small>
                                    <h5 class="mb-0">Rp <?php echo number_format($arisan->nominal_iuran, 0, ',', '.'); ?></h5>
                                </div>
                                <div class="col-md-4">
                                    <small class="text-muted d-block">Total Dana Arisan</small>
                                    <h5 class="mb-0 text-success">Rp <?php echo number_format($arisan->nominal_iuran * count($peserta), 0, ',', '.'); ?></h5>
                                </div>
                            </div>
                        </div>

                        <hr class="my-4">

                        <div class="d-flex justify-content-between align-items-center">
                            <a href="<?php echo base_url('arisan/pertemuan/' . $arisan->id); ?>" class="btn btn-secondary">
                                <i class="bi bi-arrow-left me-2"></i>Kembali
                            </a>
                            <button type="submit" class="btn btn-primary">
                                <i class="bi bi-save me-2"></i>Simpan Pertemuan
                            </button>
                        </div>
                    </form>
                </div>
            </div>

            <!-- Info Catatan -->
            <div class="alert alert-info mt-3">
                <h6 class="mb-2"><i class="bi bi-info-circle me-2"></i>Catatan Penting:</h6>
                <ul class="mb-0 small">
                    <li>Pertemuan ke-<?php echo $pertemuan_ke; ?> dari total <?php echo count($peserta); ?> pertemuan yang akan dilaksanakan</li>
                    <li>Jika belum diundi, kosongkan saja field pemenang (bisa diisi nanti)</li>
                    <li>Sistem akan otomatis generate tagihan iuran untuk semua peserta</li>
                    <li>Pemenang yang sudah pernah dapat tidak akan muncul di pilihan</li>
                </ul>
            </div>
        </div>
    </div>
</div>

<!-- ROULETTE STYLES -->
<style>
.roulette-section {
    background: linear-gradient(135deg, #0d3d38 0%, #0b5a52 100%);
    border-radius: 20px;
    padding: 30px;
    border: 2px solid #14b8a6;
    box-shadow: 0 10px 40px rgba(13,148,136,0.25);
}

.btn-roulette {
    background: linear-gradient(135deg, #14b8a6 0%, #2dd4bf 50%, #14b8a6 100%);
    color: #fff;
    font-weight: 800;
    border: none;
    border-radius: 6px;
    box-shadow: 0 4px 15px rgba(20,184,166,0.45);
    transition: all 0.3s ease;
    text-transform: uppercase;
    letter-spacing: 1px;
}

.btn-roulette:hover:not(:disabled) {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(20,184,166,0.6);
    background: linear-gradient(135deg, #2dd4bf 0%, #14b8a6 50%, #2dd4bf 100%);
    color: #fff;
}

.btn-roulette:disabled {
    background: #6c757d;
    color: #fff;
    cursor: not-allowed;
}

.roulette-container {
    margin-top: 30px;
}

.roulette-wrapper {
    position: relative;
    width: 500px;
    height: 500px;
    margin: 0 auto;
}

#rouletteCanvas {
    width: 100%;
    height: 100%;
    border-radius: 50%;
    box-shadow: 0 0 50px rgba(20,184,166,0.3);
}

.roulette-pointer {
    position: absolute;
    top: -20px;
    left: 50%;
    transform: translateX(-50%);
    font-size: 40px;
    color: #ef4444;
    text-shadow: 0 2px 10px rgba(0,0,0,0.5);
    z-index: 10;
    filter: drop-shadow(0 0 10px rgba(239,68,68,0.8));
}

.roulette-center {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 80px;
    height: 80px;
    background: radial-gradient(circle, #2dd4bf 0%, #0b7a6e 100%);
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 0 30px rgba(20,184,166,0.85);
    border: 4px solid #fff;
    z-index: 5;
}

.center-text {
    font-size: 10px;
    font-weight: 900;
    color: #ffffff;
    text-align: center;
    line-height: 1.2;
}

.winner-display {
    animation: fadeInUp 0.5s ease;
}

.winner-card {
    background: linear-gradient(135deg, rgba(20,184,166,0.15) 0%, rgba(11,90,82,0.2) 100%);
    border: 2px solid #14b8a6;
    border-radius: 15px;
    padding: 25px;
    text-align: center;
    backdrop-filter: blur(10px);
}

.winner-icon {
    font-size: 50px;
    margin-bottom: 10px;
    animation: bounce 1s infinite;
}

.winner-title {
    color: #2dd4bf;
    font-size: 12px;
    letter-spacing: 3px;
    font-weight: 700;
    margin-bottom: 10px;
}

.winner-name {
    color: #fff;
    font-size: 28px;
    font-weight: 800;
    margin-bottom: 5px;
    text-shadow: 0 0 20px rgba(20,184,166,0.6);
}

.winner-number {
    color: rgba(255,255,255,0.75);
    font-size: 16px;
}

@keyframes fadeInUp {
    from { opacity: 0; transform: translateY(20px); }
    to   { opacity: 1; transform: translateY(0); }
}

@keyframes bounce {
    0%, 100% { transform: translateY(0); }
    50%       { transform: translateY(-10px); }
}

/* Confetti */
.confetti {
    position: fixed;
    width: 10px;
    height: 10px;
    top: -10px;
    z-index: 9999;
    animation: confetti-fall 3s linear forwards;
}

@keyframes confetti-fall {
    0%   { transform: translateY(0) rotate(0deg);      opacity: 1; }
    100% { transform: translateY(100vh) rotate(720deg); opacity: 0; }
}

@media (max-width: 768px) {
    .roulette-wrapper {
        width: 350px;
        height: 350px;
    }
    #rouletteCanvas {
        width: 350px;
        height: 350px;
    }
}
</style>
<!-- ROULETTE JAVASCRIPT -->
<script>
(function() {
  'use strict';

  // ── State ─────────────────────────────────────────────
  var currentRotation = 0;
  var isSpinning      = false;
  var selectedWinner  = null;
  var spinDuration    = 30000;
  var animFrame       = null;
  var LOGICAL_SIZE    = 500; // ukuran logis tetap

 var COLORS = [
    '#14b8a6','#0d9488','#2dd4bf','#0b7a6e','#5eead4',
    '#10b981','#059669','#34d399','#6ee7b7','#0b5a52',
    '#3b82f6','#6366f1','#8b5cf6','#f59e0b','#ef4444'
  ];

  // ── Data PHP ───────────────────────────────────────────
  var pesertaData = [
    <?php foreach($peserta_belum_dapat as $p): ?>
    { id: <?php echo $p->warga_id; ?>, nama: "<?php echo addslashes($p->nama_lengkap); ?>", nomor: <?php echo $p->nomor_urut; ?> },
    <?php endforeach; ?>
  ];

  var canvas, ctx;

  // ── Init canvas — selalu pakai ukuran logis, DPR saja yang scale ──
  function initCanvas() {
    canvas = document.getElementById('rouletteCanvas');
    if (!canvas) return false;
    ctx = canvas.getContext('2d');

    var dpr = window.devicePixelRatio || 1;

    // Set attribute size (piksel nyata)
    canvas.width  = LOGICAL_SIZE * dpr;
    canvas.height = LOGICAL_SIZE * dpr;

    // Set display size via style
    canvas.style.width  = LOGICAL_SIZE + 'px';
    canvas.style.height = LOGICAL_SIZE + 'px';

    // Reset transform & scale sekali saja
    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.scale(dpr, dpr);
    return true;
  }

  // ── Draw ───────────────────────────────────────────────
  function drawRoulette(rotation) {
    if (!ctx || !pesertaData.length) return;
    rotation = rotation || 0;

    var size   = LOGICAL_SIZE;
    var cx     = size / 2;
    var cy     = size / 2;
    var radius = cx - 20;
    var n      = pesertaData.length;
    var slice  = (2 * Math.PI) / n;

    ctx.clearRect(0, 0, size, size);

    pesertaData.forEach(function(p, i) {
      var s = i * slice + rotation;
      var e = (i + 1) * slice + rotation;

      ctx.beginPath();
      ctx.moveTo(cx, cy);
      ctx.arc(cx, cy, radius, s, e);
      ctx.closePath();
      ctx.fillStyle   = COLORS[i % COLORS.length];
      ctx.fill();
      ctx.strokeStyle = '#fff';
      ctx.lineWidth   = 2;
      ctx.stroke();

      ctx.save();
      ctx.translate(cx, cy);
      ctx.rotate(s + slice / 2);
      ctx.textAlign   = 'right';
      ctx.fillStyle   = '#fff';
      ctx.font        = 'bold 14px Arial';
      ctx.shadowColor = 'rgba(0,0,0,0.5)';
      ctx.shadowBlur  = 3;
      var lbl = p.nama.length > 12 ? p.nama.substring(0, 12) + '..' : p.nama;
      ctx.fillText('[' + p.nomor + '] ' + lbl, radius - 20, 5);
      ctx.restore();
    });

    // Ring emas
    ctx.beginPath();
    ctx.arc(cx, cy, radius, 0, 2 * Math.PI);
    ctx.strokeStyle = '#ffd700';
    ctx.lineWidth   = 8;
    ctx.stroke();

    // Lingkaran tengah
    ctx.beginPath();
    ctx.arc(cx, cy, 40, 0, 2 * Math.PI);
    ctx.fillStyle = '#ffd700';
    ctx.fill();
  }

  // ── Highlight pemenang ─────────────────────────────────
  function highlightWinner(index) {
    drawRoulette(currentRotation);

    var size   = LOGICAL_SIZE;
    var cx     = size / 2;
    var cy     = size / 2;
    var radius = cx - 20;
    var slice  = (2 * Math.PI) / pesertaData.length;
    var s      = index * slice + currentRotation;
    var e      = (index + 1) * slice + currentRotation;

    ctx.save();
    ctx.beginPath();
    ctx.moveTo(cx, cy);
    ctx.arc(cx, cy, radius, s, e);
    ctx.closePath();
    ctx.fillStyle   = '#ffd700';
    ctx.fill();
    ctx.strokeStyle = '#fff';
    ctx.lineWidth   = 4;
    ctx.stroke();

    ctx.translate(cx, cy);
    ctx.rotate(s + slice / 2);
    ctx.textAlign   = 'right';
    ctx.fillStyle   = '#1a1a2e';
    ctx.font        = 'bold 16px Arial';
    ctx.shadowColor = 'transparent';
    var lbl = selectedWinner.nama.length > 12 ? selectedWinner.nama.substring(0, 12) + '..' : selectedWinner.nama;
    ctx.fillText('[' + selectedWinner.nomor + '] ' + lbl, radius - 20, 5);
    ctx.restore();
  }

  // ── Confetti ───────────────────────────────────────────
  function createConfetti() {
    var cols = ['#ffd700','#ff6b6b','#4ecdc4','#45b7d1','#ffa07a'];
    for (var i = 0; i < 60; i++) {
      (function(idx) {
        setTimeout(function() {
          var el  = document.createElement('div');
          var sz  = 8 + Math.random() * 8;
          var dur = 2 + Math.random() * 2;
          el.className = 'confetti';
          el.style.cssText =
            'left:' + (Math.random() * 100) + '%;' +
            'background-color:' + cols[Math.floor(Math.random() * cols.length)] + ';' +
            'width:' + sz + 'px;height:' + sz + 'px;' +
            'animation-duration:' + dur + 's;' +
            'border-radius:' + (Math.random() > 0.5 ? '50%' : '2px');
          document.body.appendChild(el);
          setTimeout(function() { if (el.parentNode) el.parentNode.removeChild(el); }, dur * 1000);
        }, idx * 25);
      })(i);
    }
  }

  // ── SPIN ───────────────────────────────────────────────
  function spinRoulette() {
    if (isSpinning || !pesertaData.length) return;

    isSpinning     = true;
    selectedWinner = null;
    if (animFrame) cancelAnimationFrame(animFrame);

    // Reset winner display
    var wd = document.getElementById('winnerDisplay');
    if (wd) wd.style.display = 'none';

    // Update tombol
    var btn = document.getElementById('btnSpin');
    btn.disabled  = true;
    btn.innerHTML = '<i class="bi bi-arrow-repeat me-2"></i>SPINNING...';

    // Tampilkan container — PENTING: harus visible sebelum initCanvas
    var container = document.getElementById('rouletteContainer');
    container.style.display = 'block';

    // Init canvas setelah container visible
    if (!ctx) {
      if (!initCanvas()) return;
    }
    drawRoulette(currentRotation);

    // Scroll ke roulette
    var top = container.getBoundingClientRect().top + window.pageYOffset - 100;
    window.scrollTo({ top: top, behavior: 'smooth' });

    // Reset progress
    var bar   = document.getElementById('spinProgress');
    var timer = document.getElementById('spinTimer');
    bar.style.width  = '0%';
    bar.className    = 'progress-bar progress-bar-striped progress-bar-animated bg-warning';
    timer.textContent = '30 detik';
    timer.className   = 'badge bg-dark';

    // Tentukan pemenang
    var winnerIndex = Math.floor(Math.random() * pesertaData.length);
    var slice       = (2 * Math.PI) / pesertaData.length;
    var target      = (3 * Math.PI / 2) - (winnerIndex * slice) - (slice / 2)
                      + (5 + Math.random() * 3) * 2 * Math.PI;
    var startTime   = null;

    function animate(ts) {
      if (!startTime) startTime = ts;
      var elapsed  = ts - startTime;
      var progress = Math.min(elapsed / spinDuration, 1);
      var eased    = 1 - Math.pow(1 - progress, 3);

      currentRotation = eased * target;
      drawRoulette(currentRotation);

      bar.style.width   = Math.round(progress * 100) + '%';
      timer.textContent = Math.max(0, Math.ceil((spinDuration - elapsed) / 1000)) + ' detik';

      if (progress < 1) {
        animFrame = requestAnimationFrame(animate);
      } else {
        finishSpin(winnerIndex);
      }
    }
    animFrame = requestAnimationFrame(animate);
  }

  function finishSpin(winnerIndex) {
    isSpinning     = false;
    selectedWinner = pesertaData[winnerIndex];

    var bar   = document.getElementById('spinProgress');
    var timer = document.getElementById('spinTimer');
    bar.className    = 'progress-bar bg-success';
    bar.style.width  = '100%';
    timer.textContent = '✓ SELESAI';
    timer.className   = 'badge bg-success';

    var btn = document.getElementById('btnSpin');
    btn.disabled  = false;
    btn.innerHTML = '<i class="bi bi-arrow-repeat me-2"></i>SPIN LAGI';

    document.getElementById('winnerName').textContent   = selectedWinner.nama;
    document.getElementById('winnerNumber').textContent = 'Nomor Urut: ' + selectedWinner.nomor;
    var wd = document.getElementById('winnerDisplay');
    wd.style.display = 'block';

    highlightWinner(winnerIndex);
    createConfetti();

    var top = wd.getBoundingClientRect().top + window.pageYOffset - 100;
    window.scrollTo({ top: top, behavior: 'smooth' });
  }

  // ── Global helpers (onclick di HTML) ──────────────────
  window.confirmWinner = function() {
    if (!selectedWinner) return;

    var sel = document.getElementById('selectPemenang');
    sel.value = selectedWinner.id;
    if (window.jQuery && window.jQuery.fn.select2) window.jQuery('#selectPemenang').trigger('change');
    document.getElementById('inputNomorUndian').value = selectedWinner.nomor;

    sel.classList.add('is-valid');
    setTimeout(function() { sel.classList.remove('is-valid'); }, 3000);

    var container = document.getElementById('rouletteContainer');
    container.style.opacity    = '0';
    container.style.transition = 'opacity .4s';
    setTimeout(function() {
      container.style.display    = 'none';
      container.style.opacity    = '';
      container.style.transition = '';
    }, 400);

    var top = sel.getBoundingClientRect().top + window.pageYOffset - 150;
    window.scrollTo({ top: top, behavior: 'smooth' });
  };

  window.spinAgain = function() {
    document.getElementById('winnerDisplay').style.display = 'none';
    var bar   = document.getElementById('spinProgress');
    var timer = document.getElementById('spinTimer');
    bar.style.width  = '0%';
    bar.className    = 'progress-bar progress-bar-striped progress-bar-animated bg-warning';
    timer.textContent = '30 detik';
    timer.className   = 'badge bg-dark';
    setTimeout(spinRoulette, 150);
  };

  // ── Init saat DOM ready ────────────────────────────────
  function onReady() {
    if (!pesertaData.length) {
      var btn = document.getElementById('btnSpin');
      if (btn) { btn.disabled = true; btn.innerHTML = 'Semua peserta sudah menang'; }
      return;
    }

    // ★ Gambar preview wheel di luar container (tidak terlihat user)
    //   Caranya: init canvas dulu sebelum container disembunyikan
    if (initCanvas()) drawRoulette(0);

    // Bind tombol spin pakai addEventListener native
    var btn = document.getElementById('btnSpin');
    if (btn) {
      btn.addEventListener('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        spinRoulette(); 
      });
    }

    // Auto-fill nomor undian
    var selP = document.getElementById('selectPemenang');
    if (selP) {
      selP.addEventListener('change', function() {
        var opt = this.options[this.selectedIndex];
        document.getElementById('inputNomorUndian').value = (opt && opt.dataset.nomor) || '';
      });
    }

    // Select2 (setelah bind native agar tidak konflik)
    if (window.jQuery && window.jQuery.fn.select2) {
      window.jQuery('#selectPemenang, select[name="warga_id_tuan_rumah"]').select2({
        placeholder: '-- Pilih --',
        allowClear : true
      });
      window.jQuery('#selectPemenang').on('select2:select select2:clear', function() {
        var opt = this.options[this.selectedIndex];
        document.getElementById('inputNomorUndian').value = (opt && opt.getAttribute('data-nomor')) || '';
      });
    }

    // Resize handler
    var rt;
    window.addEventListener('resize', function() {
      clearTimeout(rt);
      rt = setTimeout(function() {
        // Hanya re-init jika canvas sedang visible
        var container = document.getElementById('rouletteContainer');
        if (container && container.style.display !== 'none') {
          initCanvas();
          drawRoulette(currentRotation);
        }
      }, 200);
    });
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', onReady);
  } else {
    onReady();
  }

})();
</script>