@extends('layouts.test')

@section('style')
<style>
/* ============================================
   FRONT DASHBOARD - MODERN REDESIGN
   ============================================ */

/* Loader Overlay - Modern Style */
#loaderOverlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(135deg, rgba(26, 26, 46, 0.97) 0%, rgba(22, 33, 62, 0.97) 100%);
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    z-index: 9999;
    backdrop-filter: blur(10px);
}

#loaderOverlay.hidden {
    display: none !important;
}

.loader-spinner {
    width: 60px;
    height: 60px;
    border: 4px solid rgba(255, 255, 255, 0.1);
    border-top-color: #10b981;
    border-radius: 50%;
    animation: spin 0.8s linear infinite;
}

@keyframes spin {
    to { transform: rotate(360deg); }
}

.loader-title {
    margin-top: 25px;
    font-size: 18px;
    font-weight: 600;
    color: #fff;
}

.loader-subtitle {
    margin-top: 8px;
    font-size: 14px;
    color: rgba(255, 255, 255, 0.6);
}

.loader-progress-container {
    margin-top: 20px;
    width: 250px;
    height: 6px;
    background: rgba(255, 255, 255, 0.1);
    border-radius: 10px;
    overflow: hidden;
}

.loader-progress-bar {
    height: 100%;
    background: linear-gradient(90deg, #10b981, #059669);
    width: 0%;
    transition: width 0.3s ease;
    border-radius: 10px;
}

/* Header Card */
.header-card {
    background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
    border-radius: 16px;
    padding: 25px 30px;
    margin-bottom: 20px;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.header-card .page-title {
    font-size: 28px;
    font-weight: 700;
    color: #fff;
    margin: 0 0 15px 0;
}

.header-stats {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;
}

.stat-item {
    display: flex;
    align-items: center;
    gap: 8px;
}

.stat-item .stat-label {
    font-size: 13px;
    color: rgba(255, 255, 255, 0.6);
}

.stat-item .stat-value {
    font-size: 15px;
    font-weight: 700;
    color: #fff;
    background: rgba(255, 255, 255, 0.1);
    padding: 4px 12px;
    border-radius: 20px;
}

.stat-item .stat-value.pending {
    background: rgba(245, 158, 11, 0.2);
    color: #fbbf24;
}

.stat-item .stat-value.success {
    background: rgba(16, 185, 129, 0.2);
    color: #10b981;
}

/* Filter Bar */
.filter-bar {
    background: #fff;
    border-radius: 12px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
    border: 1px solid #e2e8f0;
}

.filter-bar-title {
    font-size: 14px;
    font-weight: 600;
    color: #1e293b;
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    gap: 8px;
}

.filter-bar-title i {
    color: #10b981;
}

.filter-row {
    display: flex;
    flex-wrap: wrap;
    gap: 15px;
    align-items: flex-end;
}

.filter-group {
    display: flex;
    flex-direction: column;
    gap: 6px;
    min-width: 150px;
    flex: 1;
}

.filter-group label {
    font-size: 11px;
    font-weight: 600;
    color: #64748b;
    text-transform: uppercase;
    letter-spacing: 0.5px;
}

.filter-group select,
.filter-group input {
    padding: 10px 12px;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    font-size: 13px;
    background: #f8fafc;
    color: #334155;
    transition: all 0.2s ease;
}

.filter-group select:focus,
.filter-group input:focus {
    border-color: #10b981;
    outline: none;
    box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.1);
    background: #fff;
}

.filter-buttons {
    display: flex;
    gap: 10px;
}

.btn-filter {
    padding: 10px 18px;
    border-radius: 8px;
    font-size: 13px;
    font-weight: 600;
    display: inline-flex;
    align-items: center;
    gap: 6px;
    cursor: pointer;
    transition: all 0.2s ease;
    border: none;
}

.btn-filter.primary {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    color: #fff;
}

.btn-filter.primary:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
}

.btn-filter.secondary {
    background: #f1f5f9;
    color: #64748b;
    border: 1px solid #e2e8f0;
}

.btn-filter.secondary:hover {
    background: #e2e8f0;
}

/* Action Bar */
.action-bar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;
    gap: 15px;
    margin-bottom: 20px;
}

.export-btn {
    display: inline-flex;
    align-items: center;
    gap: 10px;
    padding: 12px 24px;
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    color: #fff;
    border: none;
    border-radius: 12px;
    font-size: 14px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s ease;
    box-shadow: 0 4px 15px rgba(16, 185, 129, 0.3);
}

.export-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(16, 185, 129, 0.4);
}

.export-btn i {
    font-size: 18px;
}

.load-progress {
    display: none;
    align-items: center;
    gap: 10px;
    padding: 10px 20px;
    background: #fff;
    border-radius: 10px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
}

.load-progress .progress-icon {
    width: 20px;
    height: 20px;
    border: 2px solid #e2e8f0;
    border-top-color: #10b981;
    border-radius: 50%;
    animation: spin 0.8s linear infinite;
}
.load-progress .progress-status {
    position: relative;
    width: 20px;
    height: 20px;
}

.load-progress .progress-spinner {
    width: 20px;
    height: 20px;
    border: 2px solid #e2e8f0;
    border-top-color: #10b981;
    border-radius: 50%;
    animation: spin 0.8s linear infinite;
}

.load-progress .progress-check {
    position: absolute;
    top: 0;
    left: 0;
    width: 20px;
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
}

.load-progress .progress-check.hidden {
    display: none;
}

.load-progress .progress-spinner.hidden {
    display: none;
}

@keyframes spin {
    to { transform: rotate(360deg); }
}

.load-progress .progress-text {
    font-size: 13px;
    color: #64748b;
    font-weight: 500;
}

/* Table Card */
.table-card {
    background: #fff;
    border-radius: 16px;
    box-shadow: 0 2px 20px rgba(0, 0, 0, 0.06);
    overflow: hidden;
}

.table-card .card-body {
    padding: 0;
}

/* Table Styles */
.table-responsive {
    overflow-x: auto;
}

#myTable {
    width: 100%;
    border-collapse: collapse;
}

#myTable thead th {
    background: #f8fafc;
    border-bottom: 2px solid #e2e8f0;
    color: #475569;
    font-weight: 600;
    font-size: 11px;
    text-transform: uppercase;
    letter-spacing: 0.5px;
    padding: 16px 12px;
    white-space: nowrap;
    position: sticky;
    top: 0;
    z-index: 10;
}

#myTable tbody td {
    padding: 14px 12px;
    vertical-align: middle;
    border-bottom: 1px solid #f1f5f9;
    color: #334155;
    font-size: 13px;
}

#myTable tbody tr {
    transition: background-color 0.15s ease;
}

#myTable tbody tr:hover {
    background-color: #f8fafc;
}

#myTable tbody tr.table-success {
    background-color: rgba(16, 185, 129, 0.08);
}

/* Reference Cell */
.ref-cell {
    font-weight: 700;
    color: #1e293b;
}

/* Badges */
.badge {
    display: inline-block;
    padding: 5px 10px;
    border-radius: 6px;
    font-size: 11px;
    font-weight: 600;
}

.badge-type {
    background: #e0f2fe;
    color: #0369a1;
}

.badge-mode {
    background: #fef3c7;
    color: #b45309;
}

.badge-amount {
    background: #f1f5f9;
    color: #334155;
}

.badge-step {
    background: #ede9fe;
    color: #6d28d9;
}

.badge-time {
    font-weight: 700;
    padding: 6px 10px;
}

.badge-time.positive {
    background: #dcfce7;
    color: #15803d;
}

.badge-time.negative {
    background: #fee2e2;
    color: #b91c1c;
}

/* Document Links */
.action-links {
    display: flex;
    gap: 6px;
    flex-wrap: wrap;
}

.doc-link {
    padding: 5px 10px;
    border-radius: 6px;
    font-size: 11px;
    font-weight: 600;
    text-decoration: none;
    transition: all 0.2s ease;
}

.doc-link.devis {
    background: #dbeafe;
    color: #1d4ed8;
}

.doc-link.devis:hover {
    background: #bfdbfe;
}

.doc-link.rapport {
    background: #dcfce7;
    color: #15803d;
}

.doc-link.rapport:hover {
    background: #bbf7d0;
}

.doc-link.facture {
    background: #fef3c7;
    color: #b45309;
}

.doc-link.facture:hover {
    background: #fde68a;
}

/* View Button */
.view-btn {
    display: inline-flex;
    align-items: center;
    justify-content: center;
    width: 36px;
    height: 36px;
    background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%);
    color: #fff;
    border-radius: 8px;
    transition: all 0.2s ease;
}

.view-btn:hover {
    transform: scale(1.1);
    box-shadow: 0 4px 12px rgba(59, 130, 246, 0.4);
    color: #fff;
}

.view-btn i {
    font-size: 16px;
}

/* DataTables Overrides */
.dataTables_wrapper .dataTables_length select {
    padding: 6px 30px 6px 12px;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    background: #f8fafc;
}

.dataTables_wrapper .dataTables_filter input {
    padding: 8px 14px;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    margin-left: 8px;
}

.dataTables_wrapper .dataTables_paginate .paginate_button {
    padding: 8px 14px;
    border-radius: 8px;
    margin: 0 2px;
}

.dataTables_wrapper .dataTables_paginate .paginate_button.current {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%) !important;
    color: #fff !important;
    border: none !important;
}

.dataTables_wrapper .dataTables_info {
    color: #64748b;
    font-size: 13px;
}

/* Column Filters */
.column-filter-row th {
    padding: 8px 12px !important;
    background: #f1f5f9 !important;
}

.column-filter {
    width: 100%;
    padding: 6px 8px;
    border: 1px solid #e2e8f0;
    border-radius: 6px;
    font-size: 11px;
    background: #fff;
}

.column-filter:focus {
    border-color: #10b981;
    outline: none;
}

/* Responsive */
@media (max-width: 992px) {
    .filter-row {
        flex-direction: column;
    }
    
    .filter-group {
        width: 100%;
    }
}

@media (max-width: 768px) {
    .header-card {
        padding: 20px;
    }
    
    .header-card .page-title {
        font-size: 22px;
    }
    
    .action-bar {
        flex-direction: column;
        align-items: stretch;
    }
}
</style>
@endsection

@section('content')

    <!-- Loader Overlay -->
    <div id="loaderOverlay">
        <div class="loader-spinner"></div>
        <div class="loader-title">Chargement des dossiers</div>
        <div class="loader-subtitle" id="loaderSubtext">Veuillez patienter...</div>
        <div class="loader-progress-container">
            <div class="loader-progress-bar" id="loaderProgressBar"></div>
        </div>
    </div>

    <!-- Header Card -->
    <div class="header-card">
        <h1 class="page-title" id="title">Tableau de bord</h1>
        <div class="header-stats">
            <div class="stat-item">
                <span class="stat-label">Total dossiers:</span>
                <span class="stat-value success" id="statTotal">0</span>
            </div>
            <div class="stat-item">
                <span class="stat-label">Chargés:</span>
                <span class="stat-value" id="statLoaded">0</span>
            </div>
            <div class="stat-item" id="statPending" style="display: none;">
                <span class="stat-label">En attente:</span>
                <span class="stat-value pending" id="statPendingValue">0</span>
            </div>
        </div>
    </div>

    <!-- Filter Bar -->
    <div class="filter-bar">
        <div class="filter-bar-title">
            <i class="uil uil-filter"></i> Filtres Avancés
        </div>
        <div class="filter-row">
            <div class="filter-group">
                <label for="filterCompany">Compagnie</label>
                <select id="filterCompany">
                    <option value="">-- Toutes --</option>
                </select>
            </div>
            <div class="filter-group">
                <label for="filterType">Type Expertise</label>
                <select id="filterType">
                    <option value="">-- Tous --</option>
                </select>
            </div>
            <div class="filter-group">
                <label for="filterMode">Mode</label>
                <select id="filterMode">
                    <option value="">-- Tous --</option>
                </select>
            </div>
            <div class="filter-group">
                <label for="filterStep">Étape</label>
                <select id="filterStep">
                    <option value="">-- Toutes --</option>
                </select>
            </div>
            <div class="filter-group">
                <label for="filterDelai">Délai</label>
                <select id="filterDelai">
                    <option value="">-- Tous --</option>
                    <option value="negative">Négatif (retard)</option>
                    <option value="positive">Positif (dans les temps)</option>
                    <option value="critical">Critique (< 24H)</option>
                </select>
            </div>
            <div class="filter-group" style="flex: 0 0 auto;">
                <label>&nbsp;</label>
                <div class="filter-buttons">
                    <button type="button" class="btn-filter primary" onclick="applyFilters()">
                        <i class="uil uil-check"></i> Appliquer
                    </button>
                    <button type="button" class="btn-filter secondary" onclick="resetFilters()">
                        <i class="uil uil-redo"></i> Reset
                    </button>
                </div>
            </div>
        </div>
    </div>

    <!-- Action Bar -->
    <div class="action-bar">
        <button class="export-btn" onclick="exportToExcel()">
            <i class="uil uil-file-export"></i>
            Exporter Excel
        </button>
        
        <div class="load-progress" id="loadProgress">
            <div class="progress-status">
                <div class="progress-spinner"></div>
                <div class="progress-check hidden">
                    <i class="uil uil-check" style="color: #10b981; font-size: 16px;"></i>
                </div>
            </div>
            <span class="progress-text" id="progressText">Chargement...</span>
        </div>
    </div>

    <!-- Table Card -->
    <div class="table-card">
        <div class="card-body">
            <div class="table-responsive">
                <table id="myTable" class="display">
                    <thead>
                        <tr>
                            <th>Action</th>
                            <th>Référence</th>
                            <th>Compagnie</th>
                            <th>Assuré</th>
                            <th>Matricule</th>
                            <th>N° Sinistre</th>
                            <th>Type</th>
                            <th>Mode</th>
                            <th>Mt. Devis</th>
                            <th>Mt. Facture</th>
                            <th>Etape</th>
                            <th>Délai</th>
                            <th>Status</th>
                            <th>Documents</th>
                        </tr>
                    </thead>
                    <tbody id="tableBody">
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Hidden Inputs -->
    <input type="hidden" id="role" value="{{ Auth::user()->role_id }}">
    <input type="hidden" id="currentFilter" value="default">

@endsection

@section('script')
<!-- Add SheetJS from CDN -->
<script src="https://cdn.sheetjs.com/xlsx-0.20.0/package/dist/xlsx.full.min.js"></script>
<script>
(function() {
    "use strict";

    // Configuration - OPTIMIZED FOR FAST FIRST LOAD
    var CONFIG = {
        INITIAL_LOAD: 100,  // Only 100 records on first load for speed
        BATCH_SIZE: 500,    // Load more in background when needed
        API_URL: "/api/dossiers/data",
        EXPORT_URL: "/export/dossiers",
        CSRF_TOKEN: document.querySelector("meta[name=csrf-token]") ? document.querySelector("meta[name=csrf-token]").getAttribute("content") : ""
    };

    // State
    var State = {
        currentFilter: "default",
        allData: [],
        totalRecords: 0,
        isLoading: false,
        isFullyLoaded: false,
        dataTable: null,
        filterValues: {
            company: "",
            type: "",
            mode: "",
            step: "",
            delai: ""
        }
    };

    // Filter mapping
    var FILTER_MAP = {
        "/Expertiser": "expertiser",
        "/Expertise/encours": "enexp",
        "/Reporter": "areport",
        "/Devis/Carence": "carencedevis",
        "/Facture/Carence": "carencefacture",
        "/Carence/Rapport": "carencerapport",
        "/Devis/Retraiter": "devisretraiter",
        "/Facture/Retraiter": "factureretraiter",
        "/Retraiter/Rapport": "rapportaretraiter",
        "/Devis/Traitement": "traitdevis",
        "/Facture/Traitement": "traitfacture",
        "/Signer/Rapport": "rapportasigner",
        "/Instance/Rapport": "traitrapport",
        "/Devis/Envoyer": "senddevis",
        "/Facture/Envoyer": "sendfacture",
        "/Envoyer/Rapport": "sendrapport",
        "/Devis/Avis": "avisdevis",
        "/Facture/Avis": "avisfacture",
        "/Devis/Deuxieme": "deuxdevis",
        "/Facture/Deuxieme": "deuxfacture",
        "/Deuxieme/Rapport": "deuxrapport",
        "/Douteux": "douteux",
        "/Tribunale": "tribunale",
        "/Warning": "warning",
        "/Signer/Document": "docasigner",
        "/Signe/Document": "docsigner",
        "/Rapide": "rapide",
        "/Base": "basedoc",
        "/Facturation": "facturation",
        "/Devis/Trait": "devisentraitement",
        "/Facture/Trait": "factureentraitement",
        "/Devis/Photo": "attdevisav",
        "/Facture/Photo": "attfactureap",
        "/Expertise/Apres": "attexpap",
        "/Devis/Controler": "controldevis"
    };

    // DataTable language config
    var DT_LANGUAGE = {
        lengthMenu: "Afficher _MENU_ entrées",
        zeroRecords: "Aucun dossier trouvé",
        info: "Affichage de _START_ à _END_ sur _TOTAL_ entrées",
        infoEmpty: "Aucune entrée disponible",
        infoFiltered: "(filtré de _MAX_ entrées totales)",
        search: "Rechercher:",
        paginate: {
            first: "Premier",
            last: "Dernier",
            next: "Suivant",
            previous: "Précédent"
        }
    };

    // UI Functions
    function showLoader() {
        document.getElementById("loaderOverlay").classList.remove("hidden");
    }

    function hideLoader() {
        document.getElementById("loaderOverlay").classList.add("hidden");
    }

    function updateLoaderProgress(percent, text) {
        document.getElementById("loaderProgressBar").style.width = percent + "%";
        if (text) document.getElementById("loaderSubtext").textContent = text;
    }

    function updateStats(total, loaded) {
        document.getElementById("statTotal").textContent = total.toLocaleString('fr-FR');
        document.getElementById("statLoaded").textContent = loaded.toLocaleString('fr-FR');
        var pending = total - loaded;
        if (pending > 0) {
            document.getElementById("statPending").style.display = "flex";
            document.getElementById("statPendingValue").textContent = pending.toLocaleString('fr-FR');
        } else {
            document.getElementById("statPending").style.display = "none";
        }
    }

    // Populate filter dropdowns from data
    function populateFilters() {
        var companies = {};
        var types = {};
        var modes = {};
        var steps = {};

        State.allData.forEach(function(row) {
            if (row.company) companies[row.company] = true;
            if (row.type_expertise) types[row.type_expertise] = true;
            if (row.mode) modes[row.mode] = true;
            if (row.step) steps[row.step] = true;
        });

        populateSelect("filterCompany", Object.keys(companies).sort());
        populateSelect("filterType", Object.keys(types).sort());
        populateSelect("filterMode", Object.keys(modes).sort());
        populateSelect("filterStep", Object.keys(steps).sort());
    }

    function populateSelect(id, options) {
        var select = document.getElementById(id);
        var currentValue = select.value;
        
        // Keep first option (-- All --)
        while (select.options.length > 1) {
            select.remove(1);
        }
        
        options.forEach(function(opt) {
            var option = document.createElement("option");
            option.value = opt;
            option.textContent = opt;
            select.appendChild(option);
        });
        
        // Restore previous value if exists
        if (currentValue) {
            select.value = currentValue;
        }
    }

    // Apply filters
    window.applyFilters = function() {
        State.filterValues.company = document.getElementById("filterCompany").value;
        State.filterValues.type = document.getElementById("filterType").value;
        State.filterValues.mode = document.getElementById("filterMode").value;
        State.filterValues.step = document.getElementById("filterStep").value;
        State.filterValues.delai = document.getElementById("filterDelai").value;

        if (State.dataTable) {
            State.dataTable.draw();
        }
    };

    // Reset filters
    window.resetFilters = function() {
        document.getElementById("filterCompany").value = "";
        document.getElementById("filterType").value = "";
        document.getElementById("filterMode").value = "";
        document.getElementById("filterStep").value = "";
        document.getElementById("filterDelai").value = "";
        
        State.filterValues = {
            company: "",
            type: "",
            mode: "",
            step: "",
            delai: ""
        };

        if (State.dataTable) {
            State.dataTable.draw();
        }
    };

    // Custom filter function for DataTable
    $.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {
        // Only apply to our table
        if (settings.nTable.id !== 'myTable') return true;

        var row = State.allData[dataIndex];
        if (!row) return true;

        // Company filter
        if (State.filterValues.company && row.company !== State.filterValues.company) {
            return false;
        }

        // Type filter
        if (State.filterValues.type && row.type_expertise !== State.filterValues.type) {
            return false;
        }

        // Mode filter
        if (State.filterValues.mode && row.mode !== State.filterValues.mode) {
            return false;
        }

        // Step filter
        if (State.filterValues.step && row.step !== State.filterValues.step) {
            return false;
        }

        // Delai filter
        if (State.filterValues.delai) {
            var timeleft = parseFloat(row.timeleft) || 0;
            switch (State.filterValues.delai) {
                case "negative":
                    if (timeleft >= 0) return false;
                    break;
                case "positive":
                    if (timeleft < 0) return false;
                    break;
                case "critical":
                    if (timeleft < 0 || timeleft > 24) return false;
                    break;
            }
        }

        return true;
    });

    // Format table row - REDESIGNED
    function formatRow(v) {
        var html = "";
        
        // Row class for updated items
        if (v.is_updated == 1) {
            html += "<tr class=\"table-success\">";
        } else {
            html += "<tr>";
        }
        
        // Action - View Button (FIRST)
        html += "<td>";
        html += "<a href=\"Dossier/" + v.id + "\" class=\"view-btn\" title=\"Voir le dossier\">";
        html += "<i class=\"uil uil-eye\"></i>";
        html += "</a>";
        html += "</td>";
        
        // Reference
        html += "<td class=\"ref-cell\">" + (v.ref || "-") + "</td>";
        
        // Company
        html += "<td>" + (v.company || "-") + "</td>";
        
        // Insured Name
        html += "<td><strong>" + (v.insured_name || "-") + "</strong></td>";
        
        // Matricule
        html += "<td>" + (v.matricule || "-") + "</td>";
        
        // N° Sinistre
        html += "<td>" + (v.numero_sinistre || "-") + "</td>";
        
        // Type
        html += "<td><span class=\"badge badge-type\">" + (v.type_expertise || "-") + "</span></td>";
        
        // Mode
        html += "<td><span class=\"badge badge-mode\">" + (v.mode || "-") + "</span></td>";
        
        // Montant Devis
        html += "<td><span class=\"badge badge-amount\">" + (v.montant_devis || "-") + "</span></td>";
        
        // Montant Facture
        html += "<td><span class=\"badge badge-amount\">" + (v.montant_facture || "-") + "</span></td>";
        
        // Step
        html += "<td><span class=\"badge badge-step\">" + (v.step || "-") + "</span></td>";
        
        // Time Left - store numeric value for sorting
        var timeleftNum = parseFloat(v.timeleft) || 0;
        if (timeleftNum > 0) {
            html += "<td data-order=\"" + timeleftNum + "\"><span class=\"badge badge-time positive\">" + v.timeleft + "H</span></td>";
        } else {
            html += "<td data-order=\"" + timeleftNum + "\"><span class=\"badge badge-time negative\">" + v.timeleft + "H</span></td>";
        }
        
        // Status
        html += "<td><span class=\"badge bg-" + (v.status_color || "secondary") + "\">" + (v.status || "-") + "</span></td>";
        
        // Document Links (combined into one cell)
        html += "<td>";
        html += "<div class=\"action-links\">";
        html += "<a href=\"Devis/Dossier/" + v.id + "\" class=\"doc-link devis\">Devis</a>";
        html += "<a href=\"Rapport/" + v.id + "\" class=\"doc-link rapport\">Rapport</a>";
        html += "<a href=\"Dossier/" + v.id + "/Facture\" class=\"doc-link facture\">Facture</a>";
        html += "</div>";
        html += "</td>";
        
        html += "</tr>";
        return html;
    }

    // Safely destroy DataTable
    function destroyDataTable() {
        try {
            if ($.fn.DataTable && $.fn.DataTable.isDataTable("#myTable")) {
                $("#myTable").DataTable().destroy();
            }
        } catch (e) {
            console.log("DataTable destroy warning:", e);
        }
        State.dataTable = null;
    }

    // Initialize DataTable with events
    function initDataTable() {
        State.dataTable = $("#myTable").DataTable({
            paging: true,
            pageLength: 25,
            lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "Tout"]],
            ordering: true,
            // DEFAULT SORT: Délai column (index 11), ascending (oldest/most negative first)
            order: [[11, "asc"]],
            searching: true,
            info: true,
            autoWidth: false,
            language: DT_LANGUAGE,
            dom: '<"top"lf>rt<"bottom"ip><"clear">',
            columnDefs: [
                // Action column - no sorting, first column
                {
                    targets: 0,
                    orderable: false
                },
                // Délai column (now index 11) - numeric sorting
                {
                    targets: 11,
                    type: 'num',
                    orderSequence: ['asc', 'desc']
                },
                // Disable sorting on Documents column (now index 13)
                {
                    targets: 13,
                    orderable: false
                }
            ]
        });

        // Bind events
        State.dataTable.on("page.dt", function() {
            if (!State.isFullyLoaded && State.allData.length < State.totalRecords) {
                loadRemaining();
            }
        });

        State.dataTable.on("length.dt", function(e, settings, len) {
            if (!State.isFullyLoaded && State.allData.length < State.totalRecords) {
                if (len > State.allData.length || len === -1) {
                    loadRemaining();
                }
            }
        });
    }

    // Build table body HTML
    function buildTableBody() {
        var tbody = document.getElementById("tableBody");
        var html = "";
        for (var i = 0; i < State.allData.length; i++) {
            html += formatRow(State.allData[i]);
        }
        tbody.innerHTML = html;
    }

    // Fetch data from API
    function fetchBatch(filter, start, length, callback) {
        var xhr = new XMLHttpRequest();
        var params = "filter=" + encodeURIComponent(filter) + "&start=" + start + "&length=" + length + "&draw=1";
        xhr.open("GET", CONFIG.API_URL + "?" + params, true);
        xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    try {
                        callback(null, JSON.parse(xhr.responseText));
                    } catch (e) {
                        callback(e, null);
                    }
                } else {
                    callback(new Error("Network error: " + xhr.status), null);
                }
            }
        };
        xhr.send();
    }

    // Load initial data - OPTIMIZED FOR SPEED
    function loadInitial(filter) {
        // Reset progress bar to loading state
        var spinner = document.querySelector('.progress-spinner');
        var check = document.querySelector('.progress-check');
        if (spinner && check) {
            spinner.classList.remove('hidden');
            check.classList.add('hidden');
            document.getElementById("progressText").textContent = "Chargement...";
            document.getElementById("loadProgress").style.display = "flex";
        }
        State.isLoading = true;
        State.isFullyLoaded = false;
        State.allData = [];
        State.currentFilter = filter;

        showLoader();
        updateLoaderProgress(30, "Chargement rapide...");

        // Request only 100 records for fast first display
        fetchBatch(filter, 0, CONFIG.INITIAL_LOAD, function(err, result) {
            if (err) {
                console.error("Error loading data:", err);
                hideLoader();
                alert("Erreur lors du chargement des données");
                State.isLoading = false;
                return;
            }

            State.allData = result.data || [];
            State.totalRecords = result.recordsTotal || 0;

            updateLoaderProgress(90, "Affichage...");
            
            renderTable();
            updateStats(State.totalRecords, State.allData.length);
            populateFilters();

            // Check if we have all data or need to load more
            if (State.allData.length >= State.totalRecords) {
                State.isFullyLoaded = true;
                
                // Show success state briefly
                var spinner = document.querySelector('.progress-spinner');
                var check = document.querySelector('.progress-check');
                var text = document.getElementById("progressText");
                
                spinner.classList.add('hidden');
                check.classList.remove('hidden');
                text.textContent = "Chargement terminé ! (" + 
                    State.allData.length.toLocaleString('fr-FR') + " dossiers)";
                
                // Auto-hide after 1.5 seconds
                setTimeout(function() {
                    document.getElementById("loadProgress").style.display = "none";
                }, 1500);
            } else {
                // Show load more indicator
                document.getElementById("loadProgress").style.display = "flex";
                var remaining = State.totalRecords - State.allData.length;
                document.getElementById("progressText").textContent = remaining.toLocaleString('fr-FR') + " dossiers restants - Naviguez pour charger plus";
            }

            updateLoaderProgress(100, "Terminé!");
            setTimeout(hideLoader, 200); // Faster hide
            State.isLoading = false;
        });
    }

    // Load remaining data in background
    function loadRemaining() {
        if (State.isFullyLoaded || State.isLoading) return;
        if (State.allData.length >= State.totalRecords) {
            State.isFullyLoaded = true;
            return;
        }

        State.isLoading = true;
        document.getElementById("loadProgress").style.display = "flex";

        function loadNextBatch() {
            if (State.allData.length >= State.totalRecords) {
                State.isFullyLoaded = true;
                State.isLoading = false;
                document.getElementById("statPending").style.display = "none";
                // Show checkmark & final message
                document.querySelector('.progress-spinner').classList.add('hidden');
                document.querySelector('.progress-check').classList.remove('hidden');
                document.getElementById("progressText").textContent = "Chargement terminé ! (" + 
                    State.allData.length.toLocaleString('fr-FR') + " dossiers)";
                refreshTable();
                populateFilters();
                return;
            }

            var pct = Math.round((State.allData.length / State.totalRecords) * 100);
            document.getElementById("progressText").textContent = State.allData.length.toLocaleString('fr-FR') + " / " + State.totalRecords.toLocaleString('fr-FR') + " (" + pct + "%)";

            fetchBatch(State.currentFilter, State.allData.length, CONFIG.BATCH_SIZE, function(err, result) {
                if (err || !result.data || result.data.length === 0) {
                    State.isFullyLoaded = true;
                    // Show checkmark & final message
                    document.querySelector('.progress-spinner').classList.add('hidden');
                    document.querySelector('.progress-check').classList.remove('hidden');
                    document.getElementById("progressText").textContent = "Terminé ! (" + 
                        State.allData.length.toLocaleString('fr-FR') + " dossiers)";
                    refreshTable();
                    populateFilters();
                    return;
                }

                State.allData = State.allData.concat(result.data);
                updateStats(State.totalRecords, State.allData.length);
                loadNextBatch();
            });
        }

        loadNextBatch();
    }

    // Refresh table with new data
    function refreshTable() {
        var currentPage = 0;
        var currentSearch = "";

        if (State.dataTable) {
            try {
                currentPage = State.dataTable.page();
                currentSearch = State.dataTable.search();
            } catch (e) {}
        }

        destroyDataTable();
        buildTableBody();
        initDataTable();

        if (currentSearch) {
            State.dataTable.search(currentSearch).draw(false);
        }
        
        var totalPages = State.dataTable.page.info().pages;
        if (currentPage > 0 && currentPage < totalPages) {
            State.dataTable.page(currentPage).draw(false);
        }
    }

    // Render table (initial)
    function renderTable() {
        destroyDataTable();
        buildTableBody();
        initDataTable();
    }

    // Load data for sidebar filter
    function loadData(url, title) {
        var filter = FILTER_MAP[url] || "default";
        State.currentFilter = filter;
        document.getElementById("currentFilter").value = filter;
        document.getElementById("title").textContent = title;
        
        // Reset dropdown filters when changing sidebar filter
        resetFilters();
        
        loadInitial(filter);
    }

    // Export to Excel
    function exportToExcel() {
        if (!State.dataTable) {
            alert("Aucune donnée à exporter.");
            return;
        }

        try {
            // Get visible rows data (as objects, respecting current order & search)
            var data = State.dataTable.rows({ search: 'applied' }).data().toArray();

            if (data.length === 0) {
                alert("Aucun dossier visible à exporter.");
                return;
            }

            // Map to desired columns (skip Action & Documents)
            var exportData = data.map(function(row) {
                // Column order: [0]Action, [1]Reference, [2]Compagnie, [3]Assuré, [4]Matricule,
                // [5]Sinistre, [6]Type, [7]Mode, [8]Mt. Devis, [9]Mt. Facture, [10]Etape, [11]Délai, [12]Status, [13]Documents
                return {
                    "Référence": row[1] || "",
                    "Compagnie": row[2] || "",
                    "Assuré": row[3] || "",
                    "Matricule": row[4] || "",
                    "N° Sinistre": row[5] || "",
                    "Type": row[6] ? $(row[6]).text().trim() : "",
                    "Mode": row[7] ? $(row[7]).text().trim() : "",
                    "Mt. Devis": row[8] ? $(row[8]).text().trim() : "",
                    "Mt. Facture": row[9] ? $(row[9]).text().trim() : "",
                    "Étape": row[10] ? $(row[10]).text().trim() : "",
                    "Délai": row[11] ? $(row[11]).text().trim() : "",
                    "Statut": row[12] ? $(row[12]).text().trim() : ""
                };
            });

            // Convert to worksheet
            var ws = XLSX.utils.json_to_sheet(exportData);

            // Auto-fit column width
            var colWidths = Object.keys(exportData[0]).map(key => ({
                wch: Math.max(10, key.length + 2)
            }));
            ws['!cols'] = colWidths;

            // Create workbook
            var wb = XLSX.utils.book_new();
            XLSX.utils.book_append_sheet(wb, ws, "Dossiers");

            // Generate & download
            var filename = "Dossiers_" + new Date().toISOString().slice(0,10) + ".xlsx";
            XLSX.writeFile(wb, filename);

        } catch (e) {
            console.error("Export error:", e);
            alert("Erreur lors de l'export Excel : " + (e.message || e));
        }
    }

    // Bind sidebar events
    function bindSidebarEvents() {
        var bindings = {
            "collapse1": ["/Expertiser", "Attente Photo Avant"],
            "collapse92": ["/Expertise/encours", "Dossier En Expertise"],
            "collapse95": ["/Instance/Rapport", "Instance Rapport"],
            "collapse2": ["/Devis/Carence", "Attente Devis"],
            "collapse3": ["/Facture/Carence", "Attente Facture"],
            "collapse4": ["/Carence/Rapport", "Attente Rapport"],
            "collapse13": ["/Devis/Envoyer", "Accord Devis"],
            "collapse14": ["/Facture/Envoyer", "Accord Facture"],
            "collapse15": ["/Envoyer/Rapport", "Rapport A Envoyer"],
            "collapse15b": ["/Envoyer/Rapport", "Rapport A Envoyer"],
            "collapse16": ["/Devis/Deuxieme", "2ème Devis"],
            "collapse17": ["/Facture/Deuxieme", "2ème Facture"],
            "collapse05": ["/Deuxieme/Rapport", "Rapport Refusé"],
            "collapse90": ["/Facture/Trait", "Facture en Attente Accord"],
            "collapse91": ["/Devis/Trait", "Devis en Attente Accord"],
            "collapse72": ["/Base", "Attente Doc de Base"],
            "collapse50": ["/Signer/Document", "Documents A Signer"],
            "collapse80": ["/Devis/Photo", "Devis Sans Photo"],
            "collapse81": ["/Facture/Photo", "Facture Sans Photo"],
            "collapse96": ["/Expertise/Apres", "Attente Photo Après"],
            "collapse5": ["/Devis/Retraiter", "Devis A Retraiter"],
            "collapse6": ["/Facture/Retraiter", "Facture A Retraiter"],
            "collapse77": ["/Devis/Traitement", "Devis A Traiter"],
            "collapse9": ["/Facture/Traitement", "Facture A Traiter"],
            "collapse93": ["/Devis/Controler", "Devis A Contrôler"],
            "collapse8": ["/Signer/Rapport", "Rapport A Signer"],
            "collapse10": ["/Devis/Avis", "Demande Avis Devis"],
            "collapse11": ["/Facture/Avis", "Demande Avis Facture"],
            "collapse20": ["/Douteux", "Sinistre Douteux"],
            "collapse21": ["/Tribunale", "Dossier Tribunale"],
            "collapse85": ["/Facturation", "Dossier A Facturer"],
            "collapse71": ["/Rapide", "Dossier Rapide"],
            "collapse88": ["/Signe/Document", "Documents Signés"],
            "collapse7": ["/Retraiter/Rapport", "Rapport A Retraiter"]
        };

        for (var id in bindings) {
            (function(elemId, url, title) {
                var el = document.getElementById(elemId);
                if (el) {
                    el.addEventListener("click", function(e) {
                        e.preventDefault();
                        loadData(url, title);
                    });
                    el.style.cursor = "pointer";
                }
            })(id, bindings[id][0], bindings[id][1]);
        }
    }

    // Initialize on DOM ready
    $(document).ready(function() {
        destroyDataTable();
        bindSidebarEvents();
        loadInitial("default");
    });

    // Expose globally
    window.loadData = loadData;
    window.exportToExcel = exportToExcel;
    window.applyFilters = applyFilters;
    window.resetFilters = resetFilters;

})();
</script>
@endsection