{{-- resources/views/kegiatan/create.blade.php --}}
@extends('layouts.app')

@section('content')
<style>
    /* Optimized CSS - Combined selectors and removed unused styles */
    select[multiple] {
        min-height: 100px;
        max-height: 150px;
    }
    
    select[multiple] option {
        padding: 5px;
    }
    
    select[multiple] option:checked {
        background-color: #007bff;
        color: white;
    }
    
    .form-label small {
        display: block;
        margin-top: 2px;
    }
    
    .anggota-item {
        border-bottom: 1px solid #eee;
        padding: 8px 0;
    }
    
    .anggota-item:last-child {
        border-bottom: none;
    }
    
    .partisipan-checkbox {
        margin-right: 10px;
    }
    
    .selected-partisipan {
        max-height: 300px;
        overflow-y: auto;
        border: 1px solid #ddd;
        border-radius: 5px;
        padding: 10px;
    }
    
    /* Performance optimization - will-change for smooth scrolling */
    .anggota-item, .selected-partisipan {
        will-change: transform;
    }
    
    /* Searchable dropdown styling */
    .dropdown-menu {
        position: absolute;
        top: 100%;
        left: 0;
        z-index: 1000;
        border: 1px solid #dee2e6;
        border-radius: 0.375rem;
        box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
    }

    .dropdown-item {
        padding: 0.5rem 1rem;
        border-bottom: 1px solid #f8f9fa;
    }

    .dropdown-item:hover,
    .dropdown-item.active {
        background-color: #f8f9fa;
        color: #495057;
    }

    .dropdown-item:last-child {
        border-bottom: none;
    }

    .dropdown-item strong {
        color: #007bff;
    }
    
    /* Event type toggle styles */
    #multi_day_fields {
        display: none;
    }
    
    #single_day_fields {
        display: block;
    }
</style>
<!-- Page Header -->
<div class="d-flex flex-column flex-md-row justify-content-between align-items-start align-items-md-center mb-4">
    <div class="mb-3 mb-md-0">
        <h1 class="h2 fw-bold text-dark mb-2">
            <i class="fas fa-calendar-plus text-primary me-2"></i>Tambah Kegiatan
        </h1>
        <p class="text-muted mb-0 fs-6">
            <i class="fas fa-info-circle me-1"></i>Buat kegiatan baru Partai Keadilan Sejahtera
        </p>
    </div>
    <div class="d-flex flex-column flex-sm-row gap-2">
        <a href="{{ route('kegiatan.index') }}" class="btn btn-outline-secondary px-3" style="border-radius: 6px;">
            <i class="fas fa-arrow-left me-1"></i>Kembali
        </a>
    </div>
</div>

<!-- Form Card -->
<div class="card shadow-sm border-0">
    <div class="card-header bg-gradient-primary py-3">
        <h6 class="m-0 font-weight-bold text-white d-flex align-items-center">
            <i class="fas fa-plus me-2"></i>Form Tambah Kegiatan
        </h6>
    </div>
    <div class="card-body p-4">
        @if($errors->any())
            <div class="alert alert-danger">
                <ul class="mb-0">
                    @foreach($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif


                    @if(session('error'))
                        <div class="alert alert-danger">{{ session('error') }}</div>
                    @endif
                    
                    <form action="{{ route('kegiatan.store') }}" method="POST" id="kegiatanForm">
                        @csrf
                        
                        <!-- Info Kegiatan -->
                        <div class="row mb-4">
                            <div class="col-12">
                                <h5 class="text-primary mb-3">
                                    <i class="fas fa-info-circle me-2"></i>Informasi Kegiatan
                                </h5>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-8">
                                <div class="form-group mb-3">
                                    <label for="nama_kegiatan" class="form-label fw-semibold text-dark">
                                        <i class="fas fa-calendar-alt me-1 text-primary"></i>Nama Kegiatan <span class="text-danger">*</span>
                                    </label>
                                    <input type="text" name="nama_kegiatan" id="nama_kegiatan" 
                                           class="form-control @error('nama_kegiatan') is-invalid @enderror" 
                                           placeholder="Masukkan nama kegiatan"
                                           value="{{ old('nama_kegiatan') }}" 
                                           style="border-radius: 6px;" required>
                                    @error('nama_kegiatan')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                            
                            <div class="col-md-4">
                                <div class="form-group mb-3">
                                    <label for="ref_jenis_kegiatan_id" class="form-label fw-semibold text-dark">
                                        <i class="fas fa-tag me-1 text-primary"></i>Jenis Kegiatan <span class="text-danger">*</span>
                                    </label>
                                    <select name="ref_jenis_kegiatan_id" id="ref_jenis_kegiatan_id" 
                                            class="form-control @error('ref_jenis_kegiatan_id') is-invalid @enderror" 
                                            onchange="toggleJenisLainnya()" 
                                            style="border-radius: 6px;" required>
                                        <option value="">-- Pilih Jenis --</option>
                                        @foreach($jenisKegiatans as $jenis)
                                            <option value="{{ $jenis->ref_jenis_kegiatan_id }}" 
                                                    {{ old('ref_jenis_kegiatan_id') == $jenis->ref_jenis_kegiatan_id ? 'selected' : '' }}>
                                                {{ $jenis->nama_jenis_kegiatan }}
                                            </option>
                                        @endforeach
                                        <option value="lainnya" {{ old('ref_jenis_kegiatan_id') == 'lainnya' ? 'selected' : '' }} class="text-warning fw-bold">
                                            <i class="fas fa-edit me-1"></i>Lainnya
                                        </option>
                                    </select>
                                    @error('ref_jenis_kegiatan_id')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                    
                                    <!-- Input untuk jenis kegiatan lainnya -->
                                    <div id="jenis-lainnya-input" class="mt-2" style="display: {{ old('ref_jenis_kegiatan_id') == 'lainnya' ? 'block' : 'none' }};">
                                        <label for="jenis_kegiatan_lainnya" class="form-label text-warning">
                                            <i class="fas fa-pen me-1"></i>Tuliskan jenis kegiatan lainnya:
                                        </label>
                                        <input type="text" class="form-control @error('jenis_kegiatan_lainnya') is-invalid @enderror" 
                                               id="jenis_kegiatan_lainnya" 
                                               name="jenis_kegiatan_lainnya" 
                                               placeholder="Contoh: Rapat Koordinasi, Workshop, dll"
                                               value="{{ old('jenis_kegiatan_lainnya') }}"
                                               style="border-radius: 6px;">
                                        @error('jenis_kegiatan_lainnya')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="form-group mb-3">
                            <label for="deskripsi" class="form-label fw-semibold text-dark">
                                <i class="fas fa-align-left me-1 text-primary"></i>Deskripsi Kegiatan
                            </label>
                            <textarea name="deskripsi" id="deskripsi" class="form-control" rows="3" 
                                      placeholder="Jelaskan deskripsi kegiatan (opsional)"
                                      style="border-radius: 6px;">{{ old('deskripsi') }}</textarea>
                        </div>
                        
                        <!-- Tanggal & Waktu -->
                        <div class="row mb-4">
                            <div class="col-12">
                                <h5 class="text-primary mb-3">
                                    <i class="fas fa-calendar me-2"></i>Tanggal & Waktu
                                </h5>
                            </div>
                        </div>
                        
                        <!-- Event Type Toggle -->
                        <div class="row mb-4">
                            <div class="col-12">
                                <div class="form-group mb-3">
                                    <label class="form-label fw-semibold text-dark">
                                        <i class="fas fa-calendar-alt me-1 text-primary"></i>Jenis Kegiatan <span class="text-danger">*</span>
                                    </label>
                                    <div class="btn-group w-100" role="group" aria-label="Event type">
                                        <input type="radio" class="btn-check" name="event_type" id="single_day" value="single" 
                                               {{ old('event_type', 'single') == 'single' ? 'checked' : '' }}
                                               onchange="toggleEventType()">
                                        <label class="btn btn-outline-primary" for="single_day">
                                            <i class="fas fa-calendar-day me-1"></i>Satu Hari
                                        </label>
                                        
                                        <input type="radio" class="btn-check" name="event_type" id="multi_day" value="multi"
                                               {{ old('event_type') == 'multi' ? 'checked' : '' }}
                                               onchange="toggleEventType()">
                                        <label class="btn btn-outline-primary" for="multi_day">
                                            <i class="fas fa-calendar-week me-1"></i>Lebih dari Satu Hari
                                        </label>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <script>
                        // Inline script to ensure function is available immediately
                        function toggleEventType() {
                            const singleDayRadio = document.getElementById('single_day');
                            const multiDayRadio = document.getElementById('multi_day');
                            const singleDayFields = document.getElementById('single_day_fields');
                            const multiDayFields = document.getElementById('multi_day_fields');
                            
                            if (singleDayRadio && singleDayRadio.checked) {
                                if (singleDayFields) singleDayFields.style.display = 'block';
                                if (multiDayFields) multiDayFields.style.display = 'none';
                            } else if (multiDayRadio && multiDayRadio.checked) {
                                if (singleDayFields) singleDayFields.style.display = 'none';
                                if (multiDayFields) multiDayFields.style.display = 'block';
                            }
                        }
                        
                        // Initialize on page load
                        document.addEventListener('DOMContentLoaded', function() {
                            toggleEventType();
                        });
                        
                        // Filter type toggle function
                        function toggleFilterType() {
                            const filterPerUpa = document.getElementById('filter_per_upa');
                            const filterPerDpc = document.getElementById('filter_per_dpc');
                            const filterPerOrang = document.getElementById('filter_per_orang');
                            
                            const dpcSection = document.getElementById('dpc-filter-section');
                            const upaSection = document.getElementById('upa-filter-section');
                            const namaSection = document.getElementById('nama-filter-section');
                            
                            if (filterPerUpa && filterPerUpa.checked) {
                                // Per UPA: Show DPD, DPC, UPA
                                if (dpcSection) dpcSection.style.display = 'block';
                                if (upaSection) upaSection.style.display = 'block';
                                if (namaSection) namaSection.style.display = 'none';
                                
                                // Enable DPC and UPA fields
                                const filterDpc = document.getElementById('filter-dpc');
                                const filterUpa = document.getElementById('filter-upa');
                                if (filterDpc) filterDpc.disabled = false;
                                if (filterUpa) filterUpa.disabled = true; // Will be enabled when DPC is selected
                                
                            } else if (filterPerDpc && filterPerDpc.checked) {
                                // Per DPC: Show DPD, DPC only
                                if (dpcSection) dpcSection.style.display = 'block';
                                if (upaSection) upaSection.style.display = 'none';
                                if (namaSection) namaSection.style.display = 'none';
                                
                                // Enable DPC field only
                                const filterDpc = document.getElementById('filter-dpc');
                                const filterUpa = document.getElementById('filter-upa');
                                if (filterDpc) filterDpc.disabled = false;
                                if (filterUpa) filterUpa.disabled = true;
                                
                            } else if (filterPerOrang && filterPerOrang.checked) {
                                // Per Orang: Show DPD, Nama Anggota
                                if (dpcSection) dpcSection.style.display = 'none';
                                if (upaSection) upaSection.style.display = 'none';
                                if (namaSection) namaSection.style.display = 'block';
                                
                                // Disable DPC and UPA fields
                                const filterDpc = document.getElementById('filter-dpc');
                                const filterUpa = document.getElementById('filter-upa');
                                if (filterDpc) filterDpc.disabled = true;
                                if (filterUpa) filterUpa.disabled = true;
                            }
                        }
                        </script>
                        
                        <!-- Single Day Event Fields -->
                        <div id="single_day_fields">
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="form-group mb-3">
                                        <label for="tanggal_kegiatan" class="form-label fw-semibold text-dark">
                                            <i class="fas fa-calendar me-1 text-primary"></i>Tanggal <span class="text-danger">*</span>
                                        </label>
                                        <input type="date" name="tanggal_kegiatan" id="tanggal_kegiatan" 
                                               class="form-control @error('tanggal_kegiatan') is-invalid @enderror" 
                                               value="{{ old('tanggal_kegiatan', date('Y-m-d')) }}" 
                                               style="border-radius: 6px;" required>
                                        @error('tanggal_kegiatan')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                                
                                <div class="col-md-4">
                                    <div class="form-group mb-3">
                                        <label for="waktu_mulai" class="form-label fw-semibold text-dark">
                                            <i class="fas fa-clock me-1 text-primary"></i>Jam Mulai <span class="text-danger">*</span>
                                        </label>
                                        <input type="time" name="waktu_mulai" id="waktu_mulai" 
                                               class="form-control @error('waktu_mulai') is-invalid @enderror" 
                                               value="{{ old('waktu_mulai') }}" 
                                               style="border-radius: 6px;" required>
                                        @error('waktu_mulai')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                                
                                <div class="col-md-4">
                                    <div class="form-group mb-3">
                                        <label for="waktu_selesai" class="form-label fw-semibold text-dark">
                                            <i class="fas fa-clock me-1 text-primary"></i>Jam Akhir
                                        </label>
                                        <input type="time" name="waktu_selesai" id="waktu_selesai" 
                                               class="form-control @error('waktu_selesai') is-invalid @enderror" 
                                               value="{{ old('waktu_selesai') }}"
                                               style="border-radius: 6px;">
                                        @error('waktu_selesai')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Multi Day Event Fields -->
                        <div id="multi_day_fields">
                            <div class="row">
                                <div class="col-md-3">
                                    <div class="form-group mb-3">
                                        <label for="tanggal_mulai" class="form-label fw-semibold text-dark">
                                            <i class="fas fa-calendar me-1 text-primary"></i>Tanggal Mulai <span class="text-danger">*</span>
                                        </label>
                                        <input type="date" name="tanggal_mulai" id="tanggal_mulai" 
                                               class="form-control @error('tanggal_mulai') is-invalid @enderror" 
                                               value="{{ old('tanggal_mulai', date('Y-m-d')) }}" 
                                               style="border-radius: 6px;">
                                        @error('tanggal_mulai')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                                
                                <div class="col-md-3">
                                    <div class="form-group mb-3">
                                        <label for="waktu_mulai_multi" class="form-label fw-semibold text-dark">
                                            <i class="fas fa-clock me-1 text-primary"></i>Jam Mulai <span class="text-danger">*</span>
                                        </label>
                                        <input type="time" name="waktu_mulai_multi" id="waktu_mulai_multi" 
                                               class="form-control @error('waktu_mulai_multi') is-invalid @enderror" 
                                               value="{{ old('waktu_mulai_multi') }}" 
                                               style="border-radius: 6px;">
                                        @error('waktu_mulai_multi')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                                
                                <div class="col-md-3">
                                    <div class="form-group mb-3">
                                        <label for="tanggal_selesai" class="form-label fw-semibold text-dark">
                                            <i class="fas fa-calendar-check me-1 text-primary"></i>Tanggal Akhir <span class="text-danger">*</span>
                                        </label>
                                        <input type="date" name="tanggal_selesai" id="tanggal_selesai" 
                                               class="form-control @error('tanggal_selesai') is-invalid @enderror" 
                                               value="{{ old('tanggal_selesai') }}"
                                               style="border-radius: 6px;">
                                        @error('tanggal_selesai')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                                
                                <div class="col-md-3">
                                    <div class="form-group mb-3">
                                        <label for="waktu_selesai_multi" class="form-label fw-semibold text-dark">
                                            <i class="fas fa-clock me-1 text-primary"></i>Jam Akhir
                                        </label>
                                        <input type="time" name="waktu_selesai_multi" id="waktu_selesai_multi" 
                                               class="form-control @error('waktu_selesai_multi') is-invalid @enderror" 
                                               value="{{ old('waktu_selesai_multi') }}"
                                               style="border-radius: 6px;">
                                        @error('waktu_selesai_multi')
                                            <div class="invalid-feedback">{{ $message }}</div>
                                        @enderror
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Tempat & PIC -->
                        <div class="row mb-4">
                            <div class="col-12">
                                <h5 class="text-primary mb-3">
                                    <i class="fas fa-map-marker-alt me-2"></i>Tempat & PIC
                                </h5>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-8">
                                <div class="form-group mb-3">
                                    <label for="tempat" class="form-label fw-semibold text-dark">
                                        <i class="fas fa-map-marker-alt me-1 text-primary"></i>Tempat Kegiatan <span class="text-danger">*</span>
                                    </label>
                                    <input type="text" name="tempat" id="tempat" 
                                           class="form-control @error('tempat') is-invalid @enderror" 
                                           placeholder="Masukkan lokasi kegiatan"
                                           value="{{ old('tempat') }}" 
                                           style="border-radius: 6px;" required>
                                    @error('tempat')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                            
                            <div class="col-md-4">
                                <div class="form-group mb-3">
                                    <label for="target_peserta" class="form-label fw-semibold text-dark">
                                        <i class="fas fa-users me-1 text-primary"></i>Target Peserta
                                    </label>
                                    <input type="number" name="target_peserta" id="target_peserta" 
                                           class="form-control @error('target_peserta') is-invalid @enderror" 
                                           placeholder="Jumlah target peserta"
                                           value="{{ old('target_peserta') }}" 
                                           style="border-radius: 6px;" min="1">
                                    @error('target_peserta')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group mb-3">
                                    <label for="pic_search" class="form-label fw-semibold text-dark">
                                        <i class="fas fa-user-tie me-1 text-primary"></i>Person in Charge (PIC)
                                    </label>
                                    <div class="position-relative">
                                        <input type="text" class="form-control @error('pic_anggota_id') is-invalid @enderror" 
                                               id="pic_search" name="pic_search" 
                                               placeholder="Cari PIC..." 
                                               autocomplete="off" style="border-radius: 6px;">
                                        <input type="hidden" id="pic_anggota_id" name="pic_anggota_id" 
                                               value="{{ old('pic_anggota_id') }}">
                                        <div id="pic_dropdown" class="dropdown-menu w-100" style="display: none; max-height: 300px; overflow-y: auto;">
                                            <!-- Options will be populated by JavaScript -->
                                        </div>
                                    </div>
                                    @error('pic_anggota_id')
                                        <div class="invalid-feedback">{{ $message }}</div>
                                    @enderror
                                </div>
                            </div>
                            
                            <div class="col-md-6">
                                <div class="form-group mb-3">
                                    <label for="catatan" class="form-label fw-semibold text-dark">
                                        <i class="fas fa-sticky-note me-1 text-primary"></i>Catatan
                                    </label>
                                    <textarea name="catatan" id="catatan" class="form-control" rows="2" 
                                              placeholder="Catatan tambahan (opsional)"
                                              style="border-radius: 6px;">{{ old('catatan') }}</textarea>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Daftar Partisipan -->
                        <div class="row mb-4">
                            <div class="col-12">
                                <h5 class="text-primary mb-3">
                                    <i class="fas fa-users me-2"></i>Daftar Partisipan
                                </h5>
                            </div>
                        </div>
                        
                        {{-- Filter Partisipan --}}
                        <div class="row mb-3">
                            <div class="col-md-12">
                                <div class="card">
                                    <div class="card-header">
                                        <h6 class="mb-0"><i class="fas fa-filter"></i> Filter Pemilihan Peserta</h6>
                                    </div>
                                    <div class="card-body">
                                        <!-- Filter Type Toggle -->
                                        <div class="row mb-3">
                                            <div class="col-12">
                                                <label class="form-label fw-semibold">
                                                    <i class="fas fa-cogs me-1 text-primary"></i>Jenis Filter <span class="text-danger">*</span>
                                                </label>
                                                <div class="btn-group w-100" role="group" aria-label="Filter type">
                                                    <input type="radio" class="btn-check" name="filter_type" id="filter_per_upa" value="upa" 
                                                           {{ old('filter_type', 'upa') == 'upa' ? 'checked' : '' }}
                                                           onchange="toggleFilterType()">
                                                    <label class="btn btn-outline-primary" for="filter_per_upa">
                                                        <i class="fas fa-users me-1"></i>Per UPA
                                                    </label>
                                                    
                                                    <input type="radio" class="btn-check" name="filter_type" id="filter_per_dpc" value="dpc"
                                                           {{ old('filter_type') == 'dpc' ? 'checked' : '' }}
                                                           onchange="toggleFilterType()">
                                                    <label class="btn btn-outline-primary" for="filter_per_dpc">
                                                        <i class="fas fa-building me-1"></i>Per DPC
                                                    </label>
                                                    
                                                    <input type="radio" class="btn-check" name="filter_type" id="filter_per_orang" value="orang"
                                                           {{ old('filter_type') == 'orang' ? 'checked' : '' }}
                                                           onchange="toggleFilterType()">
                                                    <label class="btn btn-outline-primary" for="filter_per_orang">
                                                        <i class="fas fa-user me-1"></i>Per Orang
                                                    </label>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Filter Fields -->
                                        <div class="row">
                                            <div class="col-md-2">
                                                <label class="form-label">Jenis Kelamin</label>
                                                <select id="filter-jenis-kelamin" class="form-control">
                                                    <option value="">Semua</option>
                                                    <option value="L">Laki-laki</option>
                                                    <option value="P">Perempuan</option>
                                                </select>
                                            </div>
                                            
                                            <!-- DPD Field (always visible) -->
                                            <div class="col-md-2">
                                                <label class="form-label">DPD</label>
                                                <select id="filter-dpd" class="form-control">
                                                    <option value="">Semua</option>
                                                    @php
                                                        $dpdList = cache()->remember('dpd_active_list', 600, function() {
                                                            return \App\Models\Dpd::active()->select(['dpd_id', 'nama_dpd'])->get();
                                                        });
                                                    @endphp
                                                    @foreach($dpdList as $dpd)
                                                        <option value="{{ $dpd->dpd_id }}">{{ $dpd->nama_dpd }}</option>
                                                    @endforeach
                                                </select>
                                            </div>
                                            
                                            <!-- DPC Field (visible for DPC and UPA filter) -->
                                            <div class="col-md-2" id="dpc-filter-section">
                                                <label class="form-label">DPC</label>
                                                <select id="filter-dpc" class="form-control" multiple>
                                                    <option value="">Pilih DPD dulu</option>
                                                </select>
                                                <small class="text-muted">Pilih satu atau lebih DPC</small>
                                            </div>
                                            
                                            <!-- UPA Field (visible only for UPA filter) -->
                                            <div class="col-md-2" id="upa-filter-section">
                                                <label class="form-label">UPA</label>
                                                <select id="filter-upa" class="form-control" multiple disabled>
                                                    <option value="">Pilih DPC dulu</option>
                                                </select>
                                                <small class="text-muted">Pilih satu atau lebih UPA</small>
                                            </div>
                                            
                                            <!-- Nama Anggota Field (visible only for per orang filter) -->
                                            <div class="col-md-2" id="nama-filter-section" style="display: none;">
                                                <label class="form-label">Nama Anggota</label>
                                                <input type="text" id="filter-nama" class="form-control" placeholder="Cari nama...">
                                            </div>
                                            
                                            <div class="col-md-2">
                                                <label class="form-label">&nbsp;</label>
                                                <button type="button" id="reset-filter" class="btn btn-outline-secondary btn-block">
                                                    <i class="fas fa-undo"></i>
                                                </button>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group mb-3">
                                    <label>Pilih Anggota Partisipan:</label>
                                    <div class="border p-3" style="max-height: 300px; overflow-y: auto;" id="anggota-list">
                                        <div id="anggota-content">
                                            @php
                                                $oldPartisipan = collect(old('partisipan', []));
                                            @endphp
                                            @foreach($anggotas as $anggota)
                                            @php
                                                $isChecked = $oldPartisipan->contains($anggota->id);
                                                $jenjang = $anggota->refJenjang->jenjang ?? 'N/A';
                                                $jenisKelamin = $anggota->jenis_kelamin == 'L' ? 'Laki-laki' : 'Perempuan';
                                                $grupUpa = $anggota->refGrupUpa->nama_grup_upa ?? 'N/A';
                                                $dpc = $anggota->dpc->nama_dpc ?? 'N/A';
                                                $dpd = $anggota->dpd->nama_dpd ?? 'N/A';
                                            @endphp
                                            <div class="form-check mb-2 anggota-item" 
                                                 data-nama="{{ strtolower($anggota->nama_lengkap) }}"
                                                 data-jenis-kelamin="{{ $anggota->jenis_kelamin }}"
                                                 data-upa="{{ $anggota->ref_grup_upa_id }}"
                                                 data-dpc="{{ $anggota->dpc_id }}"
                                                 data-dpd="{{ $anggota->dpd_id }}">
                                                <input class="form-check-input partisipan-checkbox" type="checkbox" 
                                                       name="partisipan[]" value="{{ $anggota->id }}" 
                                                       id="anggota_{{ $anggota->id }}"
                                                       {{ $isChecked ? 'checked' : '' }}>
                                                <label class="form-check-label" for="anggota_{{ $anggota->id }}">
                                                    <strong>{{ $anggota->nama_lengkap }}</strong><br>
                                                    <small class="text-muted">
                                                        {{ $jenjang }} - {{ $jenisKelamin }} - {{ $grupUpa }} - {{ $dpc }} - {{ $dpd }}
                                                    </small>
                                                </label>
                                            </div>
                                            @endforeach
                                        </div>
                                        
                                        <!-- Pagination untuk data anggota -->
                                        <div class="d-flex justify-content-center mt-3" id="anggota-pagination">
                                            <!-- Pagination removed - using full collection -->
                                        </div>
                                    </div>
                                    <small class="text-muted">Centang untuk memilih anggota sebagai partisipan kegiatan</small>
                                </div>
                            </div>
                            
                            <div class="col-md-6">
                                <div class="form-group mb-3">
                                    <label>Partisipan Terpilih:</label>
                                    <div id="selected-partisipan" class="border p-3" style="min-height: 300px;">
                                        <div class="text-muted text-center py-5">
                                            <i class="fas fa-user-plus fa-2x mb-2"></i><br>
                                            Pilih anggota dari daftar sebelah kiri
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="d-flex justify-content-end gap-2 mt-4">
                            <a href="{{ route('kegiatan.index') }}" class="btn btn-outline-secondary px-4" style="border-radius: 6px;">
                                <i class="fas fa-times me-1"></i>Batal
                            </a>
                            <button type="submit" class="btn btn-primary px-4" id="submitBtn" style="border-radius: 6px;">
                                <i class="fas fa-save me-1"></i><span class="btn-text">Simpan Kegiatan</span>
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
// Function untuk toggle input jenis kegiatan lainnya - GLOBAL SCOPE
function toggleJenisLainnya() {
    const select = document.getElementById('ref_jenis_kegiatan_id');
    const inputDiv = document.getElementById('jenis-lainnya-input');
    const input = document.getElementById('jenis_kegiatan_lainnya');
    
    if (!select || !inputDiv || !input) {
        return;
    }
    
    if (select.value === 'lainnya') {
        inputDiv.style.display = 'block';
        input.focus();
        input.required = true;
    } else {
        inputDiv.style.display = 'none';
        input.value = '';
        input.required = false;
    }
}

document.addEventListener('DOMContentLoaded', function() {
    const checkboxes = document.querySelectorAll('.partisipan-checkbox');
    const selectedContainer = document.getElementById('selected-partisipan');
    const targetPesertaInput = document.getElementById('target_peserta');
    
    // Filter elements
    const filterNama = document.getElementById('filter-nama');
    const filterJenisKelamin = document.getElementById('filter-jenis-kelamin');
    const filterUpa = document.getElementById('filter-upa');
    const filterDpc = document.getElementById('filter-dpc');
    const filterDpd = document.getElementById('filter-dpd');
    const resetFilter = document.getElementById('reset-filter');
    
    // Check if all required elements exist
    if (!filterDpd || !filterDpc || !filterUpa) {
        console.error('One or more filter elements not found');
        return; // Exit if elements not found
    }
    
    // Debounce function untuk optimasi performa
    function debounce(func, wait) {
        let timeout;
        return function executedFunction(...args) {
            const later = () => {
                clearTimeout(timeout);
                func(...args);
            };
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
        };
    }
    
    // Cache untuk menyimpan data yang sudah difilter
    let filteredAnggotaItems = null;
    let allAnggotaItems = document.querySelectorAll('.anggota-item');
    let currentPage = 1;
    let isLoading = false;
    
    // Update selected partisipan display
    function updateSelectedPartisipan() {
        const selected = document.querySelectorAll('.partisipan-checkbox:checked');
        
        // Update target peserta otomatis
        targetPesertaInput.value = selected.length;
        
        if (selected.length === 0) {
            selectedContainer.innerHTML = `
                <div class="text-muted text-center py-5">
                    <i class="fas fa-user-plus fa-2x mb-2"></i><br>
                    Pilih anggota dari daftar sebelah kiri
                </div>
            `;
            return;
        }
        
        let html = '<div class="mb-2"><strong>Partisipan Terpilih (' + selected.length + ' orang):</strong></div>';
        
        selected.forEach((checkbox, index) => {
            const label = document.querySelector(`label[for="${checkbox.id}"]`);
            const nama = label.querySelector('strong').textContent;
            const info = label.querySelector('small').textContent;
            const anggotaId = checkbox.value;
            
            html += `
                <div class="border-bottom pb-2 mb-2">
                    <div class="row align-items-center">
                        <div class="col-8">
                            <strong>${nama}</strong><br>
                            <small class="text-muted">${info}</small>
                        </div>
                        <div class="col-4">
                            <select name="status_partisipasi[]" class="form-control form-control-sm">
                                <option value="Wajib" selected>Wajib</option>
                                <option value="Opsional">Opsional</option>
                                <option value="Undangan">Undangan</option>
                            </select>
                        </div>
                    </div>
                </div>
            `;
        });
        
        selectedContainer.innerHTML = html;
    }
    
    // Load DPC berdasarkan DPD
    function loadDpcByDpd(dpdId) {
        console.log('loadDpcByDpd called with dpdId:', dpdId);
        const filterDpcElement = document.getElementById('filter-dpc');
        
        if (!filterDpcElement) {
            console.error('filterDpc element not found!');
            return;
        }
        
        if (!dpdId) {
            console.log('No dpdId, resetting DPC dropdown');
            filterDpcElement.innerHTML = '<option value="">Pilih DPD dulu</option>';
            filterDpcElement.disabled = true;
            loadUpaByDpc([]);
            return;
        }
        
        console.log('Fetching DPC data for DPD:', dpdId);
        fetch(`/api/dpc-by-dpd/${dpdId}`, {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
            },
            credentials: 'same-origin'
        })
            .then(response => {
                console.log('API response status:', response.status);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                console.log('DPC data received:', data);
                filterDpcElement.innerHTML = '';
                data.forEach(dpc => {
                    filterDpcElement.innerHTML += `<option value="${dpc.dpc_id}">${dpc.nama_dpc}</option>`;
                });
                filterDpcElement.disabled = false;
                console.log('DPC dropdown updated successfully');
            })
            .catch(error => {
                console.error('Error loading DPC:', error);
                filterDpcElement.innerHTML = '<option value="">Error loading DPC</option>';
            });
    }
    
    // Load UPA berdasarkan DPC (multiple)
    function loadUpaByDpc(dpcIds) {
        if (!dpcIds || dpcIds.length === 0) {
            filterUpa.innerHTML = '<option value="">Pilih DPC dulu</option>';
            filterUpa.disabled = true;
            return;
        }
        
        // Jika array, gabungkan dengan koma untuk API
        const dpcIdString = Array.isArray(dpcIds) ? dpcIds.join(',') : dpcIds;
        
        fetch(`/api/upa-by-dpc/${dpcIdString}`, {
            method: 'GET',
            headers: {
                'X-Requested-With': 'XMLHttpRequest',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
            },
            credentials: 'same-origin'
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                filterUpa.innerHTML = '';
                data.forEach(upa => {
                    filterUpa.innerHTML += `<option value="${upa.ref_grup_upa_id}">${upa.nama_grup_upa}</option>`;
                });
                filterUpa.disabled = false;
            })
            .catch(error => {
                console.error('Error loading UPA:', error);
                filterUpa.innerHTML = '<option value="">Error loading UPA</option>';
            });
    }
    
    
    function resetFilters() {
        filterNama.value = '';
        filterJenisKelamin.value = '';
        filterDpd.value = '';
        filterDpc.innerHTML = '<option value="">Pilih DPD dulu</option>';
        filterDpc.disabled = true;
        filterUpa.innerHTML = '<option value="">Pilih DPC dulu</option>';
        filterUpa.disabled = true;
    }
    
    // Event listeners
    checkboxes.forEach(checkbox => {
        checkbox.addEventListener('change', updateSelectedPartisipan);
    });
    
    // Debounced filter function untuk optimasi performa
    const debouncedFilterAnggota = debounce(() => {
        loadAnggotaPage(1); // Reset ke halaman 1 saat filter
    }, 300);
    
    // Function to get current filter type
    function getCurrentFilterType() {
        const filterPerUpa = document.getElementById('filter_per_upa');
        const filterPerDpc = document.getElementById('filter_per_dpc');
        const filterPerOrang = document.getElementById('filter_per_orang');
        
        if (filterPerUpa && filterPerUpa.checked) return 'upa';
        if (filterPerDpc && filterPerDpc.checked) return 'dpc';
        if (filterPerOrang && filterPerOrang.checked) return 'orang';
        return 'upa'; // default
    }
    
    // Filter event listeners dengan debouncing
    if (filterNama) {
        filterNama.addEventListener('input', debouncedFilterAnggota);
    }
    
    if (filterJenisKelamin) {
        filterJenisKelamin.addEventListener('change', () => loadAnggotaPage(1));
    }
    
    if (filterDpd) {
        filterDpd.addEventListener('change', function() {
            console.log('DPD changed to:', this.value);
            loadDpcByDpd(this.value);
            loadAnggotaPage(1);
        });
        console.log('DPD event listener added');
    } else {
        console.error('filterDpd not found');
    }
    
    if (filterDpc) {
        filterDpc.addEventListener('change', function() {
            const selectedDpcIds = Array.from(this.selectedOptions).map(option => option.value);
            loadUpaByDpc(selectedDpcIds);
            loadAnggotaPage(1);
        });
    }
    filterUpa.addEventListener('change', () => loadAnggotaPage(1));
    resetFilter.addEventListener('click', function() {
        resetFilters();
        loadAnggotaPage(1);
    });
    
    // Initialize pada load jika ada old values
    updateSelectedPartisipan();
    
    // Global function for event type toggle
    window.toggleEventType = function() {
        const singleDayRadio = document.getElementById('single_day');
        const multiDayRadio = document.getElementById('multi_day');
        const singleDayFields = document.getElementById('single_day_fields');
        const multiDayFields = document.getElementById('multi_day_fields');
        
        if (singleDayRadio && singleDayRadio.checked) {
            if (singleDayFields) singleDayFields.style.display = 'block';
            if (multiDayFields) multiDayFields.style.display = 'none';
            
            // Set required attributes
            const tanggalKegiatan = document.getElementById('tanggal_kegiatan');
            const waktuMulai = document.getElementById('waktu_mulai');
            const waktuSelesai = document.getElementById('waktu_selesai');
            
            if (tanggalKegiatan) tanggalKegiatan.required = true;
            if (waktuMulai) waktuMulai.required = true;
            if (waktuSelesai) waktuSelesai.required = false;
            
        } else if (multiDayRadio && multiDayRadio.checked) {
            if (singleDayFields) singleDayFields.style.display = 'none';
            if (multiDayFields) multiDayFields.style.display = 'block';
            
            // Set required attributes
            const tanggalMulai = document.getElementById('tanggal_mulai');
            const tanggalSelesai = document.getElementById('tanggal_selesai');
            const waktuMulaiMulti = document.getElementById('waktu_mulai_multi');
            const waktuSelesaiMulti = document.getElementById('waktu_selesai_multi');
            
            if (tanggalMulai) tanggalMulai.required = true;
            if (tanggalSelesai) tanggalSelesai.required = true;
            if (waktuMulaiMulti) waktuMulaiMulti.required = true;
            if (waktuSelesaiMulti) waktuSelesaiMulti.required = false;
        }
    };
    
    // Initialize on page load
    document.addEventListener('DOMContentLoaded', function() {
        setTimeout(function() {
            window.toggleEventType();
            // Initialize filter type toggle
            if (typeof toggleFilterType === 'function') {
                toggleFilterType();
            }
        }, 100);
    });
    
    // Auto-fill tanggal selesai jika kosong (for multi-day events)
    document.getElementById('tanggal_mulai').addEventListener('change', function() {
        const tanggalMulai = this.value;
        const tanggalSelesai = document.getElementById('tanggal_selesai');
        
        if (tanggalMulai && !tanggalSelesai.value && multiDayRadio.checked) {
            tanggalSelesai.value = tanggalMulai;
        }
    });
    
    // Optimasi loading - preload data yang mungkin dibutuhkan
    const preloadData = () => {
        // Preload DPC data untuk DPD yang paling sering digunakan
        const mostUsedDpd = filterDpd.querySelector('option[value]:not([value=""])');
        if (mostUsedDpd) {
            loadDpcByDpd(mostUsedDpd.value);
        }
    };
    
    // Preload data setelah DOM selesai dimuat
    setTimeout(preloadData, 100);
    
    // AJAX Pagination untuk data anggota
    function loadAnggotaPage(page) {
        if (isLoading) return;
        
        isLoading = true;
        const loadingHtml = '<div class="text-center py-3"><i class="fas fa-spinner fa-spin"></i> Memuat data...</div>';
        document.getElementById('anggota-content').innerHTML = loadingHtml;
        
        // Get selected partisipan untuk maintain state
        const selectedPartisipan = Array.from(document.querySelectorAll('.partisipan-checkbox:checked')).map(cb => cb.value);
        
        const filters = {
            page: page,
            nama: filterNama.value,
            jenis_kelamin: filterJenisKelamin.value,
            dpd: filterDpd.value,
            dpc: Array.from(filterDpc.selectedOptions).map(option => option.value),
            upa: Array.from(filterUpa.selectedOptions).map(option => option.value),
            old_partisipan: selectedPartisipan
        };
        
        fetch('/api/anggota-paginated', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
            },
            body: JSON.stringify(filters)
        })
        .then(response => response.json())
        .then(data => {
            document.getElementById('anggota-content').innerHTML = data.html;
            document.getElementById('anggota-pagination').innerHTML = data.pagination;
            
            // Re-attach event listeners
            const newCheckboxes = document.querySelectorAll('.partisipan-checkbox');
            newCheckboxes.forEach(checkbox => {
                checkbox.addEventListener('change', updateSelectedPartisipan);
            });
            
            // Update cache
            allAnggotaItems = document.querySelectorAll('.anggota-item');
            filteredAnggotaItems = null;
            currentPage = page;
            isLoading = false;
        })
        .catch(error => {
            console.error('Error loading anggota:', error);
            document.getElementById('anggota-content').innerHTML = '<div class="text-center py-3 text-danger">Error memuat data</div>';
            isLoading = false;
        });
    }
    
    // Event delegation untuk pagination
    document.addEventListener('click', function(e) {
        if (e.target.matches('.pagination a')) {
            e.preventDefault();
            const url = new URL(e.target.href);
            const page = url.searchParams.get('page') || 1;
            loadAnggotaPage(page);
        }
    });
    
    // Optimasi form submission dengan loading state
    const form = document.getElementById('kegiatanForm');
    const submitBtn = document.getElementById('submitBtn');
    const btnText = submitBtn.querySelector('.btn-text');
    
    form.addEventListener('submit', function(e) {
        
        // Validate PIC selection
        const picId = document.getElementById('pic_anggota_id');
        const picSearch = document.getElementById('pic_search');
        
        if (picSearch.value.trim() && !picId.value) {
            e.preventDefault();
            alert('PIC yang dipilih tidak valid. Silakan pilih ulang PIC.');
            return false;
        }
        
        submitBtn.disabled = true;
        btnText.textContent = 'Menyimpan...';
        submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> <span class="btn-text">Menyimpan...</span>';
    });
});

    // Searchable PIC Dropdown
    const picSearch = document.getElementById('pic_search');
    const picId = document.getElementById('pic_anggota_id');
    const picDropdown = document.getElementById('pic_dropdown');
    
    if (!picSearch || !picId || !picDropdown) {
        console.error('PIC dropdown elements not found');
        return;
    }
    
    let allAnggotas = [];
    try {
        allAnggotas = @json($anggotas);
    } catch (e) {
        console.error('Error parsing anggotas data:', e);
        allAnggotas = [];
    }
    
    let filteredAnggotas = [];
    let selectedIndex = -1;
    
    // Initialize with selected value if exists
    const selectedAnggotaId = picId.value;
    if (selectedAnggotaId) {
        const selectedAnggota = allAnggotas.find(a => a.id == selectedAnggotaId);
        if (selectedAnggota) {
            picSearch.value = `${selectedAnggota.nomor_identitas_anggota} - ${selectedAnggota.nama_lengkap} - ${selectedAnggota.ref_jenjang?.jenjang || 'N/A'}`;
        }
    }
    
    function filterAnggotas(searchTerm) {
        if (searchTerm.length < 2) {
            filteredAnggotas = [];
            picDropdown.style.display = 'none';
            return;
        }
        
        filteredAnggotas = allAnggotas.filter(anggota => 
            anggota.nama_lengkap.toLowerCase().includes(searchTerm.toLowerCase()) ||
            anggota.nomor_identitas_anggota.toLowerCase().includes(searchTerm.toLowerCase()) ||
            (anggota.ref_jenjang?.jenjang || '').toLowerCase().includes(searchTerm.toLowerCase())
        );
        
        displayDropdown();
    }
    
    function displayDropdown() {
        if (filteredAnggotas.length === 0) {
            picDropdown.style.display = 'none';
            return;
        }
        
        picDropdown.innerHTML = '';
        filteredAnggotas.forEach((anggota, index) => {
            const option = document.createElement('div');
            option.className = 'dropdown-item';
            option.style.cursor = 'pointer';
            option.innerHTML = `
                <div class="d-flex justify-content-between">
                    <div>
                        <strong>${anggota.nomor_identitas_anggota}</strong> - ${anggota.nama_lengkap}
                    </div>
                    <small class="text-muted">${anggota.ref_jenjang?.jenjang || 'N/A'}</small>
                </div>
            `;
            
            option.addEventListener('click', function() {
                selectAnggota(anggota);
            });
            
            option.addEventListener('mouseenter', function() {
                // Remove active class from all options
                picDropdown.querySelectorAll('.dropdown-item').forEach(item => {
                    item.classList.remove('active');
                });
                // Add active class to current option
                this.classList.add('active');
                selectedIndex = index;
            });
            
            picDropdown.appendChild(option);
        });
        
        picDropdown.style.display = 'block';
        selectedIndex = -1;
    }
    
    function selectAnggota(anggota) {
        picSearch.value = `${anggota.nomor_identitas_anggota} - ${anggota.nama_lengkap} - ${anggota.ref_jenjang?.jenjang || 'N/A'}`;
        picId.value = anggota.id;
        picDropdown.style.display = 'none';
        filteredAnggotas = [];
    }
    
    picSearch.addEventListener('input', function() {
        filterAnggotas(this.value);
    });
    
    picSearch.addEventListener('keydown', function(e) {
        if (picDropdown.style.display === 'none') return;
        
        switch(e.key) {
            case 'ArrowDown':
                e.preventDefault();
                selectedIndex = Math.min(selectedIndex + 1, filteredAnggotas.length - 1);
                updateSelection();
                break;
            case 'ArrowUp':
                e.preventDefault();
                selectedIndex = Math.max(selectedIndex - 1, -1);
                updateSelection();
                break;
            case 'Enter':
                e.preventDefault();
                if (selectedIndex >= 0 && filteredAnggotas[selectedIndex]) {
                    selectAnggota(filteredAnggotas[selectedIndex]);
                }
                break;
            case 'Escape':
                picDropdown.style.display = 'none';
                selectedIndex = -1;
                break;
        }
    });
    
    function updateSelection() {
        const options = picDropdown.querySelectorAll('.dropdown-item');
        options.forEach((option, index) => {
            if (index === selectedIndex) {
                option.classList.add('active');
            } else {
                option.classList.remove('active');
            }
        });
    }
    
    // Close dropdown when clicking outside
    document.addEventListener('click', function(e) {
        if (!picSearch.contains(e.target) && !picDropdown.contains(e.target)) {
            picDropdown.style.display = 'none';
        }
    });
    
    // Initialize jenis lainnya toggle on page load
    toggleJenisLainnya();
    
    // Add event listener for jenis kegiatan dropdown
    const jenisSelect = document.getElementById('ref_jenis_kegiatan_id');
    if (jenisSelect) {
        jenisSelect.addEventListener('change', function() {
            toggleJenisLainnya();
        });
    } else {
        console.error('Jenis select element not found!');
    }
</script>
@endsection