@extends('layouts.app')

@section('title', 'Data Anggota - Sistem Informasi PKS')

@section('content')
<style>
/* Custom pagination styling untuk ukuran lebih kecil */
.pagination {
    font-size: 0.875rem;
    margin-bottom: 0;
}

.pagination .page-link {
    padding: 0.375rem 0.75rem;
    font-size: 0.875rem;
    border-radius: 0.375rem;
    margin: 0 0.125rem;
    border: 1px solid #dee2e6;
    color: #6c757d;
    text-decoration: none;
    transition: all 0.15s ease-in-out;
}

.pagination .page-link:hover {
    color: #0056b3;
    background-color: #e9ecef;
    border-color: #dee2e6;
}

.pagination .page-item.active .page-link {
    background-color: #007bff;
    border-color: #007bff;
    color: white;
}

.pagination .page-item.disabled .page-link {
    color: #6c757d;
    background-color: #fff;
    border-color: #dee2e6;
}

.pagination .page-item:first-child .page-link,
.pagination .page-item:last-child .page-link {
    border-radius: 0.375rem;
}

/* Mobile responsive table */
@media (max-width: 768px) {
    .table-responsive {
        border: none;
    }
    
    .table {
        font-size: 0.75rem;
    }
    
    .table th,
    .table td {
        padding: 0.375rem 0.25rem;
        white-space: nowrap;
    }
    
    .table th:first-child,
    .table td:first-child {
        position: sticky;
        left: 0;
        background: white;
        z-index: 10;
    }
    
    .table th:last-child,
    .table td:last-child {
        position: sticky;
        right: 0;
        background: white;
        z-index: 10;
    }
    
    /* Mobile form adjustments */
    .form-control,
    .form-select {
        font-size: 16px; /* Prevents zoom on iOS */
    }
    
    .btn {
        font-size: 0.8rem;
        padding: 0.4rem 0.8rem;
    }
    
    .badge {
        font-size: 0.7rem;
        padding: 0.2rem 0.4rem;
    }
    
    /* Mobile card adjustments */
    .card-header {
        padding: 0.75rem;
    }
    
    .card-body {
        padding: 0.75rem;
    }
    
    /* Mobile search form */
    .row.g-2 > .col-lg-2,
    .row.g-2 > .col-lg-3,
    .row.g-2 > .col-lg-9 {
        margin-bottom: 0.5rem;
    }
    
    /* Mobile table scroll indicator */
    .table-responsive::after {
        content: "← Scroll untuk melihat lebih banyak →";
        display: block;
        text-align: center;
        font-size: 0.75rem;
        color: #6c757d;
        padding: 0.5rem;
        background: #f8f9fa;
        border-top: 1px solid #dee2e6;
    }
}
</style>
<!-- Success/Error Messages -->
@if(session('success'))
    <div class="alert alert-success alert-dismissible fade show" role="alert">
        <i class="fas fa-check-circle me-2"></i>
        {{ session('success') }}
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
@endif

@if(session('error'))
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
        <i class="fas fa-exclamation-circle me-2"></i>
        {{ session('error') }}
        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
@endif

<!-- 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-users text-primary me-2"></i>
            @if(isset($pageTitle))
                {{ $pageTitle }}
            @else
                Data Anggota
            @endif
        </h1>
        <p class="text-muted mb-0 fs-6">
            <i class="fas fa-info-circle me-1"></i>
            @if(isset($filterStatus))
                Kelola data anggota {{ $filterStatus }} Partai Keadilan Sejahtera
            @else
                Kelola data anggota Partai Keadilan Sejahtera
            @endif
        </p>
    </div>
    <div class="d-flex flex-column flex-sm-row gap-2">
        <a href="{{ route('anggota.create') }}" class="btn btn-primary px-3" style="border-radius: 6px;">
            <i class="fas fa-user-plus me-1"></i>Tambah Anggota
        </a>
        <a href="{{ route('anggota.export', request()->query()) }}" class="btn px-3" style="border-radius: 6px; background-color: #217346; border-color: #217346; color: white; transition: all 0.3s ease;" onmouseover="this.style.backgroundColor='#1e5f3a'; this.style.borderColor='#1e5f3a';" onmouseout="this.style.backgroundColor='#217346'; this.style.borderColor='#217346';">
            <i class="fas fa-file-excel me-1"></i>Export Excel
        </a>
    </div>
</div>

<!-- Total Count Badge -->
<div class="d-flex justify-content-between align-items-center mb-3">
    <div class="d-flex gap-2 align-items-center">
        <span class="badge bg-primary fs-6 px-3 py-2">
            <i class="fas fa-users me-1"></i>
            @if(isset($filterStatus))
                Total {{ $filterStatus }}: {{ $anggota->total() }} anggota
            @else
                Total: {{ $anggota->total() }} anggota
            @endif
        </span>
        <span class="badge bg-secondary fs-6 px-3 py-2">
            <i class="fas fa-list me-1"></i>
            Menampilkan {{ ($anggota->currentPage() - 1) * $anggota->perPage() + 1 }} sampai {{ ($anggota->currentPage() - 1) * $anggota->perPage() + $anggota->count() }} dari {{ $anggota->total() }} data
        </span>
    </div>
</div>

<!-- Filter & Search -->
<div class="card shadow-sm mb-4 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-filter me-2"></i>Filter & Pencarian
            @if(isset($filterStatus))
                <span class="badge bg-light text-dark ms-2">
                    <i class="fas fa-check-circle me-1"></i>Status: {{ $filterStatus }}
                </span>
            @endif
        </h6>
    </div>
    <div class="card-body p-3">
        <form method="GET" action="{{ request()->routeIs('anggota.aktif') ? route('anggota.aktif') : (request()->routeIs('anggota.non-aktif') ? route('anggota.non-aktif') : route('anggota.index')) }}" id="filterForm">
            <!-- Row 1: Pencarian, Status, Jenis Kelamin, Jenjang -->
            <div class="row g-2 mb-3">
                <div class="col-lg-3 col-md-6">
                    <label class="form-label fw-semibold text-dark small">
                        <i class="fas fa-search me-1 text-primary"></i>Pencarian
                    </label>
                    <input type="text" class="form-control" name="search" 
                           value="{{ request('search') }}" 
                           placeholder="Nama, NIA, atau Email..."
                           style="border-radius: 6px;">
                </div>
                <div class="col-lg-3 col-md-6">
                    <label class="form-label fw-semibold text-dark small">
                        <i class="fas fa-user-check me-1 text-primary"></i>Status
                    </label>
                    <select class="form-select" name="status" style="border-radius: 6px;">
                        <option value="">Semua Status</option>
                        @foreach($statusList as $status)
                            <option value="{{ $status }}" {{ (request('status') == $status || (isset($filterStatus) && $filterStatus == $status)) ? 'selected' : '' }}>
                                {{ $status }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="col-lg-3 col-md-6">
                    <label class="form-label fw-semibold text-dark small">
                        <i class="fas fa-venus-mars me-1 text-primary"></i>Jenis Kelamin
                    </label>
                    <select class="form-select" name="jenis_kelamin" style="border-radius: 6px;">
                        <option value="">Semua Jenis Kelamin</option>
                        <option value="L" {{ request('jenis_kelamin') == 'L' ? 'selected' : '' }}>Laki-laki</option>
                        <option value="P" {{ request('jenis_kelamin') == 'P' ? 'selected' : '' }}>Perempuan</option>
                    </select>
                </div>
                <div class="col-lg-3 col-md-6">
                    <label class="form-label fw-semibold text-dark small">
                        <i class="fas fa-layer-group me-1 text-primary"></i>Jenjang
                    </label>
                    <select class="form-select" name="jenjang" style="border-radius: 6px;">
                        <option value="">Semua Jenjang</option>
                        @foreach($jenjangList as $jenjang)
                            <option value="{{ $jenjang->ref_jenjang_id }}" {{ request('jenjang') == $jenjang->ref_jenjang_id ? 'selected' : '' }}>
                                {{ $jenjang->jenjang }}
                            </option>
                        @endforeach
                    </select>
                </div>
            </div>
            
            <!-- Row 2: DPC, DPD, Provinsi, dan Action Buttons -->
            <div class="row g-2 align-items-end">
                <div class="col-lg-3 col-md-6">
                    <label class="form-label fw-semibold text-dark small">
                        <i class="fas fa-sitemap me-1 text-primary"></i>DPC
                    </label>
                    <select class="form-select" name="dpc" style="border-radius: 6px;">
                        <option value="">Semua DPC</option>
                        @foreach($dpcList as $dpc)
                            <option value="{{ $dpc->dpc_id }}" {{ request('dpc') == $dpc->dpc_id ? 'selected' : '' }}>
                                {{ $dpc->nama_dpc }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="col-lg-3 col-md-6">
                    <label class="form-label fw-semibold text-dark small">
                        <i class="fas fa-building me-1 text-primary"></i>DPD
                    </label>
                    <select class="form-select" name="dpd" style="border-radius: 6px;">
                        <option value="">Semua DPD</option>
                        @foreach($dpdList as $dpd)
                            <option value="{{ $dpd->dpd_id }}" {{ request('dpd') == $dpd->dpd_id ? 'selected' : '' }}>
                                {{ $dpd->nama_dpd }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="col-lg-3 col-md-6">
                    <label class="form-label fw-semibold text-dark small">
                        <i class="fas fa-map-marker-alt me-1 text-primary"></i>Provinsi
                    </label>
                    <select class="form-select" name="provinsi" style="border-radius: 6px;">
                        <option value="">Semua Provinsi</option>
                        @foreach($provinsiList as $provinsi)
                            <option value="{{ $provinsi }}" {{ request('provinsi') == $provinsi ? 'selected' : '' }}>
                                {{ $provinsi }}
                            </option>
                        @endforeach
                    </select>
                </div>
                <div class="col-lg-3 col-md-6">
                    <div class="d-flex gap-2 justify-content-end">
                        <button type="submit" class="btn btn-primary px-3" style="border-radius: 6px;">
                            <i class="fas fa-search me-1"></i>Cari Data
                        </button>
                        <a href="{{ route('anggota.index') }}" class="btn btn-outline-secondary px-3" style="border-radius: 6px;">
                            <i class="fas fa-undo me-1"></i>Reset
                        </a>
                    </div>
                </div>
            </div>
        </form>
    </div>
</div>


<!-- Data Table -->
<div class="card shadow-sm border-0">
    <div class="card-header bg-gradient-primary py-4">
        <h6 class="m-0 font-weight-bold text-white d-flex align-items-center">
            <i class="fas fa-list me-2"></i>Daftar Anggota
        </h6>
    </div>
    <div class="card-body p-0">
        @if($anggota->count() > 0)
            <div class="table-responsive">
                <table class="table table-hover mb-0" id="dataTable">
                    <thead class="table-light">
                        <tr>
                            <th class="text-center py-3" style="width: 60px;">
                                <i class="fas fa-hashtag me-1 text-primary"></i>No
                            </th>
                            <th class="py-3">
                                <i class="fas fa-id-card me-1 text-primary"></i>NIA
                            </th>
                            <th class="py-3">
                                <i class="fas fa-user me-1 text-primary"></i>Nama Lengkap
                            </th>
                            <th class="text-center py-3" style="width: 100px;">
                                <i class="fas fa-venus-mars me-1 text-primary"></i>JK
                            </th>
                            <th class="py-3">
                                <i class="fas fa-map-marker-alt me-1 text-primary"></i>Kota
                            </th>
                            <th class="text-center py-3" style="width: 100px;">
                                <i class="fas fa-mail-bulk me-1 text-primary"></i>Kode Pos
                            </th>
                            <th class="text-center py-3" style="width: 120px;">
                                <i class="fas fa-layer-group me-1 text-primary"></i>Jenjang
                            </th>
                            <th class="text-center py-3" style="width: 120px;">
                                <i class="fas fa-home me-1 text-primary"></i>UPA
                            </th>
                            <th class="text-center py-3" style="width: 100px;">
                                <i class="fas fa-info-circle me-1 text-primary"></i>Status
                            </th>
                            <th class="text-center py-3" style="width: 120px;">
                                <i class="fas fa-cogs me-1 text-primary"></i>Aksi
                            </th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach($anggota as $member)
                        @php
                            // Pre-calculate values untuk mengurangi conditional checks
                            $hasFoto = !empty($member->foto);
                            $jenisKelaminText = $member->jenis_kelamin == 'L' ? 'Laki-laki' : 'Perempuan';
                            $jenisKelaminClass = $member->jenis_kelamin == 'L' ? 'info' : 'danger';
                            $jenjang = $member->refJenjang->jenjang ?? 'N/A';
                            $upa = $member->upa->nama_upa ?? null;
                            $statusClass = match($member->status_keanggotaan) {
                                'Aktif' => 'success',
                                'Tidak Aktif' => 'warning',
                                default => 'danger'
                            };
                        @endphp
                        <tr class="align-middle">
                            <td class="text-center">
                                <span class="fw-bold text-muted fs-6">{{ ($anggota->currentPage() - 1) * $anggota->perPage() + $loop->iteration }}.</span>
                            </td>
                            <td>
                                <span class="text-dark fs-6">{{ $member->nomor_identitas_anggota }}</span>
                            </td>
                            <td>
                                <div class="d-flex align-items-center">
                                    @if($hasFoto)
                                        <img src="{{ Storage::url($member->foto) }}?v={{ $member->updated_at ? $member->updated_at->timestamp : time() }}" 
                                             class="rounded-circle me-3 shadow-sm" 
                                             style="width: 40px; height: 40px; object-fit: cover;"
                                             loading="lazy">
                                    @else
                                        <div class="rounded-circle me-3 d-flex align-items-center justify-content-center shadow-sm" 
                                             style="width: 40px; height: 40px; background: linear-gradient(135deg, #F0833A, #E67E22);">
                                            <i class="fas fa-user text-white"></i>
                                        </div>
                                    @endif
                                    <div>
                                        <div class="fw-bold text-primary fs-6">
                                            <a href="{{ $member->show_url }}" class="text-decoration-none text-primary">
                                                {{ $member->nama_lengkap }}
                                            </a>
                                        </div>
                                        <small class="text-muted">{{ $member->email }}</small>
                                    </div>
                                </div>
                            </td>
                            <td class="text-center">
                                <span class="text-dark">
                                    {{ $jenisKelaminText }}
                                </span>
                            </td>
                            <td>
                                <span class="text-dark">{{ $member->kota }}</span>
                            </td>
                            <td class="text-center">
                                <span class="text-muted">{{ $member->kode_pos ?? '-' }}</span>
                            </td>
                            <td class="text-center">
                                <span class="text-dark">
                                    {{ $jenjang }}
                                </span>
                            </td>
                            <td class="text-center">
                                @if($upa)
                                    <span class="text-dark">
                                        {{ $upa }}
                                    </span>
                                @else
                                    <span class="text-muted">-</span>
                                @endif
                            </td>
                            <td class="text-center">
                                <span class="text-dark">
                                    {{ $member->status_keanggotaan }}
                                </span>
                            </td>
                            <td class="text-center">
                                <div class="btn-group btn-group-sm">
                                    <a href="{{ $member->show_url }}" 
                                       class="btn btn-outline-info btn-sm px-3" 
                                       title="Detail"
                                       style="border-radius: 6px;">
                                        <i class="fas fa-eye"></i>
                                    </a>
                                    <a href="{{ $member->edit_url }}" 
                                       class="btn btn-outline-warning btn-sm px-3" 
                                       title="Edit"
                                       style="border-radius: 6px;">
                                        <i class="fas fa-edit"></i>
                                    </a>
                                    <button type="button" 
                                            class="btn btn-outline-danger btn-sm px-3" 
                                            title="Hapus"
                                            style="border-radius: 6px;"
                                            onclick="confirmDelete('{{ $member->url_slug }}', '{{ $member->nama_lengkap }}')">
                                        <i class="fas fa-trash"></i>
                                    </button>
                                </div>
                            </td>
                        </tr>
                        @endforeach
                    </tbody>
                </table>
            </div>

            <!-- Pagination -->
            <div class="d-flex justify-content-between align-items-center mt-4 px-3 py-3" style="background-color: #f8f9fa; border-top: 1px solid #dee2e6;">
                <div class="text-muted">
                    <i class="fas fa-info-circle me-1"></i>
                    Menampilkan {{ $anggota->firstItem() ?? 0 }} sampai {{ $anggota->lastItem() ?? 0 }} 
                    dari {{ $anggota->total() }} data
                </div>
                <div>
                    {{ $anggota->appends(request()->query())->links() }}
                </div>
            </div>
        @else
            <div class="text-center py-5">
                <i class="fas fa-users fa-5x text-muted mb-3"></i>
                <h5 class="text-muted">Belum Ada Data Anggota</h5>
                <p class="text-muted">Mulai dengan menambahkan anggota baru atau import dari Excel</p>
                <a href="{{ route('anggota.create') }}" class="btn btn-primary me-2">
                    <i class="fas fa-plus me-1"></i> Tambah Anggota
                </a>
                <button type="button" class="btn btn-outline-primary" data-bs-toggle="modal" data-bs-target="#importModal">
                    <i class="fas fa-upload me-1"></i> Import Excel
                </button>
            </div>
        @endif
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title">
                    <i class="fas fa-exclamation-triangle me-2"></i>Konfirmasi Hapus
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p>Apakah Anda yakin ingin menghapus anggota <strong id="memberName"></strong>?</p>
                <p class="text-danger"><i class="fas fa-warning me-1"></i>Tindakan ini tidak dapat dibatalkan!</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Batal</button>
                <form id="deleteForm" method="POST" class="d-inline">
                    @csrf
                    @method('DELETE')
                    <button type="submit" class="btn btn-danger">
                        <i class="fas fa-trash me-1"></i> Hapus
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>


@push('scripts')
<script>
function confirmDelete(slug, name) {
    document.getElementById('memberName').textContent = name;
    document.getElementById('deleteForm').action = `/anggota/${slug}`;
    new bootstrap.Modal(document.getElementById('deleteModal')).show();
}

// Initialize DataTable
$(document).ready(function() {
    $('#dataTable').DataTable({
        "paging": false,
        "searching": false,
        "ordering": true,
        "info": false,
        "responsive": true,
        "columnDefs": [
            { "orderable": false, "targets": -1 }
        ],
        "language": {
            "emptyTable": "Tidak ada data anggota",
            "zeroRecords": "Tidak ada data yang cocok dengan filter"
        }
    });
});

// Auto-submit form on filter change
$('select[name="status"], select[name="jenis_kelamin"], select[name="jenjang"], select[name="provinsi"], select[name="dpd"], select[name="dpc"]').change(function() {
    $(this).closest('form').submit();
});
</script>
@endpush

<!-- Enhanced Import Section di anggota/index.blade.php -->

<!-- Import Excel Section -->
<div class="card shadow mb-4">
    <div class="card-header py-3">
        <h6 class="m-0 font-weight-bold text-white">
            <i class="fas fa-upload me-2"></i>Import Data Excel
        </h6>
    </div>
    <div class="card-body">
        <!-- Import Form -->
        <form id="importForm" action="{{ route('anggota.import') }}" method="POST" enctype="multipart/form-data">
            @csrf
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="form-label">Pilih File Excel</label>
                    <input type="file" class="form-control" id="importFile" name="file" 
                           accept=".xlsx,.xls,.csv" required>
                    <div class="form-text">Format: Excel (.xlsx, .xls) atau CSV. Maksimal 10MB</div>
                </div>
                
                <div class="col-md-3 mb-3">
                    <label class="form-label">Mode Import</label>
                    <select class="form-select" name="action" id="importAction">
                        <option value="validate">Validasi Saja</option>
                        <option value="import">Import ke Database</option>
                    </select>
                </div>
                
                <div class="col-md-3 mb-3">
                    <label class="form-label">&nbsp;</label>
                    <div class="d-grid gap-2">
                        <button type="submit" class="btn btn-success" id="importBtn">
                            <i class="fas fa-upload me-1"></i> <span id="importBtnText">Validasi File</span>
                        </button>
                        <button type="button" class="btn btn-outline-secondary btn-sm" onclick="previewFile()">
                            <i class="fas fa-eye me-1"></i> Preview
                        </button>
                    </div>
                </div>
            </div>
        </form>

        <!-- Template Download -->
        <div class="row mt-3">
            <div class="col-12">
                <div class="alert alert-info d-flex align-items-center">
                    <i class="fas fa-info-circle me-2"></i>
                    <div>
                        Belum punya template? 
                        <a href="{{ route('anggota.export', ['type' => 'template']) }}" class="btn btn-sm btn-outline-primary ms-2">
                            <i class="fas fa-download me-1"></i> Download Template
                        </a>
                    </div>
                </div>
            </div>
        </div>

        <!-- Import Progress -->
        <div id="importProgress" class="mt-3" style="display: none;">
            <div class="progress">
                <div class="progress-bar progress-bar-striped progress-bar-animated" 
                     role="progressbar" style="width: 0%"></div>
            </div>
            <div class="text-center mt-2">
                <small class="text-muted">Memproses import...</small>
            </div>
        </div>

        <!-- Preview Results -->
        <div id="previewResults" class="mt-4" style="display: none;">
            <h6><i class="fas fa-eye me-2"></i>Preview Data</h6>
            <div class="table-responsive">
                <table class="table table-sm table-bordered" id="previewTable">
                    <thead id="previewHeader"></thead>
                    <tbody id="previewBody"></tbody>
                </table>
            </div>
            <div id="previewSummary" class="mt-2"></div>
        </div>
    </div>
</div>

<!-- Import Errors Modal -->
<div class="modal fade" id="importErrorsModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title">
                    <i class="fas fa-exclamation-triangle me-2"></i>Error Import
                </h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="importErrorsContent"></div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Tutup</button>
                <a href="{{ route('anggota.export', ['type' => 'template']) }}" class="btn btn-primary">
                    <i class="fas fa-download me-1"></i> Download Template
                </a>
            </div>
        </div>
    </div>
</div>

<script>
// Import functionality
document.getElementById('importAction').addEventListener('change', function() {
    const action = this.value;
    const btnText = document.getElementById('importBtnText');
    const btn = document.getElementById('importBtn');
    
    if (action === 'validate') {
        btnText.textContent = 'Validasi File';
        btn.className = 'btn btn-warning';
    } else {
        btnText.textContent = 'Import ke Database';
        btn.className = 'btn btn-success';
    }
});

document.getElementById('importForm').addEventListener('submit', function(e) {
    const fileInput = document.getElementById('importFile');
    
    if (!fileInput.files[0]) {
        e.preventDefault();
        alert('Pilih file terlebih dahulu!');
        return;
    }
    
    // Show progress
    document.getElementById('importProgress').style.display = 'block';
    document.getElementById('importBtn').disabled = true;
});

function previewFile() {
    const fileInput = document.getElementById('importFile');
    
    if (!fileInput.files[0]) {
        alert('Pilih file terlebih dahulu!');
        return;
    }
    
    const formData = new FormData();
    formData.append('file', fileInput.files[0]);
    
    fetch('{{ route("anggota.import.preview") }}', {
        method: 'POST',
        body: formData,
        headers: {
            'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content')
        }
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showPreviewResults(data.data);
        } else {
            alert('Error: ' + data.message);
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('Terjadi kesalahan saat preview file');
    });
}

function showPreviewResults(data) {
    const previewDiv = document.getElementById('previewResults');
    const headerRow = document.getElementById('previewHeader');
    const bodyRows = document.getElementById('previewBody');
    const summary = document.getElementById('previewSummary');
    
    // Clear previous results
    headerRow.innerHTML = '';
    bodyRows.innerHTML = '';
    
    // Create header
    const headerHtml = data.headers.map(header => `<th>${header}</th>`).join('');
    headerRow.innerHTML = headerHtml;
    
    // Create body rows (max 5 for preview)
    const bodyHtml = data.rows.slice(0, 5).map(row => {
        const cells = data.headers.map(header => `<td>${row[header] || '-'}</td>`).join('');
        return `<tr>${cells}</tr>`;
    }).join('');
    bodyRows.innerHTML = bodyHtml;
    
    // Show summary
    summary.innerHTML = `
        <div class="alert alert-info">
            <i class="fas fa-info-circle me-2"></i>
            <strong>Total baris:</strong> ${data.total_rows} | 
            <strong>Preview:</strong> ${Math.min(5, data.rows.length)} baris pertama
        </div>
    `;
    
    previewDiv.style.display = 'block';
}

// Show import errors if any
@if(session('import_errors'))
document.addEventListener('DOMContentLoaded', function() {
    const errors = @json(session('import_errors'));
    showImportErrors(errors);
});

function showImportErrors(errors) {
    const modal = new bootstrap.Modal(document.getElementById('importErrorsModal'));
    const content = document.getElementById('importErrorsContent');
    
    let html = '<div class="table-responsive"><table class="table table-sm">';
    html += '<thead><tr><th>Baris</th><th>Error</th><th>Data</th></tr></thead><tbody>';
    
    errors.forEach(error => {
        html += `<tr>
            <td>${error.row}</td>
            <td><span class="text-danger">${error.error}</span></td>
            <td><small>${JSON.stringify(error.data).slice(0, 100)}...</small></td>
        </tr>`;
    });
    
    html += '</tbody></table></div>';
    content.innerHTML = html;
    modal.show();
}
@endif

// Preview data if available
@if(session('preview_data'))
document.addEventListener('DOMContentLoaded', function() {
    const previewData = @json(session('preview_data'));
    if (previewData && previewData.length > 0) {
        const headers = Object.keys(previewData[0]);
        showPreviewResults({
            headers: headers,
            rows: previewData,
            total_rows: previewData.length
        });
    }
});
@endif

// Optimasi performa halaman data anggota
document.addEventListener('DOMContentLoaded', function() {
    // 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);
        };
    }
    
    // Optimasi search dengan debouncing
    const searchInput = document.querySelector('input[name="search"]');
    if (searchInput) {
        const debouncedSearch = debounce(function() {
            // Auto submit form saat search
            document.getElementById('filterForm').submit();
        }, 500);
        
        searchInput.addEventListener('input', debouncedSearch);
    }
    
    // Optimasi filter dengan debouncing
    const filterSelects = document.querySelectorAll('select[name="status"], select[name="jenis_kelamin"], select[name="jenjang"], select[name="provinsi"], select[name="dpd"], select[name="dpc"]');
    filterSelects.forEach(select => {
        const debouncedFilter = debounce(function() {
            document.getElementById('filterForm').submit();
        }, 300);
        
        select.addEventListener('change', debouncedFilter);
    });
    
    // Loading state untuk form submission
    const filterForm = document.getElementById('filterForm');
    if (filterForm) {
        filterForm.addEventListener('submit', function() {
            const submitBtn = this.querySelector('button[type="submit"]');
            if (submitBtn) {
                submitBtn.disabled = true;
                submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Memuat...';
            }
        });
    }
    
    // Intersection Observer untuk lazy loading gambar
    if ('IntersectionObserver' in window) {
        const imageObserver = new IntersectionObserver((entries, observer) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    const img = entry.target;
                    if (img.dataset.src) {
                        img.src = img.dataset.src;
                        img.removeAttribute('data-src');
                        observer.unobserve(img);
                    }
                }
            });
        });
        
        // Observe semua gambar dengan data-src
        document.querySelectorAll('img[data-src]').forEach(img => {
            imageObserver.observe(img);
        });
    }
    
    // Preload halaman berikutnya untuk pagination yang lebih cepat
    const nextPageLink = document.querySelector('.pagination .page-link[rel="next"]');
    if (nextPageLink) {
        const link = document.createElement('link');
        link.rel = 'prefetch';
        link.href = nextPageLink.href;
        document.head.appendChild(link);
    }
});
</script>

@endsection