@extends('guru.layouts.app')

@section('title', 'Daftar Challenge')

@section('content')

<style>
.page-title {
    font-size: 22px;
    font-weight: 800;
    margin-bottom: 12px;
    margin-top: -10px;
}
@media (min-width: 769px) {
    .page-title { font-size: 30px; margin-top: -20px; margin-bottom: 10px; }
}

.custom-card {
    background: white;
    border-radius: 16px;
    border: 2px solid #e5e5e5;
    padding: 14px;
}
@media (min-width: 769px) { .custom-card { border-radius: 20px; padding: 25px; } }

.btn-primary-custom {
    background: #2b8ef3;
    color: white;
    border-radius: 10px;
    padding: 8px 14px;
    border: none;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    font-size: 13px;
    text-decoration: none;
    cursor: pointer;
    font-family: 'Poppins', sans-serif;
    white-space: nowrap;
}
@media (min-width: 769px) { .btn-primary-custom { padding: 8px 18px; font-size: 14px; gap: 8px; } }

.table-header { background: #a5e6ba; }
.search-box {
    background: #a5e6ba;
    border-radius: 30px;
    padding: 6px 14px;
    display: flex;
    align-items: center;
    gap: 8px;
}
.search-box input {
    border: none;
    outline: none;
    background: transparent;
    width: 130px;
    font-family: 'Poppins', sans-serif;
    font-size: 13px;
}
@media (min-width: 769px) { .search-box input { width: 160px; } }

.action-icon { width: 20px; cursor: pointer; margin: 0 3px; }
.inline-icon { width: 16px; height: 16px; vertical-align: middle; display: inline-block; }

.deadline-badge {
    font-size: 11px; font-weight: 700;
    padding: 3px 8px; border-radius: 99px;
    display: inline-flex; align-items: center; gap: 4px;
    white-space: nowrap;
}
.deadline-aktif { background: #dcfce7; color: #16a34a; }
.deadline-lewat { background: #fee2e2; color: #ef4444; }

.kelas-chip {
    display: inline-block; background: #e6f0ff; color: #1d4ed8;
    font-size: 11px; font-weight: 600; padding: 2px 7px;
    border-radius: 99px; margin: 1px;
}
.soal-count {
    background: #f0fdf4; color: #16a34a;
    font-size: 12px; font-weight: 700;
    padding: 3px 10px; border-radius: 99px;
    white-space: nowrap;
}
.durasi-badge {
    background: #ede9fe; color: #5b21b6;
    font-size: 11px; font-weight: 700;
    padding: 3px 10px; border-radius: 99px;
    display: inline-flex; align-items: center; gap: 4px;
    white-space: nowrap;
}

.alert-success-custom {
    background: #dcfce7; color: #166534;
    border-radius: 10px; padding: 10px 14px;
    margin-bottom: 14px; font-weight: 500; font-size: 13px;
    display: flex; align-items: center; gap: 8px;
}

/* ── TABLE ── */
.table-responsive-custom { overflow-x: auto; -webkit-overflow-scrolling: touch; }
.table { min-width: 640px; }

/* ── TOP BAR ── */
.top-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 10px;
    margin-bottom: 14px;
}

/* ── MODAL ── */
.modal-content {
    border-radius: 16px; border: none;
    box-shadow: 0 10px 40px rgba(0,0,0,0.2);
}
.modal-header-yellow {
    background: #f9c946; color: #1e293b;
    border-bottom: none; border-radius: 16px 16px 0 0;
    padding: 14px 18px;
}
@media (min-width: 769px) { .modal-header-yellow { padding: 18px 24px; } }
.modal-header-yellow .modal-title {
    font-weight: 800; font-size: 16px;
    display: flex; align-items: center; gap: 8px;
}
@media (min-width: 769px) { .modal-header-yellow .modal-title { font-size: 18px; } }
.modal-body label { font-weight: 600; font-size: 13px; }

/* ── STEP INDICATOR ── */
.step-indicator {
    display: flex; align-items: center;
    margin-bottom: 16px; background: #f8fafc;
    border-radius: 12px; padding: 10px 14px;
    border: 1px solid #e2e8f0; flex-shrink: 0;
}
.step-dot {
    width: 28px; height: 28px; border-radius: 50%;
    display: flex; align-items: center; justify-content: center;
    font-size: 12px; font-weight: 800; flex-shrink: 0; transition: all 0.3s;
}
.step-dot.active   { background: #f9c946; color: #1e293b; box-shadow: 0 0 0 3px rgba(249,201,70,.3); }
.step-dot.done     { background: #16a34a; color: white; }
.step-dot.inactive { background: #e2e8f0; color: #94a3b8; }
.step-label { font-size: 11px; font-weight: 700; margin-left: 6px; transition: color 0.3s; }
@media (min-width: 576px) { .step-label { font-size: 12px; margin-left: 8px; } }
.step-label.active   { color: #1e293b; }
.step-label.inactive { color: #94a3b8; }
.step-line { flex: 1; height: 2px; background: #e2e8f0; margin: 0 10px; border-radius: 2px; overflow: hidden; position: relative; }
.step-line-fill { position: absolute; inset: 0; background: #16a34a; transform: scaleX(0); transform-origin: left; transition: transform 0.4s ease; }
.step-line-fill.filled { transform: scaleX(1); }

/* ── STEP PANELS ── */
.step-panel { display: none; }
.step-panel.active { display: block; }

/* ── SOAL CARD ── */
.soal-card {
    background: #f8fafc; border: 1px solid #e2e8f0;
    border-radius: 14px; padding: 14px 16px;
    margin-bottom: 12px; position: relative;
}
.soal-card .soal-number {
    position: absolute; top: -10px; left: 16px;
    background: #667eea; color: white;
    font-size: 11px; font-weight: 700;
    padding: 2px 10px; border-radius: 99px;
}
.soal-card .btn-hapus-soal {
    position: absolute; top: 8px; right: 10px;
    background: #fee2e2; color: #ef4444;
    border: none; border-radius: 8px;
    width: 28px; height: 28px; font-size: 14px;
    cursor: pointer; display: flex; align-items: center; justify-content: center;
}
.soal-card .btn-hapus-soal:hover { background: #fca5a5; }
.opsi-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-top: 8px; }
.opsi-item { display: flex; flex-direction: column; gap: 4px; }
.opsi-item label { font-size: 12px; color: #64748b; font-weight: 600; }
.opsi-item input { border-radius: 8px; border: 1px solid #cbd5e1; padding: 6px 10px; font-size: 13px; }
.jawaban-row {
    display: flex; gap: 10px; align-items: center; margin-top: 10px;
    background: #fff; border-radius: 8px; padding: 8px 12px;
    border: 1px solid #e2e8f0; flex-wrap: wrap;
}
.jawaban-row label { font-size: 12px; color: #64748b; font-weight: 600; min-width: 80px; }
.btn-tambah-soal {
    background: linear-gradient(135deg, #667eea, #764ba2);
    color: white; border: none; border-radius: 10px;
    padding: 9px 18px; font-size: 13px; font-weight: 600;
    cursor: pointer; width: 100%; margin-top: 4px;
    font-family: 'Poppins', sans-serif;
}

.kelas-checkbox-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 8px;
}
@media (min-width: 576px) { .kelas-checkbox-grid { grid-template-columns: repeat(3, 1fr); } }
.kelas-check-item {
    display: flex; align-items: center; gap: 8px;
    background: #f8fafc; border: 1px solid #e2e8f0;
    border-radius: 8px; padding: 8px 10px; cursor: pointer;
    transition: all 0.2s;
}
.kelas-check-item:hover { background: #e6f0ff; border-color: #2b8ef3; }

/* ── MODAL FIXED HEIGHT ── */
.modal-dialog-fixed .modal-content {
    max-height: 92vh; overflow: hidden;
    display: flex; flex-direction: column;
}
.modal-dialog-fixed form { display: contents; }
.modal-dialog-fixed .modal-header,
.modal-dialog-fixed .modal-footer { flex-shrink: 0; }
.modal-dialog-fixed .modal-body {
    flex: 1 1 auto; overflow: hidden;
    display: flex; flex-direction: column;
    min-height: 0; padding-bottom: 0;
}
.modal-dialog-fixed .step-indicator { flex-shrink: 0; margin-bottom: 14px; }
.modal-dialog-fixed .step-panel { display: none; }
.modal-dialog-fixed .step-panel.active {
    display: flex; flex-direction: column;
    flex: 1 1 auto; min-height: 0;
}
#tambah-step-1, #edit-step-1 { overflow-y: auto; padding-right: 4px; }
#tambah-step-2, #edit-step-2 { overflow: hidden; }
.soal-scroll-area {
    flex: 1 1 auto; min-height: 0;
    overflow-y: auto; padding-right: 4px;
    scroll-behavior: smooth;
}
.soal-scroll-area::-webkit-scrollbar { width: 5px; }
.soal-scroll-area::-webkit-scrollbar-track { background: #f1f5f9; border-radius: 99px; }
.soal-scroll-area::-webkit-scrollbar-thumb { background: #cbd5e1; border-radius: 99px; }
.soal-scroll-area::-webkit-scrollbar-thumb:hover { background: #94a3b8; }

/* ── DURASI FIELD ── */
.durasi-input-wrap { position: relative; }
.durasi-input-wrap input { padding-right: 60px; }
.durasi-input-wrap .durasi-unit {
    position: absolute; right: 12px; top: 50%;
    transform: translateY(-50%); font-size: 12px; font-weight: 700;
    color: #5b21b6; pointer-events: none;
}
.durasi-hint { font-size: 11px; color: #94a3b8; margin-top: 4px; font-style: italic; }
.durasi-preview {
    display: inline-flex; align-items: center; gap: 6px;
    background: #ede9fe; color: #5b21b6; font-size: 12px; font-weight: 700;
    padding: 4px 12px; border-radius: 99px; margin-top: 6px; transition: all 0.2s;
}

.section-divider {
    display: flex; align-items: center; gap: 6px;
    font-size: 13px; font-weight: 700; color: #667eea;
    border-bottom: 2px solid #e6f0ff;
    padding-bottom: 6px; margin: 14px 0 10px;
}
.btn-green {
    background: #16a34a; color: white; border: none; border-radius: 10px;
    padding: 8px 18px; font-size: 13px; font-weight: 700;
    cursor: pointer; font-family: 'Poppins', sans-serif;
    display: inline-flex; align-items: center; gap: 6px; transition: background 0.2s;
}
@media (min-width: 769px) { .btn-green { padding: 9px 22px; font-size: 14px; } }
.btn-green:hover { background: #15803d; }
</style>

<h3 class="page-title">DAFTAR CHALLENGE</h3>

@if(session('success'))
    <div class="alert-success-custom">
        <img src="{{ asset('images/icon/gurud/v.png') }}" class="inline-icon" alt="Berhasil">
        {{ session('success') }}
    </div>
@endif

<div class="custom-card">
    <div class="top-bar">
        <button class="btn-primary-custom" onclick="openTambahModal()">
            <img src="{{ asset('images/icon/main/add.png') }}" class="inline-icon" alt="Tambah"> Tambah Challenge
        </button>
        <form method="GET">
            <div class="search-box">
                <input type="text" name="search" placeholder="Cari challenge..."
                       value="{{ request('search') }}">
                <button style="border:none;background:none" type="submit">
                    <img src="{{ asset('images/icon/main/search.png') }}" class="inline-icon" alt="Cari">
                </button>
            </div>
        </form>
    </div>

    <div class="table-responsive-custom">
        <table class="table text-center align-middle">
            <thead class="table-header">
                <tr>
                    <th>No</th>
                    <th>Judul Challenge</th>
                    <th>Kelas</th>
                    <th>Soal</th>
                    <th>Durasi</th>
                    <th>Tenggat</th>
                    <th>Aksi</th>
                </tr>
            </thead>
            <tbody>
                @forelse($challenges as $i => $ch)
                @php $isLewat = \Carbon\Carbon::parse($ch->tenggat_waktu)->isPast(); @endphp
                <tr>
                    <td>{{ $challenges->firstItem() + $i }}</td>
                    <td style="text-align:left;min-width:160px">
                        <div style="font-weight:700;color:#1e293b;white-space:nowrap">{{ $ch->judul_challenge }}</div>
                        @if($ch->deskripsi)
                            <div style="font-size:11px;color:#94a3b8">{{ Str::limit($ch->deskripsi, 40) }}</div>
                        @endif
                    </td>
                    <td style="min-width:100px">
                        @foreach($ch->kelas as $k)
                            <span class="kelas-chip">{{ $k->tingkat }} {{ $k->nama_kelas }}</span>
                        @endforeach
                    </td>
                    <td><span class="soal-count">{{ $ch->soal_count }} soal</span></td>
                    <td>
                        @if($ch->durasi_pengerjaan)
                            <span class="durasi-badge">⏱ {{ $ch->durasi_pengerjaan }} mnt</span>
                        @else
                            <span style="font-size:12px;color:#94a3b8">—</span>
                        @endif
                    </td>
                    <td style="min-width:120px">
                        <span class="deadline-badge {{ $isLewat ? 'deadline-lewat' : 'deadline-aktif' }}">
                            @if($isLewat) Lewat @else Aktif @endif
                        </span>
                        <div style="font-size:11px;color:#64748b;margin-top:3px;white-space:nowrap">
                            {{ \Carbon\Carbon::parse($ch->tenggat_waktu)->format('d M Y, H:i') }}
                        </div>
                    </td>
                    <td style="white-space:nowrap">
                        <button onclick="openEditModal({{ $ch->id_challenge }})"
                                style="border:none;background:none;cursor:pointer">
                            <img src="{{ asset('images/icon/main/edit.png') }}" class="action-icon" alt="Edit">
                        </button>
                        <a href="{{ route('guru.challenge.show', $ch->id_challenge) }}"
                           style="border:none;background:none;display:inline">
                            <img src="{{ asset('images/icon/main/search.png') }}" class="action-icon" alt="Lihat">
                        </a>
                        <form action="{{ route('guru.challenge.destroy', $ch->id_challenge) }}"
                              method="POST" class="d-inline"
                              onsubmit="return confirm('Yakin hapus challenge ini?')">
                            @csrf @method('DELETE')
                            <button type="submit" style="border:none;background:none">
                                <img src="{{ asset('images/icon/main/del.png') }}" class="action-icon" alt="Hapus">
                            </button>
                        </form>
                    </td>
                </tr>
                @empty
                <tr>
                    <td colspan="7" class="text-muted py-4">Belum ada challenge.</td>
                </tr>
                @endforelse
            </tbody>
        </table>
    </div>
    <div class="d-flex justify-content-end mt-2">{{ $challenges->links() }}</div>
</div>

{{-- MODAL TAMBAH --}}
<div class="modal fade" id="modalTambah" tabindex="-1">
  <div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-fixed">
    <div class="modal-content">
      <div class="modal-header modal-header-yellow">
        <h5 class="modal-title">
            <img src="{{ asset('images/icon/gurud/piala.png') }}" class="inline-icon" alt="Piala">
            Tambah Challenge Baru
        </h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <form action="{{ route('guru.challenge.store') }}" method="POST" id="formTambah" novalidate>
        @csrf
        <div class="modal-body">
          <div class="step-indicator">
            <div class="step-dot active" id="tambah-dot-1">1</div>
            <span class="step-label active" id="tambah-label-1">Informasi</span>
            <div class="step-line">
              <div class="step-line-fill" id="tambah-line-fill"></div>
            </div>
            <div class="step-dot inactive" id="tambah-dot-2">2</div>
            <span class="step-label inactive" id="tambah-label-2">Daftar Soal</span>
          </div>

          <div class="step-panel active" id="tambah-step-1">
            <div class="section-divider">
                <img src="{{ asset('images/icon/gurud/buku1.png') }}" class="inline-icon" alt=""> Informasi Challenge
            </div>
            <div class="row g-2 mb-2">
              <div class="col-12">
                <label>Judul Challenge <span class="text-danger">*</span></label>
                {{-- FIXED: removed required --}}
                <input type="text" name="judul_challenge" id="tambah-judul" class="form-control"
                       placeholder="Contoh: Challenge Matematika Minggu Ini">
              </div>
            </div>
            <div class="mb-2">
              <label>Deskripsi</label>
              <textarea name="deskripsi" class="form-control" rows="2"
                        placeholder="Deskripsi singkat challenge (opsional)"></textarea>
            </div>
            <div class="row g-2 mb-2">
              <div class="col-12 col-sm-6">
                <label>Tenggat Waktu <span class="text-danger">*</span></label>
                {{-- FIXED: removed required --}}
                <input type="datetime-local" name="tenggat_waktu" id="tambah-tenggat"
                       class="form-control" min="{{ now()->format('Y-m-d\TH:i') }}">
                <div class="durasi-hint">Batas terakhir challenge bisa dikerjakan</div>
              </div>
              <div class="col-12 col-sm-6">
                <label>Durasi Pengerjaan <span class="text-danger">*</span></label>
                <div class="durasi-input-wrap">
                  {{-- FIXED: removed required --}}
                  <input type="number" name="durasi_pengerjaan" id="tambah-durasi"
                         class="form-control" min="1" max="360" placeholder="cth: 20"
                         oninput="updateDurasiPreview('tambah')">
                  <span class="durasi-unit">menit</span>
                </div>
                <div id="tambah-durasi-preview" class="durasi-preview" style="display:none">
                  ⏱ <span id="tambah-durasi-text">—</span>
                </div>
                <div class="durasi-hint">Waktu hitung mundur saat siswa mengerjakan</div>
              </div>
            </div>
            <div class="section-divider">
                <img src="{{ asset('images/icon/gurud/school.png') }}" class="inline-icon" alt=""> Target Kelas
            </div>
            <div class="kelas-checkbox-grid mb-1">
              @foreach($kelas as $k)
              <label class="kelas-check-item">
                <input type="checkbox" name="id_kelas[]" value="{{ $k->id_kelas }}">
                <span style="font-size:12px;font-weight:600">{{ $k->tingkat }} {{ $k->nama_kelas }}</span>
              </label>
              @endforeach
            </div>
          </div>

          <div class="step-panel" id="tambah-step-2">
            <div class="section-divider" style="flex-shrink:0">
                <img src="{{ asset('images/icon/gurud/buku1.png') }}" class="inline-icon" alt=""> Daftar Soal
            </div>
            <div id="soalContainer" class="soal-scroll-area"></div>
            <div style="flex-shrink:0;padding-top:8px">
              <button type="button" class="btn-tambah-soal" onclick="tambahSoal('soalContainer')">+ Tambah Soal</button>
            </div>
          </div>
        </div>

        <div class="modal-footer" style="gap:8px">
          <button type="button" class="btn btn-secondary" id="tambah-btn-back"
                  data-bs-dismiss="modal">Batal</button>
          <button type="button" class="btn-green" id="tambah-btn-next"
                  onclick="tambahGoStep2()">Berikutnya →</button>
          <button type="submit" class="btn-green" id="tambah-btn-submit" style="display:none">
            <img src="{{ asset('images/icon/gurud/save.png') }}" class="inline-icon" alt=""> Simpan
          </button>
        </div>
      </form>
    </div>
  </div>
</div>

{{-- MODAL EDIT --}}
<div class="modal fade" id="modalEdit" tabindex="-1">
  <div class="modal-dialog modal-xl modal-dialog-centered modal-dialog-fixed">
    <div class="modal-content">
      <div class="modal-header modal-header-yellow">
        <h5 class="modal-title">
            <img src="{{ asset('images/icon/gurud/pencil.png') }}" class="inline-icon" alt=""> Edit Challenge
        </h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <form id="formEdit" method="POST" novalidate>
        @csrf @method('PUT')
        <div class="modal-body">
          <div class="step-indicator">
            <div class="step-dot active" id="edit-dot-1">1</div>
            <span class="step-label active" id="edit-label-1">Informasi</span>
            <div class="step-line">
              <div class="step-line-fill" id="edit-line-fill"></div>
            </div>
            <div class="step-dot inactive" id="edit-dot-2">2</div>
            <span class="step-label inactive" id="edit-label-2">Daftar Soal</span>
          </div>

          <div class="step-panel active" id="edit-step-1">
            <div class="section-divider">
                <img src="{{ asset('images/icon/gurud/buku2.png') }}" class="inline-icon" alt=""> Informasi Challenge
            </div>
            <div class="row g-2 mb-2">
              <div class="col-12 col-sm-8">
                <label>Judul Challenge <span class="text-danger">*</span></label>
                {{-- FIXED: removed required --}}
                <input type="text" name="judul_challenge" id="editJudul" class="form-control">
              </div>
            </div>
            <div class="mb-2">
              <label>Deskripsi</label>
              <textarea name="deskripsi" id="editDeskripsi" class="form-control" rows="2"></textarea>
            </div>
            <div class="row g-2 mb-2">
              <div class="col-12 col-sm-6">
                <label>Tenggat Waktu <span class="text-danger">*</span></label>
                {{-- FIXED: removed required --}}
                <input type="datetime-local" name="tenggat_waktu" id="editTenggat" class="form-control">
                <div class="durasi-hint">Batas terakhir challenge bisa dikerjakan</div>
              </div>
              <div class="col-12 col-sm-6">
                <label>Durasi Pengerjaan <span class="text-danger">*</span></label>
                <div class="durasi-input-wrap">
                  {{-- FIXED: removed required --}}
                  <input type="number" name="durasi_pengerjaan" id="editDurasi"
                         class="form-control" min="1" max="360"
                         oninput="updateDurasiPreview('edit')">
                  <span class="durasi-unit">menit</span>
                </div>
                <div id="edit-durasi-preview" class="durasi-preview" style="display:none">
                  ⏱ <span id="edit-durasi-text">—</span>
                </div>
                <div class="durasi-hint">Waktu hitung mundur saat siswa mengerjakan</div>
              </div>
            </div>
            <div class="section-divider">
                <img src="{{ asset('images/icon/gurud/school.png') }}" class="inline-icon" alt=""> Target Kelas
            </div>
            <div class="kelas-checkbox-grid mb-1" id="editKelasContainer">
              @foreach($kelas as $k)
              <label class="kelas-check-item">
                <input type="checkbox" name="id_kelas[]"
                       value="{{ $k->id_kelas }}" class="edit-kelas-check">
                <span style="font-size:12px;font-weight:600">{{ $k->tingkat }} {{ $k->nama_kelas }}</span>
              </label>
              @endforeach
            </div>
          </div>

          <div class="step-panel" id="edit-step-2">
            <div class="section-divider" style="flex-shrink:0">
                <img src="{{ asset('images/icon/gurud/buku1.png') }}" class="inline-icon" alt=""> Daftar Soal
            </div>
            <div id="editSoalContainer" class="soal-scroll-area"></div>
            <div style="flex-shrink:0;padding-top:8px">
              <button type="button" class="btn-tambah-soal" onclick="tambahSoal('editSoalContainer')">+ Tambah Soal</button>
            </div>
          </div>
        </div>

        <div class="modal-footer" style="gap:8px">
          <button type="button" class="btn btn-secondary" id="edit-btn-back"
                  data-bs-dismiss="modal">Batal</button>
          <button type="button" class="btn-green" id="edit-btn-next"
                  onclick="editGoStep2()">Berikutnya →</button>
          <button type="submit" class="btn-green" id="edit-btn-submit" style="display:none">
            <img src="{{ asset('images/icon/gurud/save.png') }}" class="inline-icon" alt=""> Update
          </button>
        </div>
      </form>
    </div>
  </div>
</div>

<script>
const EDIT_DATA_URL = '{{ route("guru.challenge.editData", ":id") }}';
const UPDATE_URL    = '{{ route("guru.challenge.update",   ":id") }}';

let soalCountTambah = 0;
let soalCountEdit   = 0;

function updateDurasiPreview(prefix) {
    const input   = document.getElementById(prefix === 'edit' ? 'editDurasi' : 'tambah-durasi');
    const preview = document.getElementById(`${prefix}-durasi-preview`);
    const textEl  = document.getElementById(`${prefix}-durasi-text`);
    const val     = parseInt(input.value);
    if (!val || val < 1) { preview.style.display = 'none'; return; }
    preview.style.display = 'inline-flex';
    const jam   = Math.floor(val / 60);
    const menit = val % 60;
    let label = jam > 0 && menit > 0 ? `${jam} jam ${menit} menit` : jam > 0 ? `${jam} jam` : `${menit} menit`;
    textEl.textContent = label;
}

function tambahGoStep2() {
    const judul   = document.getElementById('tambah-judul').value.trim();
    const tenggat = document.getElementById('tambah-tenggat').value;
    const durasi  = document.getElementById('tambah-durasi').value;
    if (!judul)   { alert('Judul challenge wajib diisi.'); return; }
    if (!tenggat) { alert('Tenggat waktu wajib diisi.'); return; }
    if (!durasi || parseInt(durasi) < 1) { alert('Durasi pengerjaan wajib diisi (minimal 1 menit).'); return; }
    document.getElementById('tambah-step-1').classList.remove('active');
    document.getElementById('tambah-step-2').classList.add('active');
    document.getElementById('tambah-dot-1').classList.replace('active','done');
    document.getElementById('tambah-dot-1').textContent = '✓';
    document.getElementById('tambah-label-1').classList.replace('active','inactive');
    document.getElementById('tambah-dot-2').classList.replace('inactive','active');
    document.getElementById('tambah-label-2').classList.replace('inactive','active');
    document.getElementById('tambah-line-fill').classList.add('filled');
    document.getElementById('tambah-btn-next').style.display   = 'none';
    document.getElementById('tambah-btn-submit').style.display = '';
    const backBtn = document.getElementById('tambah-btn-back');
    backBtn.removeAttribute('data-bs-dismiss');
    backBtn.textContent = '← Kembali';
    backBtn.onclick = tambahGoStep1;
}

function tambahGoStep1() {
    document.getElementById('tambah-step-2').classList.remove('active');
    document.getElementById('tambah-step-1').classList.add('active');
    document.getElementById('tambah-dot-1').classList.replace('done','active');
    document.getElementById('tambah-dot-1').textContent = '1';
    document.getElementById('tambah-label-1').classList.replace('inactive','active');
    document.getElementById('tambah-dot-2').classList.replace('active','inactive');
    document.getElementById('tambah-label-2').classList.replace('active','inactive');
    document.getElementById('tambah-line-fill').classList.remove('filled');
    document.getElementById('tambah-btn-next').style.display   = '';
    document.getElementById('tambah-btn-submit').style.display = 'none';
    const backBtn = document.getElementById('tambah-btn-back');
    backBtn.setAttribute('data-bs-dismiss','modal');
    backBtn.textContent = 'Batal';
    backBtn.onclick = null;
}

function editGoStep2() {
    const judul   = document.getElementById('editJudul').value.trim();
    const tenggat = document.getElementById('editTenggat').value;
    const durasi  = document.getElementById('editDurasi').value;
    if (!judul)   { alert('Judul challenge wajib diisi.'); return; }
    if (!tenggat) { alert('Tenggat waktu wajib diisi.'); return; }
    if (!durasi || parseInt(durasi) < 1) { alert('Durasi pengerjaan wajib diisi (minimal 1 menit).'); return; }
    document.getElementById('edit-step-1').classList.remove('active');
    document.getElementById('edit-step-2').classList.add('active');
    document.getElementById('edit-dot-1').classList.replace('active','done');
    document.getElementById('edit-dot-1').textContent = '✓';
    document.getElementById('edit-label-1').classList.replace('active','inactive');
    document.getElementById('edit-dot-2').classList.replace('inactive','active');
    document.getElementById('edit-label-2').classList.replace('inactive','active');
    document.getElementById('edit-line-fill').classList.add('filled');
    document.getElementById('edit-btn-next').style.display   = 'none';
    document.getElementById('edit-btn-submit').style.display = '';
    const backBtn = document.getElementById('edit-btn-back');
    backBtn.removeAttribute('data-bs-dismiss');
    backBtn.textContent = '← Kembali';
    backBtn.onclick = editGoStep1;
}

function editGoStep1() {
    document.getElementById('edit-step-2').classList.remove('active');
    document.getElementById('edit-step-1').classList.add('active');
    document.getElementById('edit-dot-1').classList.replace('done','active');
    document.getElementById('edit-dot-1').textContent = '1';
    document.getElementById('edit-label-1').classList.replace('inactive','active');
    document.getElementById('edit-dot-2').classList.replace('active','inactive');
    document.getElementById('edit-label-2').classList.replace('active','inactive');
    document.getElementById('edit-line-fill').classList.remove('filled');
    document.getElementById('edit-btn-next').style.display   = '';
    document.getElementById('edit-btn-submit').style.display = 'none';
    const backBtn = document.getElementById('edit-btn-back');
    backBtn.setAttribute('data-bs-dismiss','modal');
    backBtn.textContent = 'Batal';
    backBtn.onclick = null;
}

// FIXED: semua atribut 'required' dihapus dari input soal yang di-generate dinamis
// karena browser tidak bisa memvalidasi field yang tidak visible
function tambahSoal(containerId, data = null) {
    const isEdit    = containerId === 'editSoalContainer';
    const count     = isEdit ? ++soalCountEdit : ++soalCountTambah;
    const container = document.getElementById(containerId);
    const card = document.createElement('div');
    card.className = 'soal-card';
    card.innerHTML = `
        <span class="soal-number">Soal ${count}</span>
        <button type="button" class="btn-hapus-soal" onclick="hapusSoal(this,'${containerId}')">✕</button>
        <div class="mb-2" style="margin-top:10px">
            <label>Pertanyaan <span class="text-danger">*</span></label>
            <textarea name="pertanyaan[]" class="form-control" rows="2"
                      placeholder="Tuliskan pertanyaan...">${data ? data.pertanyaan : ''}</textarea>
        </div>
        <div class="opsi-grid">
            <div class="opsi-item"><label>Opsi A</label><input type="text" name="opsi_a[]" class="form-control" placeholder="Opsi A" value="${data ? data.opsi_a : ''}"></div>
            <div class="opsi-item"><label>Opsi B</label><input type="text" name="opsi_b[]" class="form-control" placeholder="Opsi B" value="${data ? data.opsi_b : ''}"></div>
            <div class="opsi-item"><label>Opsi C</label><input type="text" name="opsi_c[]" class="form-control" placeholder="Opsi C" value="${data ? data.opsi_c : ''}"></div>
            <div class="opsi-item"><label>Opsi D</label><input type="text" name="opsi_d[]" class="form-control" placeholder="Opsi D" value="${data ? data.opsi_d : ''}"></div>
        </div>
        <div class="jawaban-row">
            <label>Jawaban Benar</label>
            <select name="jawaban_benar[]" class="form-select" style="width:90px">
                ${['A','B','C','D'].map(o =>
                    `<option value="${o}" ${data?.jawaban_benar === o ? 'selected' : ''}>${o}</option>`
                ).join('')}
            </select>
        </div>`;
    container.appendChild(card);
    renumberSoal(containerId);
    container.scrollTop = container.scrollHeight;
}

function hapusSoal(btn, containerId) {
    if (document.getElementById(containerId).querySelectorAll('.soal-card').length <= 1) {
        alert('Minimal harus ada 1 soal.'); return;
    }
    btn.closest('.soal-card').remove();
    renumberSoal(containerId);
}

function renumberSoal(containerId) {
    document.querySelectorAll(`#${containerId} .soal-card`).forEach((card, i) => {
        const num = card.querySelector('.soal-number');
        if (num) num.textContent = `Soal ${i + 1}`;
    });
}

function openTambahModal() {
    soalCountTambah = 0;
    document.getElementById('soalContainer').innerHTML = '';
    document.getElementById('formTambah').reset();
    document.getElementById('tambah-durasi-preview').style.display = 'none';
    tambahGoStep1();
    tambahSoal('soalContainer');
    new bootstrap.Modal(document.getElementById('modalTambah')).show();
}

async function openEditModal(idChallenge) {
    soalCountEdit = 0;
    document.getElementById('editSoalContainer').innerHTML = '';
    editGoStep1();
    const modalEl       = document.getElementById('modalEdit');
    const existingModal = bootstrap.Modal.getInstance(modalEl);
    if (existingModal) existingModal.dispose();
    try {
        const url = EDIT_DATA_URL.replace(':id', idChallenge);
        const res = await fetch(url);
        if (!res.ok) { alert('Gagal memuat data challenge. Status: ' + res.status); return; }
        const data = await res.json();
        document.getElementById('formEdit').action = UPDATE_URL.replace(':id', idChallenge);
        document.getElementById('editJudul').value     = data.judul_challenge ?? '';
        document.getElementById('editDeskripsi').value = data.deskripsi ?? '';
        document.getElementById('editDurasi').value    = data.durasi_pengerjaan ?? '';
        updateDurasiPreview('edit');
        document.getElementById('editTenggat').value = (data.tenggat_waktu ?? '').slice(0, 16);
        document.querySelectorAll('.edit-kelas-check').forEach(cb => {
            cb.checked = Array.isArray(data.kelas) ? data.kelas.includes(parseInt(cb.value)) : false;
        });
        soalCountEdit = 0;
        data.soal.forEach(s => tambahSoal('editSoalContainer', s));
        new bootstrap.Modal(modalEl).show();
    } catch (err) {
        console.error('openEditModal error:', err);
        alert('Terjadi kesalahan saat memuat data challenge.');
    }
}
</script>

@endsection