<?php defined('BASEPATH') OR exit('No direct script access allowed'); ?>

<style>
/* ─── DESIGN TOKENS ──────────────────────────────────────── */
:root {
  --teal-900: #0d3d38;
  --teal-800: #0b5a52;
  --teal-700: #0b7a6e;
  --teal-600: #0d9488;
  --teal-500: #14b8a6;
  --teal-400: #2dd4bf;
  --teal-100: #ccfbf1;
  --teal-50:  #f0fdfa;
  --green-500: #10b981;
  --green-600: #059669;
  --amber-400: #fbbf24;
  --amber-500: #f59e0b;
  --amber-600: #d97706;
  --amber-50:  #fffbeb;
  --amber-100: #fef3c7;
  --red-400:  #f87171;
  --red-500:  #ef4444;
  --red-600:  #dc2626;
  --blue-500: #3b82f6;
  --blue-600: #2563eb;
  --slate-50: #f8fafc;
  --slate-100:#f1f5f9;
  --slate-200:#e2e8f0;
  --slate-400:#94a3b8;
  --slate-500:#64748b;
  --slate-700:#334155;
  --slate-900:#0f172a;
  
  --radius:    14px;
  --radius-sm: 9px;
  --radius-xs: 6px;
  --shadow:    0 4px 24px rgba(13,148,136,0.10), 0 1px 4px rgba(0,0,0,0.05);
}

/* ─── WRAPPER ────────────────────────────────────────────── */
.pt-wrapper {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 24px 40px;
}

/* ─── PAGE HEADER ────────────────────────────────────────── */
.pt-page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 24px;
  flex-wrap: wrap;
  gap: 12px;
}
.pt-header-left h4 {
  font-size: 1.3rem;
  font-weight: 800;
  color: var(--teal-800);
  margin: 0 0 6px;
  display: flex;
  align-items: center;
  gap: 12px;
}
.pt-header-left h4 .hi {
  width: 44px; height: 44px;
  border-radius: 12px;
  background: linear-gradient(135deg, var(--teal-800), var(--teal-500));
  display: flex; align-items: center; justify-content: center;
  color: #fff; font-size: 1.1rem;
  box-shadow: 0 4px 14px rgba(13,148,136,0.32);
}
.pt-breadcrumb {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 0.8rem;
  color: var(--slate-400);
  padding-left: 56px;
}
.pt-breadcrumb a { color: var(--teal-600); text-decoration: none; font-weight: 600; }
.pt-breadcrumb a:hover { text-decoration: underline; }
.pt-breadcrumb .sep { color: var(--slate-300); }

/* ─── MAIN CARD ───────────────────────────────────────────── */
.pt-card {
  background: #fff;
  border-radius: var(--radius);
  box-shadow: var(--shadow);
  overflow: hidden;
  border: 1.5px solid var(--slate-100);
}
.pt-card-header {
  padding: 24px 28px;
  border-bottom: 1.5px solid var(--slate-100);
  background: linear-gradient(135deg, var(--slate-50), #fff);
}
.pt-card-header h5 {
  font-size: 1.1rem;
  font-weight: 700;
  color: var(--teal-800);
  margin: 0;
  display: flex;
  align-items: center;
  gap: 10px;
}
.pt-card-header .subtitle {
  font-size: 0.85rem;
  color: var(--slate-500);
  margin-top: 4px;
}

.pt-card-body {
  padding: 28px;
}

/* ─── FORM STYLES ─────────────────────────────────────────── */
.form-label {
  font-size: 0.85rem;
  font-weight: 600;
  color: var(--slate-700);
  margin-bottom: 6px;
}
.form-control, .form-select {
  border: 1.5px solid var(--slate-200);
  border-radius: var(--radius-sm);
  padding: 10px 14px;
  font-size: 0.9rem;
  transition: all .2s;
}
.form-control:focus, .form-select:focus {
  border-color: var(--teal-500);
  box-shadow: 0 0 0 3px rgba(13,148,136,0.12);
}
.form-text {
  font-size: 0.8rem;
  color: var(--slate-400);
}

/* ─── SECTION HEADER ──────────────────────────────────────── */
.section-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin: 32px 0 20px;
  padding-bottom: 12px;
  border-bottom: 2px solid var(--slate-100);
}
.section-header h6 {
  font-size: 1rem;
  font-weight: 700;
  color: var(--teal-800);
  margin: 0;
}
.section-header i {
  color: var(--amber-500);
  font-size: 1.2rem;
}

/* ─── ROULETTE SECTION ───────────────────────────────────── */
.roulette-section {
  background: linear-gradient(135deg, var(--teal-900) 0%, var(--teal-800) 100%);
  border-radius: 20px;
  padding: 30px;
  border: 2px solid var(--teal-500);
  box-shadow: 0 10px 40px rgba(13,148,136,0.25);
  margin-bottom: 24px;
  position: relative;
}

.btn-roulette {
  background: linear-gradient(135deg, var(--teal-500) 0%, var(--teal-400) 50%, var(--teal-500) 100%);
  color: #fff;
  font-weight: 800;
  border: none;
  border-radius: var(--radius-xs);
  box-shadow: 0 4px 15px rgba(20,184,166,0.45);
  transition: all 0.3s ease;
  text-transform: uppercase;
  letter-spacing: 1px;
  padding: 14px 36px;
  font-size: 1rem;
  cursor: pointer;
  position: relative;
  z-index: 10;
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

.btn-roulette:hover:not(:disabled) {
  transform: translateY(-3px) scale(1.02);
  box-shadow: 0 8px 25px rgba(20,184,166,0.6);
  background: linear-gradient(135deg, var(--teal-400) 0%, var(--teal-500) 50%, var(--teal-400) 100%);
  color: #fff;
}

.btn-roulette:active:not(:disabled) {
  transform: translateY(-1px) scale(0.98);
}

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

.btn-roulette.spinning {
  background: linear-gradient(135deg, var(--teal-600) 0%, var(--teal-700) 100%);
  color: white;
  animation: pulse 1s infinite;
}

@keyframes pulse {
  0%, 100% { box-shadow: 0 0 0 0 rgba(20,184,166,0.7); }
  50%       { box-shadow: 0 0 0 15px rgba(20,184,166,0); }
}

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

.roulette-container.active {
  display: block;
  animation: fadeIn 0.5s ease;
}

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

.roulette-wrapper {
  position: relative;
  width: 400px;
  height: 400px;
  margin: 0 auto;
  border-radius: 50%;
  box-shadow: 0 0 60px rgba(20,184,166,0.25);
}

#rouletteCanvas {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  display: block;
  cursor: pointer;
}

.roulette-pointer {
  position: absolute;
  top: -20px;
  left: 50%;
  transform: translateX(-50%);
  font-size: 40px;
  color: var(--red-500);
  text-shadow: 0 4px 15px rgba(0,0,0,0.5);
  z-index: 100;
  filter: drop-shadow(0 0 12px rgba(239,68,68,0.85));
  pointer-events: none;
  animation: bouncePointer 2s infinite;
}

@keyframes bouncePointer {
  0%, 100% { transform: translateX(-50%) translateY(0); }
  50%       { transform: translateX(-50%) translateY(-8px); }
}

.roulette-center {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80px;
  height: 80px;
  background: radial-gradient(circle, var(--teal-400) 0%, var(--teal-700) 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 0 35px rgba(20,184,166,0.85);
  border: 5px solid #fff;
  z-index: 50;
  pointer-events: none;
}

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

.roulette-progress {
  max-width: 400px;
  margin: 25px auto 0;
}

.progress {
  background: rgba(255,255,255,0.1);
  border-radius: 10px;
  overflow: hidden;
}

.progress-bar {
  transition: width 0.1s linear;
}

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

.winner-card {
  background: linear-gradient(135deg, rgba(20,184,166,0.15) 0%, rgba(11,90,82,0.2) 100%);
  border: 3px solid var(--teal-500);
  border-radius: 20px;
  padding: 30px;
  text-align: center;
  backdrop-filter: blur(10px);
  max-width: 400px;
  margin: 20px auto 0;
  box-shadow: 0 0 40px rgba(20,184,166,0.25);
}

.winner-icon {
  font-size: 60px;
  margin-bottom: 15px;
  animation: tada 1s infinite;
}

@keyframes tada {
  0%           { transform: scale(1); }
  10%, 20%     { transform: scale(0.9) rotate(-3deg); }
  30%, 50%, 70%, 90% { transform: scale(1.1) rotate(3deg); }
  40%, 60%, 80%      { transform: scale(1.1) rotate(-3deg); }
  100%         { transform: scale(1) rotate(0); }
}

.winner-title {
  color: var(--teal-400);
  font-size: 14px;
  letter-spacing: 4px;
  font-weight: 800;
  margin-bottom: 15px;
  text-transform: uppercase;
}

.winner-name {
  color: #fff;
  font-size: 28px;
  font-weight: 800;
  margin-bottom: 8px;
  text-shadow: 0 0 25px rgba(20,184,166,0.75);
  line-height: 1.3;
}

.winner-number {
  color: rgba(255,255,255,0.9);
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 20px;
}

.winner-actions {
  display: flex;
  gap: 12px;
  justify-content: center;
  flex-wrap: wrap;
}

/* ─── INFO BOX ───────────────────────────────────────────── */
.info-box {
  background: linear-gradient(135deg, var(--teal-50), #fff);
  border: 1.5px solid var(--teal-100);
  border-radius: var(--radius-sm);
  padding: 20px;
  margin-bottom: 24px;
}
.info-box-row {
  display: flex;
  text-align: center;
}
.info-box-item {
  flex: 1;
  padding: 0 15px;
  border-right: 1px solid var(--slate-200);
}
.info-box-item:last-child {
  border-right: none;
}
.info-box-item .label {
  font-size: 0.75rem;
  color: var(--slate-400);
  text-transform: uppercase;
  letter-spacing: 0.5px;
  margin-bottom: 4px;
}
.info-box-item .value {
  font-size: 1.1rem;
  font-weight: 700;
  color: var(--slate-900);
}
.info-box-item .value.teal  { color: var(--teal-600); }
.info-box-item .value.green { color: var(--green-600); }

/* ─── ALERT INFO ─────────────────────────────────────────── */
.alert-info-custom {
  background: var(--slate-50);
  border: 1.5px solid var(--slate-200);
  border-left: 4px solid var(--teal-500);
  border-radius: var(--radius-sm);
  padding: 18px 22px;
  margin-top: 24px;
}
.alert-info-custom h6 {
  font-size: 0.9rem;
  font-weight: 700;
  color: var(--teal-800);
  margin: 0 0 10px;
  display: flex;
  align-items: center;
  gap: 8px;
}
.alert-info-custom ul {
  margin: 0;
  padding-left: 18px;
  font-size: 0.85rem;
  color: var(--slate-600);
}
.alert-info-custom li {
  margin-bottom: 6px;
}

/* ─── BUTTONS ────────────────────────────────────────────── */
.btn-secondary {
  background: var(--slate-100);
  border: 1.5px solid var(--slate-200);
  color: var(--slate-700);
  font-weight: 600;
  border-radius: var(--radius-xs);
  padding: 10px 20px;
  transition: all .2s;
}
.btn-secondary:hover {
  background: var(--slate-200);
  color: var(--slate-900);
}

.btn-primary {
  background: linear-gradient(135deg, var(--teal-700), var(--teal-500));
  border: none;
  color: #fff;
  font-weight: 700;
  border-radius: var(--radius-xs);
  padding: 12px 28px;
  box-shadow: 0 4px 14px rgba(13,148,136,0.32);
  transition: all .2s;
  font-size: 0.95rem;
}
.btn-primary:hover {
  background: linear-gradient(135deg, var(--teal-800), var(--teal-600));
  box-shadow: 0 6px 18px rgba(13,148,136,0.4);
  transform: translateY(-1px);
}

.btn-success {
  background: linear-gradient(135deg, #10b981, #059669);
  border: none;
  color: #fff;
  font-weight: 700;
  border-radius: var(--radius-xs);
  padding: 10px 20px;
  transition: all .2s;
}
.btn-success:hover {
  background: linear-gradient(135deg, #059669, #047857);
  transform: translateY(-1px);
}

.btn-outline-light {
  border: 2px solid var(--teal-400);
  color: var(--teal-400);
  background: transparent;
  font-weight: 600;
  border-radius: var(--radius-xs);
  padding: 10px 20px;
  transition: all .2s;
}
.btn-outline-light:hover {
  background: var(--teal-400);
  color: #fff;
}

/* ─── ANIMATIONS ─────────────────────────────────────────── */
@keyframes fadeInUp {
  from { opacity: 0; transform: translateY(30px) scale(0.9); }
  to   { opacity: 1; transform: translateY(0) scale(1); }
}

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

.confetti {
  position: fixed;
  width: 12px;
  height: 12px;
  top: -12px;
  z-index: 9999;
  animation: confetti-fall 3s linear forwards;
  border-radius: 50%;
}

/* ─── MOBILE ─────────────────────────────────────────────── */
@media (max-width: 768px) {
  .pt-wrapper { padding: 0 16px 32px; }
  .roulette-wrapper { width: 280px; height: 280px; }
  #rouletteCanvas { width: 280px; height: 280px; }
  .info-box-row { flex-direction: column; }
  .info-box-item { border-right: none; border-bottom: 1px solid var(--slate-200); padding: 10px 0; }
  .info-box-item:last-child { border-bottom: none; }
  .winner-name { font-size: 20px; }
  .btn-roulette { padding: 12px 24px; font-size: 0.9rem; }
}
</style>

<div class="pt-wrapper">

  <!-- ── Page Header ───────────────────────────────────────── -->
  <div class="pt-page-header">
    <div class="pt-header-left">
      <h4>
        <span class="hi"><i class="bi bi-pencil-square"></i></span>
        Edit Pertemuan Arisan
      </h4>
      <div class="pt-breadcrumb">
        <a href="<?php echo base_url('dashboard'); ?>">Dashboard</a>
        <span class="sep">/</span>
        <a href="<?php echo base_url('arisan'); ?>">Arisan</a>
        <span class="sep">/</span>
        <a href="<?php echo base_url('arisan/pertemuan/' . $arisan->id); ?>">Pertemuan</a>
        <span class="sep">/</span>
        <span>Edit</span>
      </div>
    </div>
  </div>

  <!-- ── Main Card ─────────────────────────────────────────── -->
  <div class="pt-card">
    <div class="pt-card-header">
      <div>
        <h5><i class="bi bi-calendar-event"></i> Edit Pertemuan Ke-<?php echo $pertemuan->pertemuan_ke; ?></h5>
        <div class="subtitle"><?php echo $arisan->nama_arisan; ?></div>
      </div>
    </div>
    
    <div class="pt-card-body">
      <?php echo validation_errors('<div class="alert alert-danger alert-dismissible fade show" role="alert"><i class="bi bi-exclamation-triangle-fill me-2"></i>', '<button type="button" class="btn-close" data-bs-dismiss="alert"></button></div>'); ?>
      
      <form action="<?php echo base_url('arisan/edit_pertemuan/' . $pertemuan->id); ?>" method="post" id="formPertemuan">
        
        <!-- Basic Info -->
        <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', $pertemuan->tanggal_pertemuan); ?>">
          </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', $pertemuan->status_pertemuan == 'pending'); ?>>Pending (Belum Terlaksana)</option>
              <option value="terlaksana" <?php echo set_select('status_pertemuan', 'terlaksana', $pertemuan->status_pertemuan == 'terlaksana'); ?>>Terlaksana</option>
              <option value="batal" <?php echo set_select('status_pertemuan', 'batal', $pertemuan->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" id="selectTuanRumah" required>
            <option value="">-- Pilih Tuan Rumah --</option>
            <?php foreach($peserta as $p): ?>
              <option value="<?php echo $p->warga_id; ?>" <?php echo ($p->warga_id == $pertemuan->warga_id_tuan_rumah) ? 'selected' : ''; ?>>
                [<?php echo $p->nomor_urut; ?>] <?php echo $p->nama_lengkap; ?>
              </option>
            <?php endforeach; ?>
          </select>
          <div class="form-text">Rumah siapa pertemuan arisan dilaksanakan</div>
        </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', $pertemuan->tempat_pertemuan); ?>">
        </div>

        <!-- Pemenang Section -->
        <div class="section-header">
          <i class="bi bi-trophy-fill"></i>
          <h6>Data Pemenang Undian</h6>
        </div>

        <!-- Roulette Wheel -->
        <div class="roulette-section">
          <div class="text-center mb-3">
            <button type="button" class="btn btn-roulette" id="btnSpin" 
                    <?php echo empty($peserta_belum_dapat) ? 'disabled' : ''; ?>>
              <i class="bi bi-arrow-repeat"></i>
              <span>🎰 SPIN ROULETTE</span>
            </button>
            <div class="mt-2">
              <small class="text-muted" id="infoPeserta">
                <?php if(empty($peserta_belum_dapat)): ?>
                  <span style="color: #ff6b6b; font-weight: 600;">Semua peserta sudah pernah menang!</span>
                <?php else: ?>
                  <span style="color: #4ecdc4; font-weight: 600;"><?php echo count($peserta_belum_dapat); ?> peserta tersedia di roda</span>
                <?php endif; ?>
              </small>
            </div>
          </div>

          <div class="roulette-container" id="rouletteContainer">
            <div class="roulette-wrapper">
              <canvas id="rouletteCanvas" width="400" height="400"></canvas>
              <div class="roulette-pointer">▼</div>
              <div class="roulette-center">
                <div class="center-text">ARISAN</div>
              </div>
            </div>
            
            <div class="roulette-progress">
              <div class="progress" style="height: 10px;">
                <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" style="font-size: 0.85rem; padding: 8px 16px;">30 detik</span>
              </div>
            </div>

            <div class="winner-display" 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">
                  <button type="button" class="btn btn-success" onclick="confirmWinner()">
                    <i class="bi bi-check-lg"></i> Pilih Pemenang
                  </button>
                  <button type="button" class="btn btn-outline-light" onclick="spinAgain()">
                    <i class="bi bi-arrow-clockwise"></i> Spin Lagi
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- Pemenang Select -->
        <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->warga_id == $pertemuan->pemenang_warga_id) ? 'selected' : ''; ?>>
                  [<?php echo $p->nomor_urut; ?>] <?php echo $p->nama_lengkap; ?>
                </option>
              <?php endforeach; ?>
            </select>
            <div class="form-text">Hanya menampilkan peserta yang belum pernah dapat arisan</div>
          </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', $pertemuan->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', $pertemuan->keterangan); ?></textarea>
        </div>

        <!-- Info Dana -->
        <div class="info-box">
          <div class="info-box-row">
            <div class="info-box-item">
              <div class="label">Total Peserta</div>
              <div class="value"><?php echo count($peserta); ?> Orang</div>
            </div>
            <div class="info-box-item">
              <div class="label">Iuran per Orang</div>
              <div class="value teal">Rp <?php echo number_format($arisan->nominal_iuran, 0, ',', '.'); ?></div>
            </div>
            <div class="info-box-item">
              <div class="label">Total Dana Arisan</div>
              <div class="value green">Rp <?php echo number_format($arisan->nominal_iuran * count($peserta), 0, ',', '.'); ?></div>
            </div>
          </div>
        </div>

        <!-- Actions -->
        <div class="d-flex justify-content-between align-items-center pt-3" style="border-top: 1.5px solid var(--slate-100);">
          <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>Update Pertemuan
          </button>
        </div>
      </form>
    </div>
  </div>

  <!-- Info Alert -->
  <div class="alert-info-custom">
    <h6><i class="bi bi-info-circle"></i> Catatan Penting:</h6>
    <ul>
      <li>Mengedit pertemuan <strong>tidak akan mengubah</strong> data iuran yang sudah dibayar peserta</li>
      <li>Jika mengganti pemenang, riwayat pemenang lama akan dihapus dan diganti dengan yang baru</li>
      <li>Status pertemuan bisa diubah sesuai kondisi real (Pending → Terlaksana/Batal)</li>
      <li>Jika pemenang sudah menerima dana (sudah_diterima = ya), sistem akan memblokir perubahan pemenang</li>
    </ul>
  </div>

</div>
<script>
// ROULETTE WHEEL SCRIPT - VERSI FIXED
(function() {
  'use strict';

  var currentRotation = 0;
  var isSpinning      = false;
  var selectedWinner  = null;
  var spinDuration    = 30000;
  var animFrame       = null;
  var CANVAS_SIZE     = 400;

  var colors = [
    '#FF6B6B','#4ECDC4','#45B7D1','#FFA07A','#98D8C8',
    '#F7DC6F','#BB8FCE','#85C1E2','#F8B739','#52B788',
    '#FF8C94','#A8E6CF','#DCEDC1','#FFD3B6','#FFAAA5',
    '#C7CEEA','#B5EAD7','#FFDAC1','#FF9AA2','#C5C9E6'
  ];

  var pesertaData = [
    <?php 
    $first = true;
    foreach($peserta_belum_dapat as $p): 
      if(!$first) echo ",";
      $first = false;
    ?>
    { id: <?php echo $p->warga_id; ?>, nama: "<?php echo addslashes($p->nama_lengkap); ?>", nomor: <?php echo $p->nomor_urut; ?> }
    <?php endforeach; ?>
  ];

  var canvas, ctx;

  function initCanvas() {
    canvas = document.getElementById('rouletteCanvas');
    if (!canvas) return false;
    ctx = canvas.getContext('2d');

    var wrapper = canvas.parentElement;
    var display = Math.min(wrapper.clientWidth || CANVAS_SIZE, CANVAS_SIZE);
    var dpr     = window.devicePixelRatio || 1;

    canvas.style.width  = display + 'px';
    canvas.style.height = display + 'px';
    canvas.width        = display * dpr;
    canvas.height       = display * dpr;

    ctx.setTransform(1, 0, 0, 1, 0, 0);
    ctx.scale(dpr, dpr);
    CANVAS_SIZE = display;
    return true;
  }

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

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

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

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

      ctx.beginPath();
      ctx.moveTo(cx, cy);
      ctx.arc(cx, cy, radius, start, end);
      ctx.closePath();
      ctx.fillStyle   = colors[i % colors.length];
      ctx.fill();
      ctx.strokeStyle = '#fff';
      ctx.lineWidth   = 3;
      ctx.stroke();

      ctx.save();
      ctx.translate(cx, cy);
      ctx.rotate(start + slice / 2);
      ctx.textAlign   = 'right';
      ctx.fillStyle   = '#fff';
      ctx.font        = 'bold ' + Math.max(10, Math.round(size * 0.032)) + 'px Arial';
      ctx.shadowColor = 'rgba(0,0,0,0.6)';
      ctx.shadowBlur  = 4;
      var lbl = p.nama.length > 8 ? p.nama.substring(0, 8) + '..' : p.nama;
      ctx.fillText('[' + p.nomor + '] ' + lbl, radius - 12, 4);
      ctx.restore();
    });

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

  function highlightWinner(index) {
    drawRoulette(currentRotation);
    var size   = CANVAS_SIZE;
    var cx     = size / 2;
    var cy     = size / 2;
    var radius = cx - 10;
    var slice  = (2 * Math.PI) / pesertaData.length;
    var start  = index * slice + currentRotation;
    var end    = (index + 1) * slice + currentRotation;

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

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

  function createConfetti() {
    var cols = ['#ffd700','#ff6b6b','#4ecdc4','#45b7d1','#ffa07a','#98d8c8'];
    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);

    document.getElementById('winnerDisplay').style.display = 'none';

    var btn = document.getElementById('btnSpin');
    btn.disabled  = true;
    btn.className = btn.className.replace(/\bspinning\b/, '') + ' spinning';
    btn.innerHTML = '<i class="bi bi-arrow-repeat"></i> <span>SPINNING...</span>';

    var container = document.getElementById('rouletteContainer');
    container.classList.add('active');
    container.style.display = 'block';

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

    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';

    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.className = btn.className.replace(/\bspinning\b/, '');
    btn.innerHTML = '<i class="bi bi-arrow-repeat"></i> <span>SPIN LAGI</span>';

    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 scrollTop = wd.getBoundingClientRect().top + window.pageYOffset - 100;
    window.scrollTo({ top: scrollTop, behavior: 'smooth' });
  }
 
  // ── Global helpers dipanggil via onclick ───────────────────
  window.confirmWinner = function() {
    if (!selectedWinner) { alert('Silakan spin roulette terlebih dahulu!'); 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.classList.remove('active');
      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 ───────────────────────────────────────────────────
  function onReady() {
    if (!pesertaData.length) {
      var btn = document.getElementById('btnSpin');
      if (btn) { btn.disabled = true; btn.innerHTML = 'Semua peserta sudah menang'; }
      return;
    }

    if (!initCanvas()) { console.error('Canvas tidak ditemukan'); return; }
    drawRoulette(0);

    // ★ Bind tombol spin — pakai addEventListener (tidak terpengaruh jQuery/Select2)
    var btn = document.getElementById('btnSpin');
    if (btn) {
      btn.addEventListener('click', function(e) {
        e.preventDefault();
        e.stopPropagation();
        spinRoulette();
      });
    }

    // Auto-fill nomor dari dropdown
    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
    if (window.jQuery && window.jQuery.fn.select2) {
      window.jQuery('#selectPemenang, #selectTuanRumah').select2({ placeholder: '-- Pilih --', allowClear: true, width: '100%' });
      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
    var rt;
    window.addEventListener('resize', function() {
      clearTimeout(rt);
      rt = setTimeout(function() { initCanvas(); drawRoulette(currentRotation); }, 200);
    });

    // Pre-fill jika sudah ada pemenang terpilih
    if (selP && selP.value) {
      var opt = selP.options[selP.selectedIndex];
      var nInput = document.getElementById('inputNomorUndian');
      if (opt && opt.dataset.nomor && nInput && !nInput.value) nInput.value = opt.dataset.nomor;
    }
  }

  // Fire saat DOM siap
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', onReady);
  } else {
    onReady();
  }

})();
</script>