@extends('layouts.app')
@section('title', 'Input Data Responden')
@section('content')

<div class="row justify-content-center">
    <div class="col-lg-8">

        {{-- Header --}}
        <div class="card mb-3 border-0"
            style="background:linear-gradient(135deg,#1e3a5f,#2563eb);color:#fff">
            <div class="card-body p-4">
                <div class="d-flex justify-content-between align-items-start flex-wrap gap-2">
                    <div>
                        <div class="d-flex align-items-center gap-2 mb-1">
                            @if($panelTest->test_number)
                            <span class="badge"
                                style="background:rgba(255,255,255,.25);font-size:12px;letter-spacing:.5px">
                                📋 {{ $panelTest->test_number }}
                            </span>
                            @endif
                            @if($panelTest->type === 'internal')
                            <span class="badge"
                                style="background:rgba(255,193,7,.3);color:#fef3c7;font-size:11px">
                                🏢 Internal
                            </span>
                            @endif
                        </div>
                        <h5 class="fw-bold mb-1">{{ $panelTest->title }}</h5>
                        <div class="d-flex gap-3 flex-wrap" style="font-size:13px;opacity:.85">
                            <span><i class="bi bi-box-seam"></i> {{ $panelTest->product->name }}</span>
                            <span><i class="bi bi-calendar3"></i> {{ $panelTest->test_date->format('d M Y') }}</span>
                            @if($panelTest->location)
                            <span><i class="bi bi-geo-alt"></i> {{ $panelTest->location }}</span>
                            @endif
                        </div>
                    </div>
                    <div class="text-end">
                        <span class="badge"
                            style="background:rgba(255,255,255,.25);font-size:13px;padding:6px 12px">
                            <i class="bi bi-hash"></i> Sesi ke-{{ $session->session_number }}
                        </span>
                        <div style="font-size:12px;opacity:.7;margin-top:4px">
                            SPG: {{ auth()->user()->name }}
                        </div>
                    </div>
                </div>
            </div>
        </div>

        @if(session('error'))
        <div class="alert alert-danger alert-dismissible fade show">
            <i class="bi bi-exclamation-circle"></i> {{ session('error') }}
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
        @endif

        <form method="POST" action="{{ route('test-sessions.submit', $session) }}">
            @csrf

            {{-- ===== DATA RESPONDEN ===== --}}
            <div class="card mb-3" style="border:2px solid #f59e0b">
                <div class="card-header py-3"
                    style="background:#fffbeb;border-bottom:1px solid #fde68a">
                    <h6 class="fw-bold mb-0" style="color:#92400e">
                        <i class="bi bi-person-badge-fill"></i> Data Responden
                        <span class="badge bg-warning text-dark ms-2" style="font-size:11px">
                            Wajib Diisi
                        </span>
                    </h6>
                    <small style="color:#b45309">
                        Isi data orang yang sedang melakukan panel test
                    </small>
                </div>
                <div class="card-body p-4">
                    <div class="row g-3">

                        {{-- Nama --}}
                        <div class="col-12">
                            <label class="form-label fw-semibold">
                                <i class="bi bi-person"></i> Nama Lengkap Responden
                                <span class="text-danger">*</span>
                            </label>
                            <input type="text" name="respondent_name"
                                class="form-control form-control-lg @error('respondent_name') is-invalid @enderror"
                                value="{{ old('respondent_name') }}"
                                placeholder="Masukkan nama lengkap responden"
                                autofocus>
                            @error('respondent_name')
                            <div class="invalid-feedback">{{ $message }}</div>
                            @enderror
                        </div>

                        {{-- Nomor Perner (hanya untuk panel test internal) --}}
                        @if($panelTest->type === 'internal')
                        <div class="col-12">
                            <label class="form-label fw-semibold">
                                <i class="bi bi-person-badge text-warning"></i>
                                Nomor Perner
                                <span class="text-danger">*</span>
                                <span class="badge bg-warning text-dark ms-1" style="font-size:10px">
                                    Khusus Internal
                                </span>
                            </label>
                            <div class="input-group">
                                <span class="input-group-text bg-warning-subtle">
                                    <i class="bi bi-upc-scan"></i>
                                </span>
                                <input type="text" name="perner_number"
                                    class="form-control form-control-lg @error('perner_number') is-invalid @enderror"
                                    value="{{ old('perner_number') }}"
                                    placeholder="Contoh: 12345678"
                                    maxlength="8" pattern="[0-9]{8}"
                                    inputmode="numeric"
                                    oninput="this.value=this.value.replace(/[^0-9]/g,'').slice(0,8)"
                                    required>
                                <span class="input-group-text" id="pernerCount"
                                    style="min-width:50px;justify-content:center">0/8</span>
                            </div>
                            @error('perner_number')
                            <div class="invalid-feedback d-block">{{ $message }}</div>
                            @else
                            <div class="form-text">
                                <i class="bi bi-info-circle"></i> Nomor perner terdiri dari 8 digit angka
                            </div>
                            @enderror
                        </div>
                        @endif

                        {{-- ===== DATA LOKASI CONTACT (hanya untuk Marketing) ===== --}}
                        @if(auth()->user()->unit_type === 'marketing')
                        <div class="col-12">
                            <div class="p-3 rounded-3 mb-0"
                                style="background:#eff6ff;border:1.5px solid #bfdbfe">
                                <h6 class="fw-bold mb-3" style="color:#1d4ed8;font-size:13px">
                                    <i class="bi bi-geo-alt-fill"></i> Data Lokasi Contact
                                    <span class="badge bg-primary ms-1" style="font-size:10px">Wajib</span>
                                </h6>
                                <div class="row g-2">

                                    {{-- AREA PROMOTION dari DB --}}
                                    <div class="col-md-6">
                                        <label class="form-label fw-medium small">
                                            Area Promotion <span class="text-danger">*</span>
                                        </label>
                                        @if($areaPromotionOptions->count() > 0)
                                        <select name="area_promotion_name"
                                            class="form-select @error('area_promotion_name') is-invalid @enderror"
                                            required>
                                            <option value="">-- Pilih Area Promotion --</option>
                                            @foreach($areaPromotionOptions as $ap)
                                            <option value="{{ $ap->name }}"
                                                {{ old('area_promotion_name', auth()->user()->area_promotion) === $ap->name ? 'selected' : '' }}>
                                                {{ $ap->name }}
                                            </option>
                                            @endforeach
                                        </select>
                                        @else
                                        <input type="text" name="area_promotion_name"
                                            class="form-control @error('area_promotion_name') is-invalid @enderror"
                                            value="{{ old('area_promotion_name', auth()->user()->area_promotion) }}"
                                            placeholder="Masukkan area promotion" required>
                                        <div class="form-text text-warning">
                                            <i class="bi bi-exclamation-triangle"></i>
                                            Belum ada Area Promotion.
                                            <a href="{{ route('master-data.index') }}" target="_blank">Tambah di Master Data</a>
                                        </div>
                                        @endif
                                        @error('area_promotion_name')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>

                                    {{-- SP dari DB --}}
                                    <div class="col-md-6">
                                        <label class="form-label fw-medium small">
                                            SP (Sentra Promosi) <span class="text-danger">*</span>
                                        </label>
                                        @if($spOptions->count() > 0)
                                        <select name="sp_name"
                                            class="form-select @error('sp_name') is-invalid @enderror"
                                            required>
                                            <option value="">-- Pilih SP --</option>
                                            @foreach($spOptions as $sp)
                                            <option value="{{ $sp->name }}"
                                                {{ old('sp_name') === $sp->name ? 'selected' : '' }}>
                                                {{ $sp->name }}
                                            </option>
                                            @endforeach
                                        </select>
                                        @else
                                        <input type="text" name="sp_name"
                                            class="form-control @error('sp_name') is-invalid @enderror"
                                            value="{{ old('sp_name') }}"
                                            placeholder="Masukkan nama SP" required>
                                        <div class="form-text text-warning">
                                            <i class="bi bi-exclamation-triangle"></i>
                                            Belum ada SP di master data.
                                            <a href="{{ route('master-data.index') }}" target="_blank">Tambah di Master Data</a>
                                        </div>
                                        @endif
                                        @error('sp_name')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>

                                    {{-- PROVINSI --}}
                                    <div class="col-md-6">
                                        <label class="form-label fw-medium small">
                                            Provinsi <span class="text-danger">*</span>
                                        </label>
                                        <select name="provinsi" id="provinsiSelect"
                                            class="form-select @error('provinsi') is-invalid @enderror"
                                            style="width:100%" required>
                                            <option value="">-- Pilih Provinsi --</option>
                                        </select>
                                        @error('provinsi')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>

                                    {{-- KOTA / KABUPATEN --}}
                                    <div class="col-md-6">
                                        <label class="form-label fw-medium small">
                                            Kota / Kabupaten <span class="text-danger">*</span>
                                        </label>
                                        <select name="kota_kabupaten" id="kotaSelect"
                                            class="form-select @error('kota_kabupaten') is-invalid @enderror"
                                            style="width:100%" disabled required>
                                            <option value="">-- Pilih Provinsi dulu --</option>
                                        </select>
                                        @error('kota_kabupaten')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>

                                    {{-- KECAMATAN --}}
                                    <div class="col-md-6">
                                        <label class="form-label fw-medium small">
                                            Kecamatan <span class="text-danger">*</span>
                                        </label>
                                        <select name="kecamatan" id="kecamatanSelect"
                                            class="form-select @error('kecamatan') is-invalid @enderror"
                                            style="width:100%" disabled required>
                                            <option value="">-- Pilih Kota dulu --</option>
                                        </select>
                                        @error('kecamatan')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>

                                    {{-- KELURAHAN --}}
                                    <div class="col-md-6">
                                        <label class="form-label fw-medium small">
                                            Kelurahan <span class="text-danger">*</span>
                                        </label>
                                        <select name="kelurahan" id="kelurahanSelect"
                                            class="form-select @error('kelurahan') is-invalid @enderror"
                                            style="width:100%" disabled required>
                                            <option value="">-- Pilih Kecamatan dulu --</option>
                                        </select>
                                        @error('kelurahan')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>

                                    {{-- Deskripsi --}}
                                    <div class="col-12">
                                        <label class="form-label fw-medium small">
                                            Deskripsi / Catatan Lokasi
                                        </label>
                                        <textarea name="contact_description"
                                            class="form-control" rows="2"
                                            placeholder="Keterangan tambahan lokasi contact...">{{ old('contact_description') }}</textarea>
                                    </div>

                                </div>
                            </div>
                        </div>
                        @endif

                        {{-- Tahun Lahir + Generasi --}}
                        <div class="col-md-5">
                            <label class="form-label fw-semibold">
                                <i class="bi bi-calendar-heart"></i> Tahun Lahir
                                <span class="text-danger">*</span>
                            </label>
                            <div class="input-group">
                                <input type="number" name="birth_year" id="birthYear"
                                    class="form-control form-control-lg @error('birth_year') is-invalid @enderror"
                                    value="{{ old('birth_year') }}"
                                    placeholder="Contoh: 1995"
                                    min="1930" max="{{ date('Y') }}"
                                    oninput="detectGeneration(this.value)"
                                    required>
                                <span class="input-group-text bg-light">tahun</span>
                            </div>
                            @error('birth_year')
                            <div class="text-danger small mt-1">{{ $message }}</div>
                            @enderror
                            <input type="hidden" name="respondent_age" id="ageInput">
                        </div>

                        {{-- Badge Generasi --}}
                        <div class="col-md-7 d-flex align-items-end">
                            <div id="genContainer" class="w-100" style="display:none">
                                <label class="form-label fw-semibold text-muted small">Generasi Terdeteksi</label>
                                <div id="genBadgeDisplay"
                                    class="p-3 rounded-3 d-flex align-items-center gap-3"
                                    style="border:1.5px solid #e2e8f0;background:#f8fafc">
                                    <span id="genEmoji" style="font-size:1.8rem"></span>
                                    <div>
                                        <div class="fw-bold" id="genNameDisplay"></div>
                                        <div class="small text-muted" id="genYearRange"></div>
                                    </div>
                                </div>
                                <input type="hidden" name="generation" id="generationInput">
                            </div>
                            <div id="genPlaceholder" class="w-100">
                                <label class="form-label fw-semibold text-muted small">Generasi</label>
                                <div class="p-3 rounded-3 text-center text-muted"
                                    style="border:1.5px dashed #e2e8f0;background:#f8fafc">
                                    <i class="bi bi-question-circle"></i>
                                    <small class="d-block mt-1">Isi tahun lahir dulu</small>
                                </div>
                            </div>
                        </div>

                        {{-- Jenis Kelamin --}}
                        <div class="col-12">
                            <label class="form-label fw-semibold">
                                <i class="bi bi-gender-ambiguous"></i> Jenis Kelamin
                                <span class="text-danger">*</span>
                            </label>
                            <div class="d-flex gap-3">
                                <label class="gender-card flex-grow-1 p-3 border-2 border rounded-3 text-center"
                                    style="cursor:pointer;transition:all .2s">
                                    <input type="radio" name="respondent_gender"
                                        value="Laki-laki" class="d-none gender-radio"
                                        {{ old('respondent_gender') === 'Laki-laki' ? 'checked' : '' }}>
                                    <div style="font-size:2rem">👨</div>
                                    <div class="fw-semibold">Laki-laki</div>
                                </label>
                                <label class="gender-card flex-grow-1 p-3 border-2 border rounded-3 text-center"
                                    style="cursor:pointer;transition:all .2s">
                                    <input type="radio" name="respondent_gender"
                                        value="Perempuan" class="d-none gender-radio"
                                        {{ old('respondent_gender') === 'Perempuan' ? 'checked' : '' }}>
                                    <div style="font-size:2rem">👩</div>
                                    <div class="fw-semibold">Perempuan</div>
                                </label>
                            </div>
                            @error('respondent_gender')
                            <div class="text-danger small mt-1">{{ $message }}</div>
                            @enderror
                        </div>

                    </div>
                </div>
            </div>

            {{-- ===== DATA KONSUMEN & MARKETING ===== --}}
            <div class="card mb-3" style="border:2px solid #6366f1">
                <div class="card-header py-3"
                    style="background:#eef2ff;border-bottom:1px solid #c7d2fe">
                    <h6 class="fw-bold mb-0" style="color:#3730a3">
                        <i class="bi bi-bar-chart-fill"></i> Data Konsumen & Marketing
                        <span class="badge ms-2" style="background:#6366f1;font-size:11px">Wajib Diisi</span>
                    </h6>
                    <small style="color:#4338ca">Data untuk analisis pemasaran dan kompetitor</small>
                </div>
                <div class="card-body p-4">
                    <div class="row g-3">

                        {{-- Brand Aktivasi dari DB --}}
                        <div class="col-md-6">
                            <label class="form-label fw-semibold">
                                <i class="bi bi-tag-fill"></i> Brand Aktivasi <span class="text-danger">*</span>
                            </label>
                            <select name="brand_aktivasi"
                                class="form-select @error('brand_aktivasi') is-invalid @enderror" required>
                                <option value="">-- Pilih Brand --</option>
                                @foreach($brandAktivasis as $brand)
                                <option value="{{ $brand->name }}"
                                    {{ old('brand_aktivasi') === $brand->name ? 'selected' : '' }}>
                                    {{ $brand->name }}
                                </option>
                                @endforeach
                            </select>
                            @error('brand_aktivasi')<div class="invalid-feedback">{{ $message }}</div>@enderror
                        </div>


                        {{-- Profesi dari DB --}}
                        <div class="col-md-6">
                            <label class="form-label fw-semibold">
                                <i class="bi bi-briefcase-fill"></i> Profesi <span class="text-danger">*</span>
                            </label>
                            <select name="konsumen_profesi"
                                class="form-select @error('konsumen_profesi') is-invalid @enderror" required>
                                <option value="">-- Pilih Profesi --</option>
                                @foreach($profesis as $profesi)
                                <option value="{{ $profesi->name }}"
                                    {{ old('konsumen_profesi') === $profesi->name ? 'selected' : '' }}>
                                    {{ $profesi->name }}
                                </option>
                                @endforeach
                            </select>
                            @error('konsumen_profesi')<div class="invalid-feedback">{{ $message }}</div>@enderror
                        </div>

                        {{-- Pengeluaran RT --}}
                        <div class="col-12">
                            <label class="form-label fw-semibold">
                                <i class="bi bi-wallet2"></i>
                                Pengeluaran Rumah Tangga per Orang per Bulan
                                <span class="text-danger">*</span>
                            </label>
                            <select name="konsumen_pengeluaran"
                                class="form-select @error('konsumen_pengeluaran') is-invalid @enderror" required>
                                <option value="">-- Pilih Range Pengeluaran --</option>
                                @foreach([
                                    '> Rp 9.909.844',
                                    'Rp 5.000.000 - Rp 9.909.844',
                                    'Rp 2.040.262 - 4.999.999',
                                    'Rp 913.740 – Rp 2.040.262',
                                    'Rp 609.160 – Rp 913.740',
                                    '< Rp 609.160',
                                ] as $pengeluaran)
                                <option value="{{ $pengeluaran }}"
                                    {{ old('konsumen_pengeluaran') === $pengeluaran ? 'selected' : '' }}>
                                    {{ $pengeluaran }}
                                </option>
                                @endforeach
                            </select>
                            @error('konsumen_pengeluaran')<div class="invalid-feedback">{{ $message }}</div>@enderror
                        </div>

                        {{-- Funnel dari DB --}}
                        <div class="col-12">
                            <label class="form-label fw-semibold">
                                <i class="bi bi-funnel-fill"></i> Funnel <span class="text-danger">*</span>
                            </label>
                            <div class="d-flex flex-wrap gap-2">
                                @foreach($funnels as $funnel)
                                <label class="funnel-label px-3 py-2 border rounded-pill"
                                    style="cursor:pointer;transition:all .2s;font-size:13px">
                                    <input type="radio" name="konsumen_funnel"
                                        value="{{ $funnel->name }}" class="d-none funnel-radio"
                                        {{ old('konsumen_funnel') === $funnel->name ? 'checked' : '' }} required>
                                    {{ $funnel->name }}
                                </label>
                                @endforeach
                            </div>
                            @error('konsumen_funnel')<div class="text-danger small mt-1">{{ $message }}</div>@enderror
                        </div>

                        {{-- Alasan Tidak Konversi --}}
                        <div class="col-md-6">
                            <label class="form-label fw-semibold">
                                <i class="bi bi-x-circle"></i> Alasan Tidak Konversi
                                <span class="text-muted small">(opsional)</span>
                            </label>
                            <select name="alasan_tidak_konversi"
                                class="form-select @error('alasan_tidak_konversi') is-invalid @enderror">
                                <option value="">-- Pilih Alasan --</option>
                                @foreach([
                                    'Tidak tahu','Tidak butuh','Iklan tidak menarik',
                                    'Sudah pakai produk kompetitor','Khasiat produk kurang manjur',
                                    'Harga mahal','Tidak ada insentif/promo',
                                    'Produk sulit ditemukan','Banyak ulasan negatif',
                                ] as $alasan)
                                <option value="{{ $alasan }}"
                                    {{ old('alasan_tidak_konversi') === $alasan ? 'selected' : '' }}>
                                    {{ $alasan }}
                                </option>
                                @endforeach
                            </select>
                            @error('alasan_tidak_konversi')<div class="invalid-feedback">{{ $message }}</div>@enderror
                        </div>

                        {{-- Tahu Produk Dari Mana --}}
                        <div class="col-12">
                            <label class="form-label fw-semibold">
                                <i class="bi bi-megaphone-fill"></i> Tahu Produk Kita Dari Mana
                                <span class="text-danger">*</span>
                            </label>
                            <div class="row g-2">
                                @foreach([
                                    'Digital Ads [Detik.com, Kompas.com, Google search, Youtube, Podcast, dll]',
                                    'TV [RCTI, Trans TV, Indosiar, Metro Tv, dll]',
                                    'Radio [Prambors, Jak FM, Gen FM, dll]',
                                    'Social media [Instagram, Tiktok, Facebook, Twitter/X, dll]',
                                    'Influencer / KOL [Artis, Selebgram, Selebtok]',
                                    'Media Outdoor [billboard, videotron, baliho, neon box, dll]',
                                    'Media Instore [poster, sticker, wobbler, branding outlet, dll]',
                                    'Event & sponsorship [event musik, event olahraga, dll]',
                                    'E-commerce [Tokopedia, Tiktok Shop, Shopee, Lazada, dll]',
                                    'SPG',
                                    'Other, sebutkan…',
                                ] as $sumber)
                                <div class="col-md-6">
                                    <label class="sumber-label d-flex align-items-center gap-2 p-2 border rounded"
                                        style="cursor:pointer;transition:all .2s;font-size:13px">
                                        <input type="radio" name="sumber_tahu_produk"
                                            value="{{ $sumber }}" class="d-none sumber-radio"
                                            {{ old('sumber_tahu_produk') === $sumber ? 'checked' : '' }} required>
                                        <div class="sumber-dot"
                                            style="width:16px;height:16px;border:2px solid #cbd5e1;border-radius:50%;flex-shrink:0">
                                        </div>
                                        {{ $sumber }}
                                    </label>
                                </div>
                                @endforeach
                            </div>
                            <input type="text" name="sumber_tahu_produk_other" id="sumberOtherInput"
                                class="form-control mt-2"
                                placeholder="Sebutkan sumber lainnya..."
                                value="{{ old('sumber_tahu_produk_other') }}"
                                style="display:none">
                            @error('sumber_tahu_produk')<div class="text-danger small mt-1">{{ $message }}</div>@enderror
                        </div>

                        {{-- Brand Kompetitor dari DB --}}
                        <div class="col-md-6">
                            <label class="form-label fw-semibold">
                                <i class="bi bi-trophy"></i> Brand Kompetitor Yang Digunakan
                                <span class="text-muted small">(opsional)</span>
                            </label>
                            <select name="brand_kompetitor" id="brandKompetitorSelect"
                                class="form-select @error('brand_kompetitor') is-invalid @enderror">
                                <option value="">-- Pilih Brand Kompetitor --</option>
                                @foreach($brandKompetitors as $kompetitor)
                                <option value="{{ $kompetitor->name }}"
                                    {{ old('brand_kompetitor') === $kompetitor->name ? 'selected' : '' }}>
                                    {{ $kompetitor->name }}
                                </option>
                                @endforeach
                                <option value="Other, sebutkan…"
                                    {{ old('brand_kompetitor') === 'Other, sebutkan…' ? 'selected' : '' }}>
                                    Other, sebutkan…
                                </option>
                            </select>
                            <input type="text" name="brand_kompetitor_other" id="kompetitorOtherInput"
                                class="form-control mt-2"
                                placeholder="Sebutkan brand lainnya..."
                                value="{{ old('brand_kompetitor_other') }}"
                                style="display:none">
                            @error('brand_kompetitor')<div class="invalid-feedback">{{ $message }}</div>@enderror
                        </div>

                        {{-- Alasan Pakai Kompetitor --}}
                        <div class="col-md-6">
                            <label class="form-label fw-semibold">
                                <i class="bi bi-question-circle"></i>
                                Alasan Menggunakan Produk Kompetitor
                                <span class="text-muted small">(opsional)</span>
                            </label>
                            <select name="alasan_kompetitor"
                                class="form-select @error('alasan_kompetitor') is-invalid @enderror">
                                <option value="">-- Pilih Alasan --</option>
                                @foreach([
                                    'Sudah percaya produknya : banyak ulasan positif',
                                    'Iklan menarik','Ada momen atau penawaran yang pas',
                                    'Terbukti khasiat manjur','Harga terjangkau',
                                    'Banyak insentif/promo','Produk mudah ditemukan',
                                ] as $alasanKomp)
                                <option value="{{ $alasanKomp }}"
                                    {{ old('alasan_kompetitor') === $alasanKomp ? 'selected' : '' }}>
                                    {{ $alasanKomp }}
                                </option>
                                @endforeach
                            </select>
                            @error('alasan_kompetitor')<div class="invalid-feedback">{{ $message }}</div>@enderror
                        </div>

                    </div>
                </div>
            </div>

            {{-- ===== PERTANYAAN ===== --}}
            @php
                $sampleColors   = ['3b82f6','22c55e','f59e0b','ef4444','8b5cf6'];
                $questionNo     = 1;
                $generalQs      = $panelTest->questions;
                $totalQuestions = $generalQs->count() +
                    $panelTest->samples->sum(fn($s) => $s->questions->count());
            @endphp

            <div class="mb-3">
                <h6 class="fw-bold text-muted mb-0">
                    <i class="bi bi-clipboard-check"></i> Pertanyaan Panel Test
                    <span class="badge bg-primary ms-1">{{ $totalQuestions }} soal</span>
                    @if($panelTest->samples->count() > 0)
                    <span class="badge bg-info text-dark ms-1">{{ $panelTest->samples->count() }} sampel</span>
                    @endif
                </h6>
            </div>

            @if($totalQuestions === 0)
            <div class="card mb-3">
                <div class="card-body text-center py-4 text-muted">
                    <i class="bi bi-question-circle fs-2 d-block mb-2"></i>
                    Belum ada pertanyaan. Hubungi Supervisor.
                </div>
            </div>
            @endif

            {{-- Pertanyaan Umum --}}
            @if($generalQs->count() > 0)
            <div class="mb-2">
                <div class="d-flex align-items-center gap-2 mb-2">
                    <div style="height:2px;flex:1;background:#e2e8f0"></div>
                    <span class="text-muted small fw-medium px-2">
                        <i class="bi bi-list-check"></i> PERTANYAAN UMUM
                    </span>
                    <div style="height:2px;flex:1;background:#e2e8f0"></div>
                </div>
                @foreach($generalQs as $question)
                @include('test-sessions._question', ['question' => $question, 'no' => $questionNo, 'color' => '1e3a5f'])
                @php $questionNo++ @endphp
                @endforeach
            </div>
            @endif

            {{-- Pertanyaan per Sampel --}}
            @foreach($panelTest->samples as $si => $sample)
            @php $color = $sampleColors[$si % 5]; @endphp
            @if($sample->questions->count() > 0)
            <div class="mb-3">
                <div class="d-flex align-items-center gap-2 mb-2">
                    <div style="height:2px;flex:1;background:#e2e8f0"></div>
                    <div class="px-2">
                        <span class="badge px-3 py-2" style="background:#{{ $color }};font-size:13px">
                            Sampel {{ $si + 1 }}: {{ $sample->name }}
                            @if($sample->code)({{ $sample->code }})@endif
                        </span>
                    </div>
                    <div style="height:2px;flex:1;background:#e2e8f0"></div>
                </div>
                @if($sample->description)
                <p class="text-muted small text-center mb-2">{{ $sample->description }}</p>
                @endif
                @foreach($sample->questions as $question)
                @include('test-sessions._question', ['question' => $question, 'no' => $questionNo, 'color' => $color])
                @php $questionNo++ @endphp
                @endforeach
            </div>
            @endif
            @endforeach

            {{-- Submit --}}
            @if($totalQuestions > 0)
            <div class="card border-0 mb-4" style="background:linear-gradient(135deg,#f0fdf4,#dcfce7)">
                <div class="card-body p-4">
                    <div class="d-flex gap-3 justify-content-between align-items-center flex-wrap">
                        <div>
                            <div class="fw-bold text-success">
                                <i class="bi bi-check-circle"></i> Siap menyimpan data?
                            </div>
                            <small class="text-muted">Setelah submit, Anda bisa langsung input responden berikutnya</small>
                        </div>
                        <div class="d-flex gap-2">
                            <a href="{{ route('test-sessions.index') }}" class="btn btn-outline-secondary">
                                <i class="bi bi-x-lg"></i> Batal
                            </a>
                            <button type="submit" class="btn btn-success btn-lg px-4"
                                onclick="return validateForm()">
                                <i class="bi bi-send-fill"></i> Submit & Lanjut
                            </button>
                        </div>
                    </div>
                </div>
            </div>
            @endif

        </form>
    </div>
</div>
@endsection

@push('scripts')
<script>
// ===== API WILAYAH =====
const WILAYAH_API  = 'https://www.emsifa.com/api-wilayah-indonesia/api';
const oldProvinsi  = "{{ old('provinsi') }}";
const oldKota      = "{{ old('kota_kabupaten') }}";
const oldKecamatan = "{{ old('kecamatan') }}";
const oldKelurahan = "{{ old('kelurahan') }}";

async function loadWilayah(selectId, url, placeholder, oldValue = null) {
    const el = document.getElementById(selectId);
    el.innerHTML = `<option value="">Memuat data...</option>`;
    el.disabled  = true;
    try {
        const res  = await fetch(url);
        const data = await res.json();
        el.innerHTML = `<option value="">${placeholder}</option>`;
        data.forEach(item => {
            const opt       = document.createElement('option');
            opt.value       = item.name;
            opt.dataset.id  = item.id;
            opt.textContent = item.name;
            if (oldValue && item.name === oldValue) opt.selected = true;
            el.appendChild(opt);
        });
        el.disabled = false;
        if (oldValue && el.value === oldValue) el.dispatchEvent(new Event('change'));
    } catch (e) {
        el.innerHTML = `<option value="">Gagal memuat. Coba refresh.</option>`;
    }
}

function resetSelect(selectId, placeholder) {
    const el = document.getElementById(selectId);
    el.innerHTML = `<option value="">${placeholder}</option>`;
    el.disabled  = true;
}

document.addEventListener('DOMContentLoaded', () => {
    const provinsiEl = document.getElementById('provinsiSelect');
    if (!provinsiEl) return;
    loadWilayah('provinsiSelect', `${WILAYAH_API}/provinces.json`, '-- Pilih Provinsi --', oldProvinsi);
});

document.getElementById('provinsiSelect')?.addEventListener('change', function () {
    const id = this.options[this.selectedIndex]?.dataset?.id;
    resetSelect('kotaSelect',      '-- Pilih Kota/Kabupaten --');
    resetSelect('kecamatanSelect', '-- Pilih Kecamatan --');
    resetSelect('kelurahanSelect', '-- Pilih Kelurahan --');
    if (!id) return;
    loadWilayah('kotaSelect', `${WILAYAH_API}/regencies/${id}.json`, '-- Pilih Kota/Kabupaten --', oldKota);
});

document.getElementById('kotaSelect')?.addEventListener('change', function () {
    const id = this.options[this.selectedIndex]?.dataset?.id;
    resetSelect('kecamatanSelect', '-- Pilih Kecamatan --');
    resetSelect('kelurahanSelect', '-- Pilih Kelurahan --');
    if (!id) return;
    loadWilayah('kecamatanSelect', `${WILAYAH_API}/districts/${id}.json`, '-- Pilih Kecamatan --', oldKecamatan);
});

document.getElementById('kecamatanSelect')?.addEventListener('change', function () {
    const id = this.options[this.selectedIndex]?.dataset?.id;
    resetSelect('kelurahanSelect', '-- Pilih Kelurahan --');
    if (!id) return;
    loadWilayah('kelurahanSelect', `${WILAYAH_API}/villages/${id}.json`, '-- Pilih Kelurahan --', oldKelurahan);
});

// ===== Generasi =====
const generations = [
    { name:'Baby Boomers',     range:[1946,1964], emoji:'🎖️', color:'#92400e', bg:'#fef3c7', border:'#fcd34d' },
    { name:'Gen X',            range:[1965,1980], emoji:'💼', color:'#3730a3', bg:'#e0e7ff', border:'#a5b4fc' },
    { name:'Milenial / Gen Y', range:[1981,1996], emoji:'💻', color:'#166534', bg:'#dcfce7', border:'#86efac' },
    { name:'Gen Z',            range:[1997,2012], emoji:'📱', color:'#5b21b6', bg:'#ede9fe', border:'#c4b5fd' },
    { name:'Gen Alpha',        range:[2013, new Date().getFullYear()], emoji:'🤖', color:'#9d174d', bg:'#fce7f3', border:'#f9a8d4' },
];

function detectGeneration(birthYear) {
    const year        = parseInt(birthYear);
    const container   = document.getElementById('genContainer');
    const placeholder = document.getElementById('genPlaceholder');
    const ageInput    = document.getElementById('ageInput');
    const genInput    = document.getElementById('generationInput');
    if (!year || year < 1930 || year > new Date().getFullYear()) {
        container.style.display = 'none'; placeholder.style.display = 'block';
        ageInput.value = ''; genInput.value = ''; return;
    }
    const age = new Date().getFullYear() - year;
    ageInput.value = age;
    const gen = generations.find(g => year >= g.range[0] && year <= g.range[1]);
    container.style.display = 'block'; placeholder.style.display = 'none';
    const display = document.getElementById('genBadgeDisplay');
    const emoji   = document.getElementById('genEmoji');
    const name    = document.getElementById('genNameDisplay');
    const range   = document.getElementById('genYearRange');
    if (gen) {
        display.style.background = gen.bg; display.style.borderColor = gen.border;
        emoji.textContent = gen.emoji;
        name.textContent  = gen.name + ' (' + age + ' tahun)';
        name.style.color  = gen.color;
        range.textContent = gen.range[0] + '–' + gen.range[1];
        genInput.value    = gen.name;
    } else {
        display.style.background = '#f8fafc'; display.style.borderColor = '#e2e8f0';
        emoji.textContent = '❓'; name.textContent = 'Di luar rentang generasi';
        range.textContent = ''; genInput.value = '';
    }
}

// ===== Perner Counter =====
const pernerInput = document.querySelector('input[name="perner_number"]');
if (pernerInput) {
    pernerInput.addEventListener('input', function () {
        const count = document.getElementById('pernerCount');
        if (count) {
            const len = this.value.length;
            count.textContent = len + '/8';
            count.style.color = len === 8 ? '#16a34a' : (len > 0 ? '#d97706' : '#94a3b8');
            count.style.fontWeight = len === 8 ? '700' : '400';
        }
    });
}

// ===== Gender Responden =====
document.querySelectorAll('.gender-radio').forEach(radio => {
    radio.addEventListener('change', () => {
        document.querySelectorAll('.gender-card').forEach(c => { c.style.background = ''; c.style.borderColor = ''; c.style.color = ''; });
        const card = radio.closest('.gender-card');
        card.style.background = '#dbeafe'; card.style.borderColor = '#3b82f6'; card.style.color = '#1d4ed8';
    });
    if (radio.checked) radio.dispatchEvent(new Event('change'));
});

// ===== Gender Konsumen =====
document.querySelectorAll('.konsumen-jk-radio').forEach(radio => {
    radio.addEventListener('change', () => {
        document.querySelectorAll('.konsumen-jk').forEach(c => { c.style.background = ''; c.style.borderColor = ''; });
        const card = radio.closest('.konsumen-jk');
        card.style.background = '#dbeafe'; card.style.borderColor = '#3b82f6';
    });
    if (radio.checked) radio.dispatchEvent(new Event('change'));
});

// ===== Funnel =====
document.querySelectorAll('.funnel-radio').forEach(radio => {
    radio.addEventListener('change', () => {
        document.querySelectorAll('.funnel-label').forEach(l => { l.style.background = ''; l.style.borderColor = ''; l.style.color = ''; l.style.fontWeight = ''; });
        const lbl = radio.closest('.funnel-label');
        lbl.style.background = '#6366f1'; lbl.style.borderColor = '#6366f1'; lbl.style.color = '#fff'; lbl.style.fontWeight = '600';
    });
    if (radio.checked) radio.dispatchEvent(new Event('change'));
});

// ===== Sumber Tahu Produk =====
document.querySelectorAll('.sumber-radio').forEach(radio => {
    radio.addEventListener('change', () => {
        document.querySelectorAll('.sumber-label').forEach(lbl => {
            lbl.style.background = ''; lbl.style.borderColor = '';
            const dot = lbl.querySelector('.sumber-dot');
            if (dot) { dot.style.borderColor = '#cbd5e1'; dot.style.background = ''; }
        });
        const lbl = radio.closest('.sumber-label');
        lbl.style.background = '#eef2ff'; lbl.style.borderColor = '#6366f1';
        const dot = lbl.querySelector('.sumber-dot');
        if (dot) { dot.style.borderColor = '#6366f1'; dot.style.background = '#6366f1'; }
        const otherInput = document.getElementById('sumberOtherInput');
        otherInput.style.display = radio.value === 'Other, sebutkan…' ? 'block' : 'none';
        if (radio.value !== 'Other, sebutkan…') otherInput.value = '';
    });
    if (radio.checked) radio.dispatchEvent(new Event('change'));
});

// ===== Brand Kompetitor Other =====
document.getElementById('brandKompetitorSelect')?.addEventListener('change', function () {
    const otherInput = document.getElementById('kompetitorOtherInput');
    otherInput.style.display = this.value === 'Other, sebutkan…' ? 'block' : 'none';
    if (this.value !== 'Other, sebutkan…') otherInput.value = '';
});
if (document.getElementById('brandKompetitorSelect')?.value === 'Other, sebutkan…') {
    document.getElementById('kompetitorOtherInput').style.display = 'block';
}

// ===== Ya/Tidak =====
document.querySelectorAll('.yn-radio').forEach(radio => {
    radio.addEventListener('change', () => {
        const name = radio.name;
        document.querySelectorAll(`input[name="${name}"]`).forEach(r => {
            r.closest('.yn-label').style.background = ''; r.closest('.yn-label').style.borderColor = '';
        });
        radio.closest('.yn-label').style.background = '#dbeafe'; radio.closest('.yn-label').style.borderColor = '#3b82f6';
    });
});

// ===== Rating =====
document.querySelectorAll('.rating-group').forEach(group => {
    const labels = group.querySelectorAll('.rating-label');
    labels.forEach((label, i) => {
        label.addEventListener('click', () => {
            label.querySelector('.rating-radio').checked = true;
            labels.forEach((l, j) => {
                const star = l.querySelector('i');
                if (j <= i) { star.style.color = '#f59e0b'; l.style.background = '#fffbeb'; l.style.borderColor = '#f59e0b'; }
                else { star.style.color = '#d1d5db'; l.style.background = ''; l.style.borderColor = ''; }
            });
        });
    });
});

// ===== Multiple Choice =====
document.querySelectorAll('.mc-radio').forEach(radio => {
    radio.addEventListener('change', () => {
        const name = radio.name;
        document.querySelectorAll(`input[name="${name}"]`).forEach(r => {
            const lbl = r.closest('.mc-label');
            lbl.style.background = ''; lbl.style.borderColor = '';
            const dot = lbl.querySelector('.radio-dot');
            if (dot) { dot.style.borderColor = '#cbd5e1'; dot.style.background = ''; }
        });
        const lbl = radio.closest('.mc-label');
        lbl.style.background = '#dbeafe'; lbl.style.borderColor = '#3b82f6';
        const dot = lbl.querySelector('.radio-dot');
        if (dot) { dot.style.borderColor = '#3b82f6'; dot.style.background = '#3b82f6'; }
    });
});

// ===== Validasi =====
function validateForm() {
    const name    = document.querySelector('input[name="respondent_name"]')?.value.trim();
    const birth   = document.querySelector('input[name="birth_year"]')?.value.trim();
    const gender  = document.querySelector('input[name="respondent_gender"]:checked');
    const perner  = document.querySelector('input[name="perner_number"]');
    const kota    = document.getElementById('kotaSelect');
    const kec     = document.getElementById('kecamatanSelect');
    const kel     = document.getElementById('kelurahanSelect');
    const apName  = document.querySelector('[name="area_promotion_name"]');
    const spName  = document.querySelector('[name="sp_name"]');
    const konsumenProfesi     = document.querySelector('[name="konsumen_profesi"]')?.value;
    const konsumenPengeluaran = document.querySelector('[name="konsumen_pengeluaran"]')?.value;
    const konsumenFunnel      = document.querySelector('input[name="konsumen_funnel"]:checked');
    const sumberTahu          = document.querySelector('input[name="sumber_tahu_produk"]:checked');
    const brandAktivasi       = document.querySelector('[name="brand_aktivasi"]')?.value;

    if (!name)  { alert('❌ Nama responden harus diisi!'); document.querySelector('input[name="respondent_name"]').focus(); return false; }
    if (!birth) { alert('❌ Tahun lahir harus diisi!'); document.querySelector('input[name="birth_year"]').focus(); return false; }
    if (!gender) { alert('❌ Jenis kelamin harus dipilih!'); return false; }
    if (perner && perner.value.length !== 8) { alert('❌ Nomor perner harus 8 digit angka!'); perner.focus(); return false; }
    if (apName && !apName.value) { alert('❌ Area Promotion harus dipilih!'); apName.focus(); return false; }
    if (spName && !spName.value) { alert('❌ SP harus dipilih!'); spName.focus(); return false; }
    if (kota && !kota.value) { alert('❌ Kota/Kabupaten harus dipilih!'); kota.focus(); return false; }
    if (kec  && !kec.value)  { alert('❌ Kecamatan harus dipilih!'); kec.focus(); return false; }
    if (kel  && !kel.value)  { alert('❌ Kelurahan harus dipilih!'); kel.focus(); return false; }
    if (!brandAktivasi)       { alert('❌ Brand Aktivasi harus dipilih!'); return false; }
    if (!konsumenProfesi)     { alert('❌ Profesi konsumen harus dipilih!'); return false; }
    if (!konsumenPengeluaran) { alert('❌ Pengeluaran rumah tangga harus dipilih!'); return false; }
    if (!konsumenFunnel)      { alert('❌ Funnel harus dipilih!'); return false; }
    if (!sumberTahu)          { alert('❌ Sumber tahu produk harus dipilih!'); return false; }

    return true;
}

const oldBirth = document.getElementById('birthYear')?.value;
if (oldBirth) detectGeneration(oldBirth);
</script>
@endpush

