<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>KOMBAR FERD - Gestion des Pesées</title>
    
    <!-- PWA Manifest -->
    <link rel="manifest" href="./manifest.json">
    <meta name="theme-color" content="#667eea">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="apple-mobile-web-app-title" content="KOMBAR FERD">
    
    <!-- PWA Icons pour iOS -->
    <link rel="apple-touch-icon" sizes="72x72" href="./icons/icon-72x72.png">
    <link rel="apple-touch-icon" sizes="96x96" href="./icons/icon-96x96.png">
    <link rel="apple-touch-icon" sizes="128x128" href="./icons/icon-128x128.png">
    <link rel="apple-touch-icon" sizes="144x144" href="./icons/icon-144x144.png">
    <link rel="apple-touch-icon" sizes="152x152" href="./icons/icon-152x152.png">
    <link rel="apple-touch-icon" sizes="192x192" href="./icons/icon-192x192.png">
    
    <!-- Favicon traditionnel -->
    <link rel="icon" type="image/png" sizes="32x32" href="./icons/icon-32x32.png">
    <link rel="icon" type="image/png" sizes="16x16" href="./icons/icon-16x16.png">
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
    <!-- Bibliothèques pour les exports -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
    <script src="./push-manager.js?v=2.1"></script>
    <script src="./notification-watcher.js?v=2.1"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        :root {
            --primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            --secondary-gradient: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
            --success-gradient: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
            --dark-bg: #0f172a;
            --darker-bg: #1e293b;
            --card-bg: rgba(30, 41, 59, 0.8);
            --glass-bg: rgba(255, 255, 255, 0.1);
            --text-primary: #f1f5f9;
            --text-secondary: #94a3b8;
            --border-color: rgba(148, 163, 184, 0.2);
            --shadow-lg: 0 20px 25px -5px rgba(0, 0, 0, 0.3);
            --shadow-xl: 0 25px 50px -12px rgba(0, 0, 0, 0.4);
        }

        body {
            font-family: 'Inter', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
            background: var(--dark-bg);
            color: var(--text-primary);
            line-height: 1.6;
            overflow-x: hidden;
        }

        /* Background Animation */
        body::before {
            content: '';
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: 
                radial-gradient(600px circle at 20% 30%, rgba(102, 126, 234, 0.15) 0%, transparent 50%),
                radial-gradient(800px circle at 80% 70%, rgba(118, 75, 162, 0.1) 0%, transparent 50%),
                radial-gradient(1000px circle at 40% 80%, rgba(240, 147, 251, 0.1) 0%, transparent 50%);
            animation: backgroundShift 20s ease-in-out infinite;
            z-index: -1;
        }

        @keyframes backgroundShift {
            0%, 100% { opacity: 1; transform: scale(1); }
            50% { opacity: 0.8; transform: scale(1.1); }
        }
        
        @keyframes slideInRight {
            0% { 
                transform: translateX(100%); 
                opacity: 0; 
            }
            100% { 
                transform: translateX(0); 
                opacity: 1; 
            }
        }
        
        @keyframes bounce {
            0%, 20%, 53%, 80%, 100% { 
                transform: translate3d(0, 0, 0); 
            }
            40%, 43% { 
                transform: translate3d(0, -8px, 0); 
            }
            70% { 
                transform: translate3d(0, -4px, 0); 
            }
            90% { 
                transform: translate3d(0, -2px, 0); 
            }
        }
        
        @keyframes slideUp {
            0% { 
                transform: translate(-50%, 100%); 
                opacity: 0; 
            }
            100% { 
                transform: translate(-50%, 0); 
                opacity: 1; 
            }
        }

        /* Login Page */
        .login-container {
            display: flex;
            justify-content: center;
            align-items: center;
            min-height: 100vh;
            padding: 20px;
        }

        .login-box {
            background: var(--glass-bg);
            backdrop-filter: blur(20px);
            border: 1px solid var(--border-color);
            border-radius: 24px;
            padding: 48px;
            width: 100%;
            max-width: 420px;
            box-shadow: var(--shadow-xl);
            animation: slideUp 0.6s ease-out;
        }

        @keyframes slideUp {
            from { opacity: 0; transform: translateY(30px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .login-logo {
            text-align: center;
            margin-bottom: 40px;
        }

        .login-logo .icon {
            width: 64px;
            height: 64px;
            background: var(--primary-gradient);
            border-radius: 20px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 16px;
            animation: pulse 2s ease-in-out infinite;
        }

        @keyframes pulse {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.05); }
        }

        .login-title {
            font-size: 28px;
            font-weight: 700;
            margin-bottom: 8px;
            background: var(--primary-gradient);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }

        .login-subtitle {
            color: var(--text-secondary);
            font-size: 16px;
        }

        .form-group {
            margin-bottom: 24px;
        }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            font-weight: 500;
            color: var(--text-primary);
        }

        .form-control {
            width: 100%;
            padding: 16px 20px;
            background: rgba(30, 41, 59, 0.6);
            border: 1px solid var(--border-color);
            border-radius: 12px;
            color: var(--text-primary);
            font-size: 16px;
            transition: all 0.3s ease;
            backdrop-filter: blur(10px);
        }

        .form-control:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
            background: rgba(30, 41, 59, 0.8);
        }

        .btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            padding: 16px 32px;
            border: none;
            border-radius: 12px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            text-decoration: none;
            position: relative;
            overflow: hidden;
        }

        .btn::before {
            content: '';
            position: absolute;
            top: 0;
            left: -100%;
            width: 100%;
            height: 100%;
            background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
            transition: left 0.5s ease;
        }

        .btn:hover::before {
            left: 100%;
        }

        .btn-primary {
            background: var(--primary-gradient);
            color: white;
            box-shadow: 0 8px 15px rgba(102, 126, 234, 0.3);
            width: 100%;
        }

        .btn-primary:hover {
            transform: translateY(-2px);
            box-shadow: 0 12px 25px rgba(102, 126, 234, 0.4);
        }

        .btn-secondary {
            background: rgba(148, 163, 184, 0.1);
            color: var(--text-primary);
            border: 1px solid var(--border-color);
        }

        .btn-secondary:hover {
            background: rgba(148, 163, 184, 0.2);
        }

        .btn-sm {
            padding: 8px 16px;
            font-size: 14px;
        }

        /* Dashboard */
        .dashboard {
            display: none;
            min-height: 100vh;
        }

        .dashboard.active {
            display: block;
        }

        /* Header */
        .header {
            background: var(--glass-bg);
            backdrop-filter: blur(20px);
            border-bottom: 1px solid var(--border-color);
            padding: 16px 0;
            position: sticky;
            top: 0;
            z-index: 100;
        }

        .header-content {
            max-width: 1400px;
            margin: 0 auto;
            padding: 0 24px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .logo-section {
            display: flex;
            align-items: center;
            gap: 16px;
        }

        .logo-icon {
            width: 48px;
            height: 48px;
            background: var(--primary-gradient);
            border-radius: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-size: 20px;
            font-weight: bold;
        }

        .logo-text {
            font-size: 24px;
            font-weight: 700;
            background: var(--primary-gradient);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }

        .user-section {
            display: flex;
            align-items: center;
            gap: 16px;
        }

        .status-indicator {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 8px 16px;
            background: rgba(34, 197, 94, 0.1);
            border: 1px solid rgba(34, 197, 94, 0.2);
            border-radius: 20px;
        }

        .status-dot {
            width: 8px;
            height: 8px;
            background: #22c55e;
            border-radius: 50%;
            animation: pulse 2s ease-in-out infinite;
        }

        .user-info {
            color: var(--text-secondary);
            font-size: 14px;
        }

        .user-name {
            color: var(--text-primary);
            font-weight: 600;
        }

        .btn-logout {
            background: var(--secondary-gradient);
            color: white;
            padding: 10px 20px;
            border-radius: 8px;
            border: none;
            cursor: pointer;
            font-weight: 600;
            transition: all 0.3s ease;
        }

        .btn-logout:hover {
            transform: translateY(-1px);
            box-shadow: 0 8px 15px rgba(245, 87, 108, 0.3);
        }

        .btn-notifications {
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
            color: white;
            padding: 10px 12px;
            border-radius: 50%;
            cursor: pointer;
            font-size: 16px;
            margin-right: 15px;
            position: relative;
            transition: all 0.3s ease;
            backdrop-filter: blur(10px);
        }

        .btn-notifications:hover {
            background: rgba(255, 255, 255, 0.2);
            transform: translateY(-1px);
            box-shadow: 0 8px 15px rgba(102, 126, 234, 0.3);
        }

        .notification-badge {
            position: absolute;
            top: -5px;
            right: -5px;
            background: #dc3545;
            color: white;
            border-radius: 50%;
            width: 18px;
            height: 18px;
            font-size: 11px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
        }
        
        /* Bouton surveillance mobile */
        .mobile-watch-toggle {
            background: rgba(255,255,255,0.1);
            border: 1px solid rgba(255,255,255,0.2);
            color: white;
            padding: 8px 12px;
            border-radius: 20px;
            font-size: 14px;
            cursor: pointer;
            margin-left: 8px;
            transition: all 0.3s ease;
        }
        
        .mobile-watch-toggle:hover {
            background: rgba(255,255,255,0.2);
        }
        
        .mobile-watch-toggle.active {
            background: rgba(34, 197, 94, 0.3);
            border-color: rgba(34, 197, 94, 0.5);
        }

        .notification-panel {
            position: fixed;
            top: 70px;
            right: 20px;
            width: 350px;
            max-width: 90vw;
            z-index: 1000;
            animation: slideInRight 0.3s ease;
        }

        @keyframes slideInRight {
            from { transform: translateX(100%); opacity: 0; }
            to { transform: translateX(0); opacity: 1; }
        }

        /* Navigation */
        .nav-container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 0 24px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .nav-info {
            display: flex;
            align-items: center;
        }

        .nav-tabs {
            display: flex;
            gap: 8px;
            padding: 24px 0;
            overflow-x: auto;
            scrollbar-width: none;
            -ms-overflow-style: none;
        }

        .nav-tabs::-webkit-scrollbar {
            display: none;
        }

        .nav-tab {
            padding: 12px 24px;
            background: rgba(148, 163, 184, 0.05);
            border: 1px solid var(--border-color);
            border-radius: 12px;
            color: var(--text-secondary);
            font-weight: 500;
            cursor: pointer;
            transition: all 0.3s ease;
            white-space: nowrap;
            position: relative;
            overflow: hidden;
        }

        .nav-tab:hover {
            background: rgba(148, 163, 184, 0.1);
            color: var(--text-primary);
        }

        .nav-tab.active {
            background: var(--primary-gradient);
            color: white;
            box-shadow: 0 4px 15px rgba(102, 126, 234, 0.3);
        }

        /* Main Content */
        .main-content {
            max-width: 1400px;
            margin: 0 auto;
            padding: 32px 24px;
        }

        /* Stats Grid */
        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 24px;
            margin-bottom: 40px;
        }

        .stat-card {
            background: var(--glass-bg);
            backdrop-filter: blur(20px);
            border: 1px solid var(--border-color);
            border-radius: 20px;
            padding: 32px;
            text-align: center;
            transition: all 0.3s ease;
            position: relative;
            overflow: hidden;
        }

        .stat-card::before {
            content: '';
            position: absolute;
            top: 0;
            left: 0;
            right: 0;
            height: 4px;
            background: var(--primary-gradient);
        }

        .stat-card:hover {
            transform: translateY(-8px);
            box-shadow: var(--shadow-xl);
        }

        .stat-icon {
            width: 56px;
            height: 56px;
            background: var(--primary-gradient);
            border-radius: 16px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 20px;
            font-size: 24px;
        }

        .stat-value {
            font-size: 36px;
            font-weight: 800;
            margin-bottom: 8px;
            background: var(--primary-gradient);
            -webkit-background-clip: text;
            -webkit-text-fill-color: transparent;
            background-clip: text;
        }

        .stat-label {
            color: var(--text-secondary);
            font-size: 14px;
            text-transform: uppercase;
            letter-spacing: 0.5px;
            font-weight: 500;
        }

        /* Content Sections */
        .content-section {
            display: none;
            animation: fadeIn 0.5s ease-out;
        }

        .content-section.active {
            display: block;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }

        /* Cards */
        .card {
            background: var(--glass-bg);
            backdrop-filter: blur(20px);
            border: 1px solid var(--border-color);
            border-radius: 20px;
            padding: 32px;
            margin-bottom: 32px;
            box-shadow: var(--shadow-lg);
        }

        .card-header {
            display: flex;
            align-items: center;
            justify-content: space-between;
            margin-bottom: 24px;
            padding-bottom: 16px;
            border-bottom: 1px solid var(--border-color);
        }

        .card-title {
            font-size: 20px;
            font-weight: 700;
            color: var(--text-primary);
        }

        /* Search Form */
        .search-form {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
            gap: 24px;
            margin-bottom: 32px;
        }

        .search-actions {
            grid-column: 1 / -1;
            display: flex;
            gap: 16px;
            justify-content: center;
            flex-wrap: wrap;
            margin-top: 24px;
        }

        /* Data Table */
        .table-container {
            background: var(--card-bg);
            border-radius: 16px;
            overflow: hidden;
            border: 1px solid var(--border-color);
        }

        .data-table {
            width: 100%;
            border-collapse: collapse;
        }

        .data-table th {
            background: rgba(102, 126, 234, 0.1);
            padding: 20px 16px;
            text-align: left;
            font-weight: 600;
            color: var(--text-primary);
            border-bottom: 1px solid var(--border-color);
            position: sticky;
            top: 0;
        }

        .data-table td {
            padding: 16px;
            border-bottom: 1px solid rgba(148, 163, 184, 0.1);
            color: var(--text-secondary);
        }

        .data-table tr:hover {
            background: rgba(148, 163, 184, 0.05);
        }

        .data-table tr:last-child td {
            border-bottom: none;
        }

        /* Charts */
        .chart-container {
            background: var(--glass-bg);
            backdrop-filter: blur(20px);
            border: 1px solid var(--border-color);
            border-radius: 20px;
            padding: 32px;
            margin-bottom: 32px;
            height: 420px;
        }

        /* Ticket Preview */
        .ticket-preview {
            background: var(--glass-bg);
            backdrop-filter: blur(20px);
            border: 2px solid var(--border-color);
            border-radius: 20px;
            padding: 32px;
            margin: 32px 0;
            font-family: 'Courier New', monospace;
        }

        .ticket-header {
            text-align: center;
            margin-bottom: 32px;
            padding-bottom: 20px;
            border-bottom: 2px solid var(--border-color);
        }

        .ticket-details {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 32px;
        }

        /* Alerts */
        .alert {
            padding: 16px 20px;
            margin-bottom: 24px;
            border-radius: 12px;
            font-weight: 500;
            border-left: 4px solid;
        }

        .alert-success {
            background: rgba(34, 197, 94, 0.1);
            color: #22c55e;
            border-color: #22c55e;
        }

        .alert-error {
            background: rgba(239, 68, 68, 0.1);
            color: #ef4444;
            border-color: #ef4444;
        }

        .alert-info {
            background: rgba(59, 130, 246, 0.1);
            color: #3b82f6;
            border-color: #3b82f6;
        }

        /* Loading */
        .loading {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 40px;
            color: var(--text-secondary);
        }

        .spinner {
            width: 40px;
            height: 40px;
            border: 4px solid rgba(102, 126, 234, 0.2);
            border-top: 4px solid #667eea;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-right: 16px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* Mobile Responsive */
        @media (max-width: 768px) {
            .container {
                padding: 0 12px;
                margin: 0;
            }
            
            .header-content {
                padding: 0 16px;
                flex-wrap: wrap;
                gap: 12px;
            }

            .logo-text {
                font-size: 18px;
            }

            .user-section {
                flex-direction: column;
                align-items: flex-end;
                gap: 8px;
            }

            .status-indicator {
                padding: 6px 12px;
                font-size: 12px;
            }

            .user-info {
                font-size: 12px;
                text-align: right;
            }

            .btn-logout {
                padding: 8px 16px;
                font-size: 14px;
            }

            .main-content {
                padding: 20px 12px;
            }

            .search-form {
                grid-template-columns: 1fr;
                gap: 20px;
            }

            .search-actions {
                flex-direction: column;
                gap: 12px;
                align-items: stretch;
            }

            .search-actions .btn {
                width: 100%;
                justify-content: center;
                padding: 14px 24px;
                font-size: 16px;
            }

            .stats-grid {
                grid-template-columns: repeat(2, 1fr);
                gap: 12px;
            }

            .stat-card {
                padding: 20px 16px;
            }

            .stat-icon {
                width: 48px;
                height: 48px;
                font-size: 20px;
                margin-bottom: 16px;
            }

            .stat-value {
                font-size: 28px;
            }

            .stat-label {
                font-size: 12px;
            }

            .card {
                padding: 20px 16px;
                margin-bottom: 20px;
            }

            .card-header {
                margin-bottom: 20px;
                flex-direction: column;
                align-items: flex-start;
                gap: 12px;
            }

            .card-title {
                font-size: 18px;
            }

            .ticket-details {
                grid-template-columns: 1fr;
                gap: 20px;
            }

            .nav-tabs {
                padding: 16px 0;
                gap: 6px;
            }

            .nav-tab {
                padding: 10px 16px;
                font-size: 14px;
                border-radius: 8px;
            }

            /* Tableau responsive */
            .table-container {
                overflow-x: auto;
                -webkit-overflow-scrolling: touch;
            }

            .data-table {
                font-size: 12px;
                min-width: 700px;
            }

            .data-table th,
            .data-table td {
                padding: 8px 6px;
                white-space: nowrap;
            }

            .data-table th:first-child,
            .data-table td:first-child {
                position: sticky;
                left: 0;
                background: var(--card-bg);
                z-index: 1;
            }

            /* Form controls mobile */
            .form-control {
                padding: 14px 16px;
                font-size: 16px; /* Évite le zoom sur iOS */
                border-radius: 10px;
                width: 100%;
                box-sizing: border-box;
            }

            .form-group {
                margin-bottom: 16px;
            }

            .form-group label {
                font-size: 14px;
                margin-bottom: 6px;
                display: block;
            }
            
            .search-form {
                grid-template-columns: 1fr;
                gap: 16px;
                padding: 16px;
            }
            
            .search-actions {
                display: flex;
                flex-direction: column;
                gap: 12px;
            }
            
            .search-actions .btn {
                width: 100%;
                padding: 14px;
                font-size: 16px;
                margin: 0;
            }

            /* Alertes mobile */
            .alert {
                padding: 14px 16px;
                font-size: 14px;
                border-radius: 10px;
                margin-bottom: 16px;
            }

            /* Charts responsive */
            .chart-container {
                padding: 20px 16px;
                height: 300px;
                margin-bottom: 20px;
            }

            /* Login responsive */
            .login-box {
                padding: 32px 24px;
                margin: 20px 16px;
                border-radius: 20px;
            }

            .login-title {
                font-size: 24px;
            }

            .login-subtitle {
                font-size: 14px;
            }

            /* Ticket preview mobile */
            .ticket-preview {
                padding: 20px 16px;
                border-radius: 16px;
                font-size: 14px;
            }

            .ticket-header h2 {
                font-size: 20px;
            }

            .ticket-header h3 {
                font-size: 16px;
            }

            /* Loading mobile */
            .loading {
                padding: 30px 16px;
                font-size: 14px;
            }

            .spinner {
                width: 32px;
                height: 32px;
                margin-right: 12px;
            }

            /* Résultats info */
            #resultsInfo {
                font-size: 14px;
                text-align: center;
            }
        }

        /* Très petits écrans */
        @media (max-width: 480px) {
            .stats-grid {
                grid-template-columns: 1fr;
            }

            .header-content {
                justify-content: space-between;
            }

            .user-section {
                flex-direction: row;
                align-items: center;
                gap: 8px;
            }

            .user-info {
                display: none;
            }

            .status-indicator span {
                display: none;
            }

            .status-indicator {
                padding: 8px;
                border-radius: 50%;
                width: 32px;
                height: 32px;
                display: flex;
                align-items: center;
                justify-content: center;
            }

            .btn-logout {
                padding: 6px 12px;
                font-size: 12px;
            }

            .main-content {
                padding: 16px 8px;
            }

            .card {
                padding: 16px 12px;
            }

            .search-actions .btn {
                padding: 12px 20px;
                font-size: 15px;
            }
        }

        /* Amélioration du scroll horizontal */
        .nav-tabs::-webkit-scrollbar {
            height: 4px;
        }

        .nav-tabs::-webkit-scrollbar-track {
            background: transparent;
        }

        .nav-tabs::-webkit-scrollbar-thumb {
            background: var(--border-color);
            border-radius: 2px;
        }

        .table-container::-webkit-scrollbar {
            height: 6px;
        }

        .table-container::-webkit-scrollbar-track {
            background: var(--darker-bg);
        }

        .table-container::-webkit-scrollbar-thumb {
            background: var(--border-color);
            border-radius: 3px;
        }

        /* Print Styles */
        @media print {
            body * {
                visibility: hidden;
            }
            
            .ticket-preview,
            .ticket-preview * {
                visibility: visible;
            }
            
            .ticket-preview {
                position: absolute;
                left: 0;
                top: 0;
                background: white;
                color: black;
            }
        }

        /* Scrollbar Styles */
        ::-webkit-scrollbar {
            width: 8px;
        }

        ::-webkit-scrollbar-track {
            background: var(--darker-bg);
        }

        ::-webkit-scrollbar-thumb {
            background: var(--border-color);
            border-radius: 4px;
        }

        ::-webkit-scrollbar-thumb:hover {
            background: rgba(148, 163, 184, 0.4);
        }

        /* === STYLES RAPPORTS & ANALYTICS === */
        
        .reports-header {
            margin-bottom: 30px;
        }
        
        .reports-actions {
            display: flex;
            gap: 10px;
        }
        
        .btn-export, .btn-refresh {
            padding: 8px 16px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 13px;
            transition: all 0.3s ease;
        }
        
        .btn-export {
            background: #3498db;
            color: white;
        }
        
        .btn-export:hover {
            background: #2980b9;
            transform: translateY(-1px);
        }
        
        .btn-refresh {
            background: #2ecc71;
            color: white;
        }
        
        .btn-refresh:hover {
            background: #27ae60;
            transform: translateY(-1px);
        }
        
        .reports-filters {
            display: flex;
            gap: 20px;
            padding: 20px;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 12px;
            flex-wrap: wrap;
            align-items: end;
        }
        
        .filter-group {
            display: flex;
            flex-direction: column;
            gap: 5px;
        }
        
        .filter-group label {
            font-size: 12px;
            color: #94a3b8;
            font-weight: 500;
        }
        
        .filter-group select, .filter-group input {
            padding: 8px 12px;
            border: 1px solid rgba(148, 163, 184, 0.2);
            border-radius: 6px;
            background: rgba(255, 255, 255, 0.1);
            color: #f1f5f9;
            font-size: 13px;
        }
        
        .filter-group select:focus, .filter-group input:focus {
            outline: none;
            border-color: #667eea;
            box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
        }
        
        .metrics-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .metric-card {
            display: flex;
            align-items: center;
            gap: 15px;
            padding: 20px;
            background: rgba(255, 255, 255, 0.05);
            border-radius: 12px;
            border: 1px solid rgba(255, 255, 255, 0.1);
            transition: all 0.3s ease;
        }
        
        .metric-card:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
            border-color: rgba(102, 126, 234, 0.3);
        }
        
        .metric-icon {
            font-size: 2rem;
            width: 60px;
            height: 60px;
            display: flex;
            align-items: center;
            justify-content: center;
            background: linear-gradient(135deg, #667eea, #764ba2);
            border-radius: 10px;
        }
        
        .metric-content {
            flex: 1;
        }
        
        .metric-value {
            font-size: 2rem;
            font-weight: 700;
            color: #f1f5f9;
            line-height: 1;
            margin-bottom: 5px;
        }
        
        .metric-label {
            font-size: 0.9rem;
            color: #94a3b8;
            margin-bottom: 5px;
        }
        
        .metric-change {
            font-size: 0.8rem;
            font-weight: 600;
            padding: 2px 8px;
            border-radius: 12px;
        }
        
        .metric-change.positive {
            background: rgba(34, 197, 94, 0.2);
            color: #22c55e;
        }
        
        .metric-change.negative {
            background: rgba(239, 68, 68, 0.2);
            color: #ef4444;
        }
        
        .metric-change.neutral {
            background: rgba(148, 163, 184, 0.2);
            color: #94a3b8;
        }
        
        .charts-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(500px, 1fr));
            gap: 20px;
            margin-bottom: 30px;
        }
        
        .chart-card {
            background: rgba(255, 255, 255, 0.05);
            border-radius: 12px;
            border: 1px solid rgba(255, 255, 255, 0.1);
            overflow: hidden;
        }
        
        .chart-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 20px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
        }
        
        .chart-header h3 {
            margin: 0;
            color: #f1f5f9;
            font-size: 1.1rem;
            font-weight: 600;
        }
        
        .chart-controls select {
            padding: 4px 8px;
            border: 1px solid rgba(148, 163, 184, 0.2);
            border-radius: 4px;
            background: rgba(255, 255, 255, 0.1);
            color: #f1f5f9;
            font-size: 12px;
        }
        
        .chart-container {
            padding: 20px;
            height: 300px;
            position: relative;
        }
        
        .comparison-section {
            margin-bottom: 30px;
        }
        
        .comparison-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
            padding: 20px;
        }
        
        .comparison-card {
            background: rgba(255, 255, 255, 0.03);
            padding: 20px;
            border-radius: 10px;
            border: 1px solid rgba(255, 255, 255, 0.1);
        }
        
        .comparison-title {
            font-size: 0.9rem;
            color: #94a3b8;
            margin-bottom: 15px;
            font-weight: 500;
        }
        
        .comparison-data {
            display: flex;
            flex-direction: column;
            gap: 10px;
        }
        
        .comparison-metric {
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        .comparison-metric span:first-child {
            color: #f1f5f9;
        }
        
        .comparison-value {
            font-weight: 600;
            padding: 4px 8px;
            border-radius: 6px;
            font-size: 0.9rem;
        }
        
        .detailed-table-section {
            margin-bottom: 30px;
        }
        
        .table-controls {
            display: flex;
            gap: 15px;
            align-items: center;
        }
        
        .table-controls input {
            padding: 8px 12px;
            border: 1px solid rgba(148, 163, 184, 0.2);
            border-radius: 6px;
            background: rgba(255, 255, 255, 0.1);
            color: #f1f5f9;
            font-size: 13px;
        }
        
        .table-controls select {
            padding: 8px 12px;
            border: 1px solid rgba(148, 163, 184, 0.2);
            border-radius: 6px;
            background: rgba(255, 255, 255, 0.1);
            color: #f1f5f9;
            font-size: 13px;
        }
        
        .reports-table {
            width: 100%;
            border-collapse: collapse;
            font-size: 0.9rem;
        }
        
        .reports-table th {
            background: rgba(255, 255, 255, 0.1);
            padding: 12px;
            text-align: left;
            color: #f1f5f9;
            font-weight: 600;
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            cursor: pointer;
            transition: background 0.2s ease;
        }
        
        .reports-table th:hover {
            background: rgba(255, 255, 255, 0.15);
        }
        
        .reports-table td {
            padding: 10px 12px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.05);
            color: #e2e8f0;
        }
        
        .reports-table tbody tr:hover {
            background: rgba(255, 255, 255, 0.03);
        }
        
        .loading-row {
            text-align: center;
            color: #94a3b8;
            font-style: italic;
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .reports-filters {
                flex-direction: column;
                align-items: stretch;
            }
            
            .metrics-grid {
                grid-template-columns: 1fr;
            }
            
            .charts-grid {
                grid-template-columns: 1fr;
            }
            
            .comparison-grid {
                grid-template-columns: 1fr;
            }
            
            .reports-actions {
                flex-direction: column;
            }
            
            .table-controls {
                flex-direction: column;
                align-items: stretch;
            }
        }
    </style>
</head>
<body>
    <!-- Page de Login -->
    <div id="loginPage" class="login-container">
        <div class="login-box">
            <div class="login-logo">
                <div class="icon">⚖</div>
                <h1 class="login-title">OZIXSOT Mobile</h1>
                <p class="login-subtitle">Système de Gestion des Pesées</p>
            </div>
            
            <form id="loginForm">
                <div class="form-group">
                    <label for="username">Nom d'utilisateur</label>
                    <input type="text" id="username" name="username" class="form-control" required>
                </div>
                <div class="form-group">
                    <label for="password">Mot de passe</label>
                    <input type="password" id="password" name="password" class="form-control" required>
                </div>
                <button type="submit" class="btn btn-primary">
                    <span id="loginText">Se connecter</span>
                    <div id="loginSpinner" class="spinner" style="display: none; width: 20px; height: 20px; margin: 0 0 0 8px;"></div>
                </button>
            </form>
            
            <div id="loginError" class="alert alert-error" style="display: none; margin-top: 16px;">
                Nom d'utilisateur ou mot de passe incorrect
            </div>
        </div>
    </div>

    <!-- Dashboard -->
    <div id="dashboard" class="dashboard">
        <!-- Header -->
        <header class="header">
            <div class="header-content">
                <div class="logo-section">
                    <div class="logo-icon">⚖</div>
                    <div class="logo-text">OZIXSOT Mobil</div>
                </div>
                
                <div class="user-section">
                    <div class="status-indicator">
                        <div class="status-dot"></div>
                        <span>Temps réel</span>
                    </div>
                    <button class="btn-notifications" onclick="toggleNotificationPanel()" title="Gérer les notifications">
                        🔔
                        <span class="notification-badge" id="notificationBadge" style="display: none;"></span>
                    </button>
                    
                    <!-- Bouton contrôle surveillance -->
                    <button class="mobile-watch-toggle" id="watchToggle" onclick="toggleNotificationWatch()" title="Surveillance automatique">
                        <span id="watchIcon">🔍</span>
                    </button>
                    
                    <!-- Bouton test surveillance (debug) -->
                    <button class="mobile-watch-toggle" onclick="testNotificationWatch()" title="Test surveillance maintenant" style="
                        background: rgba(255,165,0,0.2);
                        border-color: rgba(255,165,0,0.4);
                        margin-left: 4px;
                        font-size: 12px;
                        padding: 6px 10px;
                    ">
                        🧪
                    </button>
                    
                    <!-- Bouton test notification forcée (debug) -->
                    <button class="mobile-watch-toggle" onclick="forceTestNotification()" title="Simuler nouvelle pesée" style="
                        background: rgba(255,0,128,0.2);
                        border-color: rgba(255,0,128,0.4);
                        margin-left: 4px;
                        font-size: 12px;
                        padding: 6px 10px;
                    ">
                        💥
                    </button>
                    
                    <!-- Bouton reset ID (debug) -->
                    <button class="mobile-watch-toggle" onclick="resetWatcherId()" title="Reset ID de référence" style="
                        background: rgba(0,255,128,0.2);
                        border-color: rgba(0,255,128,0.4);
                        margin-left: 4px;
                        font-size: 12px;
                        padding: 6px 10px;
                    ">
                        🔄
                    </button>
                    
                    <!-- Bouton test API direct (debug) -->
                    <button class="mobile-watch-toggle" onclick="testDirectAPI()" title="Test API direct" style="
                        background: rgba(128,0,255,0.2);
                        border-color: rgba(128,0,255,0.4);
                        margin-left: 4px;
                        font-size: 12px;
                        padding: 6px 10px;
                    ">
                        📡
                    </button>
                    <div class="user-info">
                        Bienvenue, <span class="user-name" id="userWelcome">Admin</span>
                    </div>
                    <button class="btn-logout" onclick="logout()">Déconnexion</button>
                </div>
            </div>
        </header>

        <!-- Navigation -->
        <nav class="nav-container">
            <div class="nav-tabs">
                <button class="nav-tab active" onclick="showSection('overview', this)">📊 Aperçu</button>
                <button class="nav-tab" onclick="showSection('search', this)">🔍 Recherche</button>
                <button class="nav-tab" onclick="showSection('ticket', this)">🎫 Impression</button>
                <button class="nav-tab" onclick="showSection('reports', this)">📈 Rapports</button>
            </div>
            <div class="nav-info">
                <span id="versionInfo" style="font-size: 12px; color: #666; margin-right: 10px;">v1.0.0</span>
                <button id="updateButton" onclick="forceUpdate()" style="display: none; padding: 4px 8px; background: #e74c3c; color: white; border: none; border-radius: 4px; font-size: 11px; cursor: pointer;" title="Nouvelle version disponible - Cliquer pour mettre à jour">
                    🔄 Mise à jour
                </button>
            </div>
        </nav>

        <!-- Main Content -->
        <main class="main-content">
            <!-- Section Aperçu -->
            <section id="overview" class="content-section active">
                <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                    <h2 style="margin: 0; color: #2c3e50;">📊 Aperçu des Statistiques</h2>
                    <button onclick="refreshStatistics()" style="padding: 8px 16px; background: #3498db; color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 14px;" title="Rafraîchir les statistiques">
                        🔄 Actualiser
                    </button>
                </div>
                <div class="stats-grid">
                    <div class="stat-card">
                        <div class="stat-icon">📊</div>
                        <div class="stat-value" id="totalPesees">145</div>
                        <div class="stat-label">Total Pesées</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon">⚖️</div>
                        <div class="stat-value" id="poidsTotal">2,450 T</div>
                        <div class="stat-label">Poids Total</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon">📅</div>
                        <div class="stat-value" id="peseesAujourdhui">12</div>
                        <div class="stat-label">Pesées Aujourd'hui</div>
                    </div>
                    <div class="stat-card">
                        <div class="stat-icon">👥</div>
                        <div class="stat-value" id="clientsActifs">8</div>
                        <div class="stat-label">Clients Actifs</div>
                    </div>
                </div>

                <div class="chart-container">
                    <canvas id="evolutionChart"></canvas>
                </div>

                <div class="chart-container">
                    <canvas id="produitsChart"></canvas>
                </div>
            </section>

            <!-- Section Recherche -->
            <section id="search" class="content-section">
                <div class="card">
                    <div class="card-header">
                        <h2 class="card-title">🔍 Recherche des Pesées</h2>
                    </div>
                    
                    <div id="searchLoading" class="loading" style="display: none;">
                        <div class="spinner"></div>
                        Chargement des options de recherche...
                    </div>
                    
                    <form class="search-form" id="searchForm">
                        <div class="form-group">
                            <label>Code Pesée</label>
                            <input type="text" placeholder="Code Pesée" id="codePesee" class="form-control">
                        </div>
                        
                        <div class="form-group">
                            <label>Numéro Ticket</label>
                            <input type="text" placeholder="Numéro Ticket" id="numTicket" class="form-control">
                        </div>
                        
                        <div class="form-group">
                            <label>Client</label>
                            <input type="text" placeholder="Client" id="client" list="clientsList" class="form-control">
                            <datalist id="clientsList"></datalist>
                        </div>
                        
                        <div class="form-group">
                            <label>Fournisseur</label>
                            <input type="text" placeholder="Fournisseur" id="fournisseur" list="fournisseursList" class="form-control">
                            <datalist id="fournisseursList"></datalist>
                        </div>
                        
                        <div class="form-group">
                            <label>Code Site</label>
                            <input type="text" placeholder="Code Site" id="codeSite" list="codesSitesList" class="form-control">
                            <datalist id="codesSitesList"></datalist>
                        </div>
                        
                        <div class="form-group">
                            <label>Site</label>
                            <input type="text" placeholder="Nom du site" id="site" list="sitesList" class="form-control">
                            <datalist id="sitesList"></datalist>
                        </div>
                        
                        <div class="form-group">
                            <label>Date Début</label>
                            <input type="date" id="dateDebut" class="form-control">
                        </div>
                        
                        <div class="form-group">
                            <label>Date Fin</label>
                            <input type="date" id="dateFin" class="form-control">
                        </div>
                        
                        <div class="form-group">
                            <label>Produit</label>
                            <input type="text" placeholder="Produit" id="produit" list="produitsList" class="form-control">
                            <datalist id="produitsList"></datalist>
                        </div>
                        
                        <div class="search-actions">
                            <button type="button" class="btn btn-primary" onclick="rechercher()">
                                🔍 Rechercher
                            </button>
                            <button type="button" class="btn btn-secondary" onclick="resetSearch()">
                                🔄 Réinitialiser
                            </button>
                            <button type="button" class="btn btn-secondary" onclick="exportResults()">
                                📊 Exporter CSV
                            </button>
                        </div>
                    </form>
                </div>

                <div class="card">
                    <div id="resultsInfo" class="alert alert-info" style="display: none;"></div>
                    
                    <div class="table-container">
                        <table class="data-table" id="resultsTable">
                            <thead>
                                <tr>
                                    <th>Code Pesée</th>
                                    <th>N° Ticket</th>
                                    <th>Date</th>
                                    <th>Client</th>
                                    <th>Fournisseur</th>
                                    <th>Produit</th>
                                    <th>Poids Net (kg)</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody id="resultsBody">
                                <!-- Résultats chargés ici -->
                            </tbody>
                        </table>
                    </div>
                </div>
            </section>

            <!-- Section Ticket -->
            <section id="ticket" class="content-section">
                <div class="card">
                    <div class="card-header">
                        <h2 class="card-title">🎫 Impression de Ticket</h2>
                    </div>
                    
                    <div class="form-group">
                        <label>Rechercher par Numéro de Ticket ou Code Pesée :</label>
                        <input type="text" id="ticketSearch" placeholder="Ex: 20250819COPT00002" class="form-control">
                        <button class="btn btn-primary" onclick="loadTicket()" style="margin-top: 16px;">
                            📥 Charger Ticket
                        </button>
                    </div>

                    <div class="ticket-preview" id="ticketPreview">
                        <div class="ticket-header">
                            <h2>KOMBAR FERD</h2>
                            <h3>TICKET DE PESÉE</h3>
                            <p>Date: <span id="ticketDate">19/08/2025</span> | N°: <span id="ticketNumber">T001234</span></p>
                        </div>
                        
                        <div class="ticket-details">
                            <div>
                                <p><strong>Client:</strong> <span id="ticketClient">EXEMPLE SARL</span></p>
                                <p><strong>Fournisseur:</strong> <span id="ticketFournisseur">FOURNISSEUR ABC</span></p>
                                <p><strong>Produit:</strong> <span id="ticketProduit">CACAO</span></p>
                                <p><strong>Provenance:</strong> <span id="ticketProvenance">ABIDJAN</span></p>
                                <p><strong>Destination:</strong> <span id="ticketDestination">GRAND BASSAM</span></p>
                                <p><strong>Véhicule:</strong> <span id="ticketVehicule">AA 1234 AB</span></p>
                            </div>
                            <div>
                                <p><strong>Poids 1:</strong> <span id="ticketPoids1">15,680 kg</span></p>
                                <p><strong>Poids 2:</strong> <span id="ticketPoids2">5,230 kg</span></p>
                                <p><strong>Poids Net:</strong> <span id="ticketPoidsNet">10,450 kg</span></p>
                                <p><strong>Peseur:</strong> <span id="ticketPeseur">DEMO</span></p>
                                <p><strong>Site:</strong> <span id="ticketSite">S001</span></p>
                            </div>
                        </div>
                    </div>

                    <button class="btn btn-primary" onclick="window.print()">
                        🖨️ Imprimer Ticket
                    </button>
                </div>
            </section>

            <!-- Section Rapports -->
            <section id="reports" class="content-section">
                <!-- En-tête des rapports avec filtres -->
                <div class="reports-header">
                    <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 20px;">
                        <h2 style="margin: 0; color: #2c3e50;">📈 Rapports et Analytics</h2>
                        <div class="reports-actions">
                            <button onclick="exportToPDF()" class="btn btn-export" title="Exporter en PDF">
                                📄 PDF
                            </button>
                            <button onclick="exportToExcel()" class="btn btn-export" title="Exporter en Excel">
                                📊 Excel
                            </button>
                            <button onclick="refreshReports()" class="btn btn-refresh" title="Actualiser les rapports">
                                🔄 Actualiser
                            </button>
                        </div>
                    </div>
                    
                    <!-- Filtres avancés -->
                    <div class="reports-filters">
                        <div class="filter-group">
                            <label>Période</label>
                            <select id="periodFilter" onchange="applyReportFilters()">
                                <option value="7d">7 derniers jours</option>
                                <option value="30d" selected>30 derniers jours</option>
                                <option value="90d">90 derniers jours</option>
                                <option value="1y">1 an</option>
                                <option value="custom">Personnalisé</option>
                            </select>
                        </div>
                        
                        <div class="filter-group" id="customDateRange" style="display: none;">
                            <label>De</label>
                            <input type="date" id="startDate">
                            <label>À</label>
                            <input type="date" id="endDate">
                        </div>
                        
                        <div class="filter-group">
                            <label>Site</label>
                            <select id="siteFilter" onchange="applyReportFilters()">
                                <option value="all">Tous les sites</option>
                            </select>
                        </div>
                        
                        <div class="filter-group">
                            <label>Client</label>
                            <select id="clientFilter" onchange="applyReportFilters()">
                                <option value="all">Tous les clients</option>
                            </select>
                        </div>
                    </div>
                </div>

                <!-- Métriques clés -->
                <div class="metrics-grid">
                    <div class="metric-card">
                        <div class="metric-icon">📊</div>
                        <div class="metric-content">
                            <div class="metric-value" id="totalWeighingsMetric">0</div>
                            <div class="metric-label">Total Pesées</div>
                            <div class="metric-change" id="weighingsChange">+0%</div>
                        </div>
                    </div>
                    
                    <div class="metric-card">
                        <div class="metric-icon">⚖️</div>
                        <div class="metric-content">
                            <div class="metric-value" id="totalWeightMetric">0 T</div>
                            <div class="metric-label">Poids Total</div>
                            <div class="metric-change" id="weightChange">+0%</div>
                        </div>
                    </div>
                    
                    <div class="metric-card">
                        <div class="metric-icon">📈</div>
                        <div class="metric-content">
                            <div class="metric-value" id="avgWeightMetric">0 kg</div>
                            <div class="metric-label">Poids Moyen</div>
                            <div class="metric-change" id="avgChange">+0%</div>
                        </div>
                    </div>
                    
                    <div class="metric-card">
                        <div class="metric-icon">👥</div>
                        <div class="metric-content">
                            <div class="metric-value" id="activeClientsMetric">0</div>
                            <div class="metric-label">Clients Actifs</div>
                            <div class="metric-change" id="clientsChange">+0%</div>
                        </div>
                    </div>
                </div>

                <!-- Graphiques -->
                <div class="charts-grid">
                    <div class="chart-card">
                        <div class="chart-header">
                            <h3>Évolution des Pesées</h3>
                            <div class="chart-controls">
                                <select id="evolutionPeriod" onchange="updateEvolutionChart()">
                                    <option value="daily">Par jour</option>
                                    <option value="weekly">Par semaine</option>
                                    <option value="monthly" selected>Par mois</option>
                                </select>
                            </div>
                        </div>
                        <div class="chart-container">
                            <canvas id="evolutionChart"></canvas>
                        </div>
                    </div>
                    
                    <div class="chart-card">
                        <div class="chart-header">
                            <h3>Répartition par Produit</h3>
                        </div>
                        <div class="chart-container">
                            <canvas id="productsChart"></canvas>
                        </div>
                    </div>
                </div>
                
                <div class="charts-grid">
                    <div class="chart-card">
                        <div class="chart-header">
                            <h3>Top 10 Clients</h3>
                        </div>
                        <div class="chart-container">
                            <canvas id="topClientsChart"></canvas>
                        </div>
                    </div>
                    
                    <div class="chart-card">
                        <div class="chart-header">
                            <h3>Performance par Site</h3>
                        </div>
                        <div class="chart-container">
                            <canvas id="sitesChart"></canvas>
                        </div>
                    </div>
                </div>
                
                <!-- Comparaisons périodiques -->
                <div class="comparison-section">
                    <div class="card">
                        <div class="card-header">
                            <h3>Comparaisons Périodiques</h3>
                        </div>
                        <div class="comparison-grid">
                            <div class="comparison-card">
                                <div class="comparison-title">Cette semaine vs Semaine précédente</div>
                                <div class="comparison-data" id="weekComparison">
                                    <div class="comparison-metric">
                                        <span>Pesées</span>
                                        <span class="comparison-value" id="weekWeighings">-</span>
                                    </div>
                                    <div class="comparison-metric">
                                        <span>Poids</span>
                                        <span class="comparison-value" id="weekWeight">-</span>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="comparison-card">
                                <div class="comparison-title">Ce mois vs Mois précédent</div>
                                <div class="comparison-data" id="monthComparison">
                                    <div class="comparison-metric">
                                        <span>Pesées</span>
                                        <span class="comparison-value" id="monthWeighings">-</span>
                                    </div>
                                    <div class="comparison-metric">
                                        <span>Poids</span>
                                        <span class="comparison-value" id="monthWeight">-</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                
                <!-- Tableau détaillé -->
                <div class="detailed-table-section">
                    <div class="card">
                        <div class="card-header">
                            <h3>Données Détaillées</h3>
                            <div class="table-controls">
                                <input type="text" id="tableSearch" placeholder="Rechercher..." onkeyup="filterDetailedTable()">
                                <select id="tableGroupBy" onchange="groupDetailedTable()">
                                    <option value="none">Sans groupement</option>
                                    <option value="client">Par client</option>
                                    <option value="product">Par produit</option>
                                    <option value="site">Par site</option>
                                    <option value="date">Par date</option>
                                </select>
                            </div>
                        </div>
                        <div class="table-container" style="max-height: 400px; overflow-y: auto;">
                            <table id="detailedReportsTable" class="reports-table">
                                <thead>
                                    <tr>
                                        <th onclick="sortTable(0)">Date 📅</th>
                                        <th onclick="sortTable(1)">Code 🔢</th>
                                        <th onclick="sortTable(2)">Client 👤</th>
                                        <th onclick="sortTable(3)">Produit 📦</th>
                                        <th onclick="sortTable(4)">Site 🏢</th>
                                        <th onclick="sortTable(5)">Poids ⚖️</th>
                                    </tr>
                                </thead>
                                <tbody id="detailedReportsBody">
                                    <tr><td colspan="6" class="loading-row">Chargement...</td></tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </section>
        </main>
    </div>

    <!-- Votre JavaScript existant adapté -->
    <script type="module">
        // Import de votre apiClient existant
        import { api } from './apiClient.js';
        window.api = api;
    </script>
    
    <script>
        // Variables globales
        const API_BASE_URL = 'https://serverkmaf.helioho.st/ozixsoftapp/pesees-api';
        let currentUser = null;
        let authToken = null;
        let peseesData = [];
        let searchOptions = {};

        // Fonctions API avec fallback si apiClient n'est pas disponible
        async function apiRequest(endpoint, options = {}) {
            if (window.api) {
                // Utiliser apiClient si disponible
                try {
                    const [path, queryStr] = endpoint.split('?', 2);
                    const query = {};
                    if (queryStr) {
                        new URLSearchParams(queryStr).forEach((v, k) => { query[k] = v; });
                    }
                    const method = options.method || 'GET';
                    const headers = options.headers || {};
                    let body = options.body;
                    if (typeof body === 'string') {
                        try { body = JSON.parse(body); } catch {}
                    }
                    const res = await window.api.request(path, {
                        method, headers, body, query
                    });
                    return { ok: res.ok, status: res.status, data: res.data, error: res.error };
                } catch (e) {
                    return { ok: false, status: 0, error: e.message };
                }
            } else {
                // Fallback direct fetch
                let url = endpoint.startsWith('http') ? endpoint : `${API_BASE_URL}/${endpoint}`;
                
                const defaultOptions = {
                    headers: {
                        'Content-Type': 'application/json',
                    }
                };
                
                if (authToken) {
                    defaultOptions.headers['Authorization'] = `Bearer ${authToken}`;
                }
                
                const finalOptions = { ...defaultOptions, ...options };
                
                try {
                    const response = await fetch(url, finalOptions);
                    const textResponse = await response.text();
                    
                    if (!textResponse.trim()) {
                        throw new Error('Réponse vide reçue de l\'API');
                    }
                    
                    const data = JSON.parse(textResponse);
                    return {
                        ok: response.ok,
                        status: response.status,
                        data: data
                    };
                } catch (error) {
                    return {
                        ok: false,
                        status: 0,
                        error: error.message
                    };
                }
            }
        }

        // Login avec animation
        document.getElementById('loginForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const loginText = document.getElementById('loginText');
            const loginSpinner = document.getElementById('loginSpinner');
            
            loginText.textContent = 'Connexion...';
            loginSpinner.style.display = 'inline-block';
            
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            
            try {
                const response = await apiRequest('auth.php', {
                    method: 'POST',
                    body: JSON.stringify({
                        action: 'login',
                        username: username,
                        password: password
                    })
                });
                
                if (response.ok && response.data.success) {
                    currentUser = response.data.data;
                    authToken = response.data.data.token;
                    
                    localStorage.setItem('authToken', authToken);
                    localStorage.setItem('currentUser', JSON.stringify(currentUser));
                    
                    // Animation de transition
                    document.getElementById('loginPage').style.opacity = '0';
                    document.getElementById('loginPage').style.transform = 'translateY(-20px)';
                    
                    setTimeout(() => {
                        document.getElementById('loginPage').style.display = 'none';
                        document.getElementById('dashboard').classList.add('active');
                        document.getElementById('userWelcome').textContent = `${currentUser.nom} (${currentUser.groupe})`;
                        initializeDashboard();
                    }, 300);
                    
                } else {
                    showLoginError(response.data?.message || 'Erreur de connexion');
                }
            } catch (error) {
                showLoginError('Erreur de connexion au serveur');
            } finally {
                loginText.textContent = 'Se connecter';
                loginSpinner.style.display = 'none';
            }
        });

        function showLoginError(message) {
            const errorDiv = document.getElementById('loginError');
            errorDiv.textContent = message;
            errorDiv.style.display = 'block';
            errorDiv.style.animation = 'none';
            setTimeout(() => errorDiv.style.animation = 'slideUp 0.3s ease-out', 10);
        }

        // Logout avec animation
        async function logout() {
            try {
                if (authToken) {
                    await apiRequest('auth.php', {
                        method: 'POST',
                        body: JSON.stringify({
                            action: 'logout',
                            token: authToken
                        })
                    });
                }
            } catch (error) {
                console.error('Erreur lors de la déconnexion:', error);
            } finally {
                currentUser = null;
                authToken = null;
                localStorage.removeItem('authToken');
                localStorage.removeItem('currentUser');
                
                document.getElementById('dashboard').classList.remove('active');
                document.getElementById('loginPage').style.display = 'flex';
                document.getElementById('loginPage').style.opacity = '1';
                document.getElementById('loginPage').style.transform = 'translateY(0)';
                document.getElementById('username').value = '';
                document.getElementById('password').value = '';
                document.getElementById('loginError').style.display = 'none';
            }
        }

        // Navigation avec animation
        function showSection(sectionName, element) {
            // Désactiver tous les onglets
            document.querySelectorAll('.nav-tab').forEach(tab => {
                tab.classList.remove('active');
            });
            
            // Masquer toutes les sections avec animation
            document.querySelectorAll('.content-section').forEach(section => {
                if (section.classList.contains('active')) {
                    section.style.opacity = '0';
                    section.style.transform = 'translateY(10px)';
                    setTimeout(() => {
                        section.classList.remove('active');
                    }, 150);
                }
            });
            
            // Activer l'onglet sélectionné
            if (element) element.classList.add('active');
            
            // Afficher la nouvelle section avec animation
            setTimeout(() => {
                const targetSection = document.getElementById(sectionName);
                targetSection.classList.add('active');
                targetSection.style.opacity = '1';
                targetSection.style.transform = 'translateY(0)';
                
                // Charger les données spécifiques à la section
                if (sectionName === 'search') {
                    loadSearchOptions();
                    initializeSearchForm();
                } else if (sectionName === 'reports') {
                    initializeReports();
                }
            }, 200);
        }

        // Initialisation du dashboard
        async function initializeDashboard() {
            try {
                await loadStatistics();
                await loadSearchResults();
                await createCharts();
                initializeSearchForm();
                
                // Démarrer l'auto-rafraîchissement des statistiques
                startStatsRefresh();
            } catch (error) {
                console.error('Erreur lors de l\'initialisation du dashboard:', error);
            }
        }

        // Charger les statistiques
        async function loadStatistics() {
            try {
                const response = await apiRequest('pesees.php?action=stats');
                
                if (response.ok && response.data.success) {
                    const stats = response.data.data;
                    document.getElementById('totalPesees').textContent = stats.totalPesees || 0;
                    document.getElementById('poidsTotal').textContent = (stats.poidsTotal || 0) + ' T';
                    document.getElementById('peseesAujourdhui').textContent = stats.peseesAujourdhui || 0;
                    document.getElementById('clientsActifs').textContent = stats.clientsActifs || 0;
                } else {
                    console.error('Erreur chargement statistiques:', response.error);
                }
            } catch (error) {
                console.error('Erreur lors du chargement des statistiques:', error);
            }
        }

        // Rafraîchir les statistiques
        async function refreshStatistics() {
            await loadStatistics();
            console.log('Statistiques rafraîchies:', new Date().toLocaleString());
        }

        // Auto-rafraîchissement des statistiques toutes les 30 secondes
        let statsRefreshInterval;
        
        function startStatsRefresh() {
            // Rafraîchir immédiatement
            refreshStatistics();
            
            // Puis toutes les 30 secondes
            statsRefreshInterval = setInterval(refreshStatistics, 30000);
            console.log('Auto-rafraîchissement des statistiques activé (30s)');
        }
        
        function stopStatsRefresh() {
            if (statsRefreshInterval) {
                clearInterval(statsRefreshInterval);
                statsRefreshInterval = null;
                console.log('Auto-rafraîchissement des statistiques arrêté');
            }
        }

        // Charger les options de recherche
        async function loadSearchOptions() {
            try {
                document.getElementById('searchLoading').style.display = 'block';
                
                const response = await apiRequest('pesees.php?action=options');
                
                if (response.ok && response.data.success) {
                    searchOptions = response.data.data;
                    
                    // Remplir les datalists
                    populateDatalist('clientsList', searchOptions.clients || []);
                    populateDatalist('fournisseursList', searchOptions.fournisseurs || []);
                    populateDatalist('produitsList', searchOptions.produits || []);
                    populateDatalist('codesSitesList', searchOptions.codesSites || []);
                    populateDatalist('sitesList', searchOptions.sites || []);
                    
                    console.log('Options de recherche chargées:', searchOptions);
                } else {
                    console.error('Erreur chargement options:', response.error);
                }
            } catch (error) {
                console.error('Erreur lors du chargement des options:', error);
            } finally {
                document.getElementById('searchLoading').style.display = 'none';
            }
        }

        function populateDatalist(datalistId, options) {
            const datalist = document.getElementById(datalistId);
            datalist.innerHTML = '';
            
            options.forEach(option => {
                const optionElement = document.createElement('option');
                optionElement.value = option;
                datalist.appendChild(optionElement);
            });
        }

        // Fonction de recherche
        async function rechercher() {
            try {
                const criteria = {
                    codePesee: document.getElementById('codePesee').value.trim(),
                    numTicket: document.getElementById('numTicket').value.trim(),
                    client: document.getElementById('client').value.trim(),
                    fournisseur: document.getElementById('fournisseur').value.trim(),
                    codeSite: document.getElementById('codeSite').value.trim(),
                    site: document.getElementById('site').value.trim(),
                    dateDebut: document.getElementById('dateDebut').value,
                    dateFin: document.getElementById('dateFin').value,
                    produit: document.getElementById('produit').value.trim()
                };
                
                console.log('Critères de recherche:', criteria);
                
                // Construire les paramètres de requête
                const params = new URLSearchParams();
                params.append('action', 'search');
                
                Object.keys(criteria).forEach(key => {
                    if (criteria[key]) {
                        params.append(key, criteria[key]);
                    }
                });
                
                console.log('URL de recherche:', 'pesees.php?' + params.toString());
                
                const response = await apiRequest('pesees.php?' + params.toString());
                
                console.log('Réponse de recherche:', response);
                
                if (response.ok && response.data.success) {
                    peseesData = response.data.data || [];
                    console.log('Données reçues:', peseesData.length, 'résultats');
                    
                    displayResults(peseesData);
                    
                    console.log('Recherche terminée avec', peseesData.length, 'résultats');
                } else {
                    console.error('Erreur recherche:', response.error);
                    
                    peseesData = [];
                    displayResults(peseesData);
                    
                    const resultsInfo = document.getElementById('resultsInfo');
                    resultsInfo.textContent = `Erreur: ${response.error || 'Erreur inconnue'}`;
                    resultsInfo.className = 'alert alert-error';
                    resultsInfo.style.display = 'block';
                }
            } catch (error) {
                console.error('Erreur lors de la recherche:', error);
                
                peseesData = [];
                displayResults(peseesData);
                
                const resultsInfo = document.getElementById('resultsInfo');
                resultsInfo.textContent = `Erreur: ${error.message}`;
                resultsInfo.className = 'alert alert-error';
                resultsInfo.style.display = 'block';
            }
        }

        function displayResults(data) {
            const tbody = document.getElementById('resultsBody');
            tbody.innerHTML = '';
            
            console.log('Affichage des résultats:', data ? data.length : 0, 'éléments');
            
            if (!data || data.length === 0) {
                tbody.innerHTML = '<tr><td colspan="8" style="text-align: center; padding: 20px; color: var(--text-secondary);">Aucun résultat trouvé</td></tr>';
                console.log('Aucun résultat à afficher');
                
                const resultsInfo = document.getElementById('resultsInfo');
                resultsInfo.textContent = '0 résultat(s) trouvé(s)';
                resultsInfo.className = 'alert alert-info';
                resultsInfo.style.display = 'block';
                return;
            }
            
            data.forEach((item, index) => {
                const row = tbody.insertRow();
                row.innerHTML = `
                    <td>${item.CodePesee || '-'}</td>
                    <td>${item.NumTicket || '-'}</td>
                    <td>${item.dmv || '-'}</td>
                    <td>${item.NomClient || '-'}</td>
                    <td>${item.NomFournisseur || '-'}</td>
                    <td>${item.NomProduit || '-'}</td>
                    <td>${(item.PoidsNet || 0).toLocaleString()}</td>
                    <td>
                        <button class="btn btn-secondary btn-sm" onclick="selectForTicket('${item.NumTicket || item.CodePesee}')">
                            Ticket
                        </button>
                    </td>
                `;
                console.log(`Ligne ${index + 1} ajoutée:`, item.CodePesee, item.NumTicket);
            });
            
            const resultsInfo = document.getElementById('resultsInfo');
            resultsInfo.textContent = `${data.length} résultat(s) trouvé(s)`;
            resultsInfo.className = 'alert alert-info';
            resultsInfo.style.display = 'block';
            
            console.log('Tableau mis à jour avec', data.length, 'lignes');
        }

        function resetSearch() {
            document.getElementById('searchForm').reset();
            
            const resultsInfo = document.getElementById('resultsInfo');
            resultsInfo.style.display = 'none';
            
            initializeSearchForm();
            
            console.log('Formulaire de recherche réinitialisé');
        }

        async function loadSearchResults() {
            try {
                const response = await apiRequest('pesees.php?action=list&limit=50');
                
                if (response.ok && response.data.success) {
                    peseesData = response.data.data.pesees || response.data.data;
                    displayResults(peseesData);
                    console.log('Résultats par défaut chargés:', peseesData.length, 'pesées');
                } else {
                    console.error('Erreur chargement pesées:', response.error);
                    const tbody = document.getElementById('resultsBody');
                    tbody.innerHTML = `<tr><td colspan="8" style="text-align: center; padding: 20px; color: #721c24;">Erreur: ${response.error || 'Impossible de charger les données'}</td></tr>`;
                }
            } catch (error) {
                console.error('Erreur lors du chargement des pesées:', error);
                const tbody = document.getElementById('resultsBody');
                tbody.innerHTML = '<tr><td colspan="8" style="text-align: center; padding: 20px; color: #721c24;">Erreur lors du chargement des données</td></tr>';
            }
        }

        async function initializeSearchForm() {
            // Essayer de récupérer la date la plus récente depuis l'API
            try {
                const response = await apiRequest('pesees.php?action=list&limit=1');
                let defaultDate = new Date().toISOString().split('T')[0]; // Fallback à aujourd'hui
                
                if (response.ok && response.data.success) {
                    // Correction: les pesées sont dans response.data.data.pesees
                    const pesees = (response.data.data && response.data.data.pesees) || response.data.data || [];
                    if (pesees.length > 0) {
                        const latestEntry = pesees[0];
                        if (latestEntry.dmv) {
                            defaultDate = latestEntry.dmv;
                            console.log('📅 Date la plus récente trouvée:', defaultDate);
                        }
                    }
                }
                
                const dateDebutField = document.getElementById('dateDebut');
                const dateFinField = document.getElementById('dateFin');
                
                let shouldSearch = false;
                
                if (!dateDebutField.value) {
                    dateDebutField.value = defaultDate;
                    shouldSearch = true;
                }
                
                if (!dateFinField.value) {
                    dateFinField.value = defaultDate;
                    shouldSearch = true;
                }
                
                console.log('📅 Dates par défaut définies:', defaultDate, '- Recherche automatique:', shouldSearch);
                
            } catch (error) {
                console.warn('⚠️ Impossible de récupérer la date par défaut:', error);
                // Fallback classique
                const today = new Date();
                const todayString = today.toISOString().split('T')[0];
                
                document.getElementById('dateDebut').value = todayString;
                document.getElementById('dateFin').value = todayString;
            }
            
            if (shouldSearch) {
                setTimeout(async () => {
                    console.log('Lancement de la recherche automatique...');
                    await rechercher();
                }, 300);
            }
        }

        function selectForTicket(identifier) {
            console.log('Sélection de ticket:', identifier);
            
            const cleanIdentifier = String(identifier).trim();
            
            if (!cleanIdentifier || cleanIdentifier === 'undefined' || cleanIdentifier === 'null') {
                alert('Identifiant de ticket invalide');
                return;
            }
            
            document.getElementById('ticketSearch').value = cleanIdentifier;
            showSection('ticket');
            
            setTimeout(() => {
                loadTicket();
            }, 100);
        }

        async function loadTicket() {
            try {
                const searchValue = document.getElementById('ticketSearch').value.trim();
                
                if (!searchValue) {
                    alert('Veuillez entrer un numéro de ticket ou code pesée');
                    return;
                }
                
                console.log('🔍 Recherche de ticket:', searchValue);
                showTemporaryMessage('🔍 Recherche du ticket en cours...', 'info');
                
                // Utilisation de l'endpoint debug qui fonctionne
                const url = `debug_ticket.php?numTicket=${encodeURIComponent(searchValue)}`;
                console.log('📡 URL de recherche:', url);
                
                const response = await fetch(url);
                const text = await response.text();
                console.log('📄 Réponse brute:', text);
                
                // Extraire le JSON de la réponse
                console.log('📄 Lignes de la réponse:', text.split('\n'));
                const lines = text.split('\n');
                
                // Chercher la ligne qui contient du JSON (commence par { ou contient success)
                const jsonLine = lines.find(line => {
                    const trimmed = line.trim();
                    return trimmed.startsWith('{') && (trimmed.includes('success') || trimmed.includes('data'));
                });
                
                console.log('📄 Ligne JSON trouvée:', jsonLine);
                let ticketData = null;
                
                if (jsonLine) {
                    try {
                        ticketData = JSON.parse(jsonLine.trim());
                        console.log('📊 JSON parsé avec succès:', ticketData);
                    } catch (e) {
                        console.error('Erreur parsing JSON:', e);
                        console.error('Ligne problématique:', jsonLine);
                    }
                } else {
                    console.log('❌ Aucune ligne JSON trouvée dans:', lines);
                }
                console.log('📊 Données extraites:', ticketData);
                
                if (ticketData && ticketData.success && ticketData.data) {
                    const ticket = ticketData.data;
                    console.log('Ticket trouvé:', ticket);
                    
                    document.getElementById('ticketDate').textContent = ticket.dmv || 'N/A';
                    document.getElementById('ticketNumber').textContent = ticket.NumTicket || 'N/A';
                    document.getElementById('ticketClient').textContent = ticket.NomClient || 'N/A';
                    document.getElementById('ticketFournisseur').textContent = ticket.NomFournisseur || 'N/A';
                    document.getElementById('ticketProduit').textContent = ticket.NomProduit || 'N/A';
                    document.getElementById('ticketProvenance').textContent = ticket.Provenance || 'N/A';
                    document.getElementById('ticketDestination').textContent = ticket.Destination || 'N/A';
                    document.getElementById('ticketVehicule').textContent = ticket.Immatriculation || 'N/A';
                    document.getElementById('ticketPoids1').textContent = (ticket.Poids1 || 0).toLocaleString() + ' kg';
                    document.getElementById('ticketPoids2').textContent = (ticket.Poids2 || 0).toLocaleString() + ' kg';
                    document.getElementById('ticketPoidsNet').textContent = (ticket.PoidsNet || 0).toLocaleString() + ' kg';
                    document.getElementById('ticketPeseur').textContent = ticket.NomPeseur1 || 'N/A';
                    document.getElementById('ticketSite').textContent = ticket.NomSite || ticket.CodeSite || 'N/A';
                    
                    console.log('✅ Ticket mis à jour dans l\'interface');
                    showTemporaryMessage('✅ Ticket chargé avec succès', 'success');
                } else {
                    console.error('❌ Erreur chargement ticket:', ticketData);
                    const errorMsg = ticketData && ticketData.message ? ticketData.message : 'Ticket non trouvé';
                    showTemporaryMessage(`❌ ${errorMsg}`, 'error');
                    
                    // Debug: montrer ce qui a été cherché
                    console.log(`🔍 Recherché: "${searchValue}"`);
                    console.log('📊 Réponse complète:', text);
                }
            } catch (error) {
                console.error('❌ Erreur lors du chargement du ticket:', error);
                showTemporaryMessage(`❌ Erreur: ${error.message}`, 'error');
            }
        }

        function exportResults() {
            if (!peseesData || peseesData.length === 0) {
                alert('Aucune donnée à exporter');
                return;
            }
            
            const headers = ['Code Pesée', 'N° Ticket', 'Date', 'Client', 'Fournisseur', 'Produit', 'Poids Net (kg)'];
            const csvContent = [
                headers.join(','),
                ...peseesData.map(item => [
                    item.CodePesee || '',
                    item.NumTicket || '',
                    item.dmv || '',
                    item.NomClient || '',
                    item.NomFournisseur || '',
                    item.NomProduit || '',
                    item.PoidsNet || 0
                ].join(','))
            ].join('\n');
            
            const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
            const link = document.createElement('a');
            const url = URL.createObjectURL(blob);
            link.setAttribute('href', url);
            link.setAttribute('download', `pesees_export_${new Date().toISOString().split('T')[0]}.csv`);
            link.style.visibility = 'hidden';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }

        // Fonctions de graphiques
        async function createCharts() {
            try {
                const response = await apiRequest('pesees.php?action=charts');
                
                if (response.ok && response.data.success) {
                    const chartData = response.data.data;
                    
                    createEvolutionChart(chartData.evolutionMensuelle || []);
                    createProduitsChart(chartData.repartitionProduits || []);
                } else {
                    console.error('Erreur chargement graphiques:', response.error);
                    createDefaultCharts();
                }
            } catch (error) {
                console.error('Erreur lors de la création des graphiques:', error);
                createDefaultCharts();
            }
        }
        
        function createEvolutionChart(data) {
            const ctx1 = document.getElementById('evolutionChart');
            if (!ctx1) return;
            
            const labels = data.map(item => item.mois || 'N/A');
            const values = data.map(item => item.nombre || 0);
            
            new Chart(ctx1, {
                type: 'line',
                data: {
                    labels: labels.length > 0 ? labels : ['Jan', 'Fév', 'Mar', 'Avr', 'Mai', 'Jun'],
                    datasets: [{
                        label: 'Nombre de Pesées',
                        data: values.length > 0 ? values : [45, 52, 48, 61, 58, 67],
                        borderColor: '#667eea',
                        backgroundColor: 'rgba(102, 126, 234, 0.1)',
                        tension: 0.4,
                        fill: true
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        title: {
                            display: true,
                            text: 'Evolution des Pesées par Mois',
                            color: '#f1f5f9'
                        },
                        legend: {
                            labels: {
                                color: '#f1f5f9'
                            }
                        }
                    },
                    scales: {
                        x: {
                            ticks: {
                                color: '#94a3b8'
                            },
                            grid: {
                                color: 'rgba(148, 163, 184, 0.1)'
                            }
                        },
                        y: {
                            ticks: {
                                color: '#94a3b8'
                            },
                            grid: {
                                color: 'rgba(148, 163, 184, 0.1)'
                            }
                        }
                    }
                }
            });
        }
        
        function createProduitsChart(data) {
            const ctx2 = document.getElementById('produitsChart');
            if (!ctx2) return;
            
            const labels = data.map(item => item.produit || 'N/A');
            const values = data.map(item => item.nombre || 0);
            
            new Chart(ctx2, {
                type: 'doughnut',
                data: {
                    labels: labels.length > 0 ? labels : ['CACAO', 'CAFE', 'COTON', 'CAJOU'],
                    datasets: [{
                        data: values.length > 0 ? values : [45, 25, 20, 10],
                        backgroundColor: ['#667eea', '#764ba2', '#f093fb', '#f5576c']
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        title: {
                            display: true,
                            text: 'Répartition par Produit',
                            color: '#f1f5f9'
                        },
                        legend: {
                            labels: {
                                color: '#f1f5f9'
                            }
                        }
                    }
                }
            });
        }

        function createReportCharts() {
            createMonthlyChart();
            createClientsChart();
        }
        
        function createMonthlyChart() {
            const ctx3 = document.getElementById('monthlyChart');
            if (!ctx3) return;
            
            new Chart(ctx3, {
                type: 'bar',
                data: {
                    labels: ['Sem 1', 'Sem 2', 'Sem 3', 'Sem 4'],
                    datasets: [{
                        label: 'Tonnage',
                        data: [120, 145, 130, 155],
                        backgroundColor: '#667eea'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        title: {
                            display: true,
                            text: 'Tonnage par Semaine',
                            color: '#f1f5f9'
                        },
                        legend: {
                            labels: {
                                color: '#f1f5f9'
                            }
                        }
                    },
                    scales: {
                        x: {
                            ticks: {
                                color: '#94a3b8'
                            },
                            grid: {
                                color: 'rgba(148, 163, 184, 0.1)'
                            }
                        },
                        y: {
                            ticks: {
                                color: '#94a3b8'
                            },
                            grid: {
                                color: 'rgba(148, 163, 184, 0.1)'
                            }
                        }
                    }
                }
            });
        }
        
        function createClientsChart() {
            const ctx4 = document.getElementById('clientsChart');
            if (!ctx4) return;
            
            new Chart(ctx4, {
                type: 'bar',
                data: {
                    labels: ['EXEMPLE SARL', 'SOCIETE XYZ', 'ENTREPRISE ABC'],
                    datasets: [{
                        label: 'Nombre de Pesées',
                        data: [25, 18, 15],
                        backgroundColor: ['#667eea', '#764ba2', '#f093fb']
                    }]
                },
                options: {
                    indexAxis: 'y',
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        title: {
                            display: true,
                            text: 'Top Clients par Nombre de Pesées',
                            color: '#f1f5f9'
                        },
                        legend: {
                            labels: {
                                color: '#f1f5f9'
                            }
                        }
                    },
                    scales: {
                        x: {
                            ticks: {
                                color: '#94a3b8'
                            },
                            grid: {
                                color: 'rgba(148, 163, 184, 0.1)'
                            }
                        },
                        y: {
                            ticks: {
                                color: '#94a3b8'
                            },
                            grid: {
                                color: 'rgba(148, 163, 184, 0.1)'
                            }
                        }
                    }
                }
            });
        }
        
        function createDefaultCharts() {
            createEvolutionChart([]);
            createProduitsChart([]);
        }

        // Vérifier session existante
        async function checkExistingSession() {
            const savedToken = localStorage.getItem('authToken');
            const savedUser = localStorage.getItem('currentUser');
            
            if (savedToken && savedUser) {
                try {
                    authToken = savedToken;
                    
                    const response = await apiRequest('auth.php', {
                        method: 'POST',
                        body: JSON.stringify({
                            action: 'verify',
                            token: authToken
                        })
                    });
                    
                    if (response.ok && response.data.success) {
                        currentUser = JSON.parse(savedUser);
                        
                        document.getElementById('loginPage').style.display = 'none';
                        document.getElementById('dashboard').classList.add('active');
                        document.getElementById('userWelcome').textContent = `${currentUser.nom} (${currentUser.groupe})`;
                        
                        await initializeDashboard();
                        return true;
                    }
                } catch (error) {
                    console.error('Token invalide:', error);
                }
            }
            
            localStorage.removeItem('authToken');
            localStorage.removeItem('currentUser');
            authToken = null;
            currentUser = null;
            
            return false;
        }

        // ===============================================
        // SERVICE WORKER - FONCTIONNALITÉS PWA
        // ===============================================
        
        // Variables pour le Service Worker
        let swRegistration = null;
        let isOnline = navigator.onLine;
        
        // Enregistrer le Service Worker
        async function registerServiceWorker() {
            if ('serviceWorker' in navigator) {
                try {
                    console.log('🔧 Enregistrement du Service Worker...');
                    
                    swRegistration = await navigator.serviceWorker.register('./sw.js', {
                        scope: './'
                    });
                    
                    console.log('✅ Service Worker enregistré:', swRegistration.scope);
                    
                    // Écouter les mises à jour
                    swRegistration.addEventListener('updatefound', () => {
                        console.log('🔄 Nouvelle version disponible');
                        showUpdateAvailable();
                    });
                    
                    // Écouter les messages du Service Worker
                    navigator.serviceWorker.addEventListener('message', event => {
                        console.log('💬 Message du SW:', event.data);
                        
                        if (event.data.type === 'SW_ACTIVATED') {
                            showOfflineCapability();
                        }
                    });
                    
                } catch (error) {
                    console.error('❌ Erreur Service Worker:', error);
                }
            } else {
                console.warn('⚠️ Service Worker non supporté');
            }
        }
        
        // Afficher la notification de capacité hors ligne
        function showOfflineCapability() {
            const notification = document.createElement('div');
            notification.innerHTML = `
                <div style="
                    position: fixed; 
                    top: 20px; 
                    right: 20px; 
                    background: linear-gradient(135deg, #28a745, #20c997);
                    color: white; 
                    padding: 15px 20px; 
                    border-radius: 10px; 
                    box-shadow: 0 10px 25px rgba(40, 167, 69, 0.3);
                    z-index: 10000;
                    font-weight: 500;
                    animation: slideInRight 0.5s ease;
                ">
                    📱 Mode hors ligne activé !<br>
                    <small style="opacity: 0.9;">Votre app fonctionne maintenant sans internet</small>
                </div>
                <style>
                    @keyframes slideInRight {
                        from { transform: translateX(100%); opacity: 0; }
                        to { transform: translateX(0); opacity: 1; }
                    }
                </style>
            `;
            
            document.body.appendChild(notification);
            
            // Supprimer après 4 secondes
            setTimeout(() => {
                notification.style.animation = 'slideInRight 0.5s ease reverse';
                setTimeout(() => notification.remove(), 500);
            }, 4000);
        }
        
        // Afficher la notification de mise à jour
        function showUpdateAvailable() {
            const updateBar = document.createElement('div');
            updateBar.innerHTML = `
                <div style="
                    position: fixed; 
                    bottom: 0; 
                    left: 0; 
                    right: 0; 
                    background: linear-gradient(135deg, #667eea, #764ba2);
                    color: white; 
                    padding: 15px; 
                    text-align: center;
                    box-shadow: 0 -5px 20px rgba(102, 126, 234, 0.3);
                    z-index: 10000;
                ">
                    🚀 Nouvelle version disponible ! 
                    <button onclick="updateApp()" style="
                        margin-left: 15px;
                        background: rgba(255,255,255,0.2);
                        border: 1px solid rgba(255,255,255,0.3);
                        color: white;
                        padding: 8px 16px;
                        border-radius: 20px;
                        cursor: pointer;
                    ">
                        Mettre à jour
                    </button>
                    <button onclick="this.parentElement.parentElement.remove()" style="
                        margin-left: 10px;
                        background: transparent;
                        border: none;
                        color: white;
                        cursor: pointer;
                        opacity: 0.7;
                    ">
                        ✕
                    </button>
                </div>
            `;
            
            document.body.appendChild(updateBar);
        }
        
        // Mettre à jour l'application
        function updateApp() {
            if (swRegistration && swRegistration.waiting) {
                swRegistration.waiting.postMessage({ type: 'SKIP_WAITING' });
                window.location.reload();
            }
        }
        
        // ===============================================
        // GESTION DES NOTIFICATIONS PUSH
        // ===============================================
        
        let notificationPanelVisible = false;
        
        // Basculer le panneau de notifications
        function toggleNotificationPanel() {
            if (notificationPanelVisible) {
                hideNotificationPanel();
            } else {
                showNotificationPanel();
            }
        }
        
        // Afficher le panneau de notifications
        function showNotificationPanel() {
            // Supprimer le panneau existant s'il y en a un
            const existingPanel = document.querySelector('.notification-panel');
            if (existingPanel) {
                existingPanel.remove();
            }
            
            // Créer le nouveau panneau
            const panel = notificationManager.createNotificationPanel();
            document.body.appendChild(panel);
            
            notificationPanelVisible = true;
            
            // Clic en dehors pour fermer
            setTimeout(() => {
                document.addEventListener('click', closeNotificationPanelOnClickOutside);
            }, 100);
        }
        
        // Masquer le panneau de notifications
        function hideNotificationPanel() {
            const panel = document.querySelector('.notification-panel');
            if (panel) {
                panel.style.animation = 'slideInRight 0.3s ease reverse';
                setTimeout(() => panel.remove(), 300);
            }
            
            notificationPanelVisible = false;
            document.removeEventListener('click', closeNotificationPanelOnClickOutside);
        }
        
        // Fonctions de contrôle de surveillance
        function toggleNotificationWatch() {
            const button = document.getElementById('watchToggle');
            const icon = document.getElementById('watchIcon');
            
            if (!window.notificationWatcher) {
                console.error('NotificationWatcher non disponible');
                return;
            }
            
            const status = notificationWatcher.getStatus();
            
            if (status.isActive) {
                // Arrêter la surveillance
                notificationWatcher.stop();
                button.classList.remove('active');
                icon.textContent = '🔍';
                button.title = 'Surveillance arrêtée - Cliquer pour redémarrer';
                console.log('🛑 Surveillance arrêtée par l\'utilisateur');
                
                // Notification
                showTemporaryMessage('🛑 Surveillance des nouvelles pesées arrêtée', 'warning');
            } else {
                // Démarrer la surveillance
                notificationWatcher.start();
                button.classList.add('active');
                icon.textContent = '👁️';
                button.title = 'Surveillance active - Cliquer pour arrêter';
                console.log('🚀 Surveillance démarrée par l\'utilisateur');
                
                // Notification
                showTemporaryMessage('🚀 Surveillance des nouvelles pesées active!', 'success');
            }
        }
        
        // Fonction de test manuel de surveillance
        function testNotificationWatch() {
            if (!window.notificationWatcher) {
                showTemporaryMessage('⚠️ NotificationWatcher non disponible', 'error');
                return;
            }
            
            console.log('🧪 Test manuel de surveillance déclenché');
            showTemporaryMessage('🧪 Test surveillance en cours...', 'info');
            
            // Forcer une vérification immédiate
            notificationWatcher.checkForNewPesees();
        }
        
        // Fonction de test de notification forcée
        function forceTestNotification() {
            if (!window.notificationWatcher) {
                showTemporaryMessage('⚠️ NotificationWatcher non disponible', 'error');
                return;
            }
            
            console.log('🧪 SIMULATION: Forcer une nouvelle pesée pour test...');
            
            // Simuler une nouvelle pesée en décrémentant l'ID de référence
            const currentId = notificationWatcher.lastPeseeId;
            console.log(`🧪 ID actuel: ${currentId}, simulation: ${currentId - 1}`);
            notificationWatcher.lastPeseeId = currentId - 1;
            
            // Déclencher immédiatement une vérification
            showTemporaryMessage('🧪 Simulation nouvelle pesée...', 'info');
            notificationWatcher.checkForNewPesees();
        }
        
        // Fonction de reset de l'ID de référence
        async function resetWatcherId() {
            if (!window.notificationWatcher) {
                showTemporaryMessage('⚠️ NotificationWatcher non disponible', 'error');
                return;
            }
            
            console.log('🔄 RESET: Réinitialisation de l\'ID de référence...');
            showTemporaryMessage('🔄 Reset de l\'ID en cours...', 'info');
            
            try {
                const newId = await notificationWatcher.resetLastPeseeId();
                showTemporaryMessage(`✅ ID mis à jour: ${newId}`, 'success');
                console.log('✅ Reset terminé avec succès');
            } catch (error) {
                console.error('❌ Erreur reset:', error);
                showTemporaryMessage('❌ Erreur lors du reset', 'error');
            }
        }
        
        // Test direct de l'API (debug)
        async function testDirectAPI() {
            console.log('🔍 === TEST DIRECT API ===');
            showTemporaryMessage('🔍 Test API en cours...', 'info');
            
            try {
                // Test 1: Fetch direct sans cache
                console.log('📡 Test 1: Fetch direct...');
                const fetchResponse = await fetch('./pesees.php?action=list&limit=3&_t=' + Date.now(), {
                    cache: 'no-cache',
                    headers: { 'Cache-Control': 'no-cache' }
                });
                const fetchData = await fetchResponse.json();
                console.log('📡 Réponse fetch direct:', fetchData);
                
                if (fetchData.success && fetchData.data && fetchData.data.pesees) {
                    const pesees = fetchData.data.pesees;
                    console.log('📊 IDs des 3 dernières pesées (fetch):');
                    pesees.forEach((p, i) => console.log(`   ${i+1}. ID=${p.ID}, Code=${p.CodePesee}`));
                    
                    const maxId = Math.max(...pesees.map(p => parseInt(p.ID)));
                    console.log(`🔢 ID maximum trouvé: ${maxId}`);
                    showTemporaryMessage(`📊 ID max trouvé: ${maxId}`, maxId > 114 ? 'success' : 'warning');
                } else {
                    console.error('❌ Structure API inattendue:', fetchData);
                }
                
                // Test 2: ApiRequest normal  
                console.log('📡 Test 2: ApiRequest...');
                const apiResponse = await apiRequest('pesees.php?action=list&limit=3');
                console.log('📡 Réponse apiRequest:', apiResponse);
                
            } catch (error) {
                console.error('❌ Erreur test API:', error);
                showTemporaryMessage('❌ Erreur test API', 'error');
            }
        }
        
        function showTemporaryMessage(message, type = 'info') {
            const colors = {
                success: 'linear-gradient(135deg, #10b981, #047857)',
                warning: 'linear-gradient(135deg, #f59e0b, #d97706)',
                info: 'linear-gradient(135deg, #3b82f6, #1d4ed8)',
                error: 'linear-gradient(135deg, #ef4444, #dc2626)'
            };
            
            const notification = document.createElement('div');
            notification.style.cssText = `
                position: fixed;
                bottom: 20px;
                left: 50%;
                transform: translateX(-50%);
                background: ${colors[type] || colors.info};
                color: white;
                padding: 12px 20px;
                border-radius: 25px;
                box-shadow: 0 8px 20px rgba(0,0,0,0.3);
                z-index: 10002;
                font-weight: 500;
                font-size: 14px;
                animation: slideUp 0.3s ease-out;
                max-width: 80vw;
                text-align: center;
            `;
            notification.textContent = message;
            
            document.body.appendChild(notification);
            
            setTimeout(() => {
                if (notification.parentElement) {
                    notification.remove();
                }
            }, 3000);
        }
        
        // Fermer le panneau en cliquant à l'extérieur
        function closeNotificationPanelOnClickOutside(event) {
            const panel = document.querySelector('.notification-panel');
            const button = document.querySelector('.btn-notifications');
            
            if (panel && !panel.contains(event.target) && !button.contains(event.target)) {
                hideNotificationPanel();
            }
        }
        
        // Mettre à jour le badge de notification
        function updateNotificationBadge(count = 0) {
            const badge = document.getElementById('notificationBadge');
            if (badge) {
                if (count > 0) {
                    badge.textContent = count > 99 ? '99+' : count;
                    badge.style.display = 'flex';
                } else {
                    badge.style.display = 'none';
                }
            }
        }
        
        // Écouter les notifications du service worker
        function setupNotificationListeners() {
            if ('serviceWorker' in navigator) {
                navigator.serviceWorker.addEventListener('message', event => {
                    if (event.data && event.data.type === 'NOTIFICATION_RECEIVED') {
                        console.log('🔔 Notification reçue via SW:', event.data);
                        
                        // Mettre à jour le badge
                        const currentCount = parseInt(document.getElementById('notificationBadge')?.textContent || '0');
                        updateNotificationBadge(currentCount + 1);
                        
                        // Afficher notification visuelle si l'app est active
                        if (document.visibilityState === 'visible') {
                            showInAppNotification(event.data);
                        }
                    }
                });
            }
        }
        
        // Afficher notification dans l'app
        function showInAppNotification(data) {
            const notification = document.createElement('div');
            notification.innerHTML = `
                <div style="
                    position: fixed;
                    top: 80px;
                    right: 20px;
                    background: linear-gradient(135deg, #667eea, #764ba2);
                    color: white;
                    padding: 15px 20px;
                    border-radius: 10px;
                    box-shadow: 0 10px 25px rgba(102, 126, 234, 0.3);
                    z-index: 10001;
                    max-width: 300px;
                    animation: slideInRight 0.5s ease;
                    cursor: pointer;
                " onclick="this.remove()">
                    <div style="font-weight: 600; margin-bottom: 5px;">
                        ${data.title || '🔔 Nouvelle notification'}
                    </div>
                    <div style="font-size: 14px; opacity: 0.9;">
                        ${data.body || 'Cliquez pour fermer'}
                    </div>
                </div>
            `;
            
            document.body.appendChild(notification);
            
            // Auto-suppression après 5 secondes
            setTimeout(() => {
                if (notification.parentNode) {
                    notification.style.animation = 'slideInRight 0.3s ease reverse';
                    setTimeout(() => notification.remove(), 300);
                }
            }, 5000);
        }
        
        // Détecter les changements de connexion
        function setupConnectivityDetection() {
            window.addEventListener('online', () => {
                isOnline = true;
                console.log('🌐 Connexion rétablie');
                showConnectionStatus('Connexion rétablie', '#28a745');
            });
            
            window.addEventListener('offline', () => {
                isOnline = false;
                console.log('📶 Hors ligne');
                showConnectionStatus('Mode hors ligne', '#ffc107');
            });
        }
        
        // Afficher le statut de connexion
        function showConnectionStatus(message, color) {
            const statusBar = document.createElement('div');
            statusBar.innerHTML = `
                <div style="
                    position: fixed;
                    top: 0;
                    left: 0;
                    right: 0;
                    background: ${color};
                    color: white;
                    padding: 10px;
                    text-align: center;
                    font-weight: 500;
                    z-index: 10000;
                    animation: slideDown 0.3s ease;
                ">
                    ${message}
                </div>
                <style>
                    @keyframes slideDown {
                        from { transform: translateY(-100%); }
                        to { transform: translateY(0); }
                    }
                </style>
            `;
            
            document.body.appendChild(statusBar);
            
            setTimeout(() => {
                statusBar.style.animation = 'slideDown 0.3s ease reverse';
                setTimeout(() => statusBar.remove(), 300);
            }, 2000);
        }
        
        // === GESTION DES VERSIONS ET MISES À JOUR ===
        let currentVersion = '1.0.0';
        
        // Vérifier la version de l'application
        async function checkVersion() {
            try {
                console.log('🔍 Début vérification version...');
                
                // Test direct avec timestamp pour éviter le cache
                const url = `version.php?_t=${Date.now()}`;
                console.log('📡 URL de vérification:', url);
                
                const response = await apiRequest(url);
                console.log('📊 Réponse version API:', response);
                
                if (response.ok && response.data && response.data.success) {
                    const serverVersion = response.data.data;
                    console.log('✅ Données version serveur:', serverVersion);
                    
                    // Mettre à jour l'affichage de la version
                    const versionInfo = document.getElementById('versionInfo');
                    if (versionInfo) {
                        versionInfo.textContent = `v${serverVersion.app_version}`;
                        console.log('📝 Version affichée mise à jour');
                    }
                    
                    // Vérifier s'il y a une nouvelle version
                    console.log('🔍 Vérification nouvelle version...');
                    if (hasNewVersion(serverVersion)) {
                        console.log('🆕 NOUVELLE VERSION DÉTECTÉE !');
                        showUpdateButton();
                        showUpdateNotification(serverVersion);
                    } else {
                        console.log('✅ Version à jour');
                    }
                    
                    return serverVersion;
                } else {
                    console.error('❌ Réponse API invalide:', response);
                }
            } catch (error) {
                console.error('❌ Erreur vérification version:', error);
                
                // Fallback - essayer avec fetch direct
                try {
                    console.log('🔄 Tentative fetch direct...');
                    const directResponse = await fetch(`./version.php?_t=${Date.now()}`, {
                        cache: 'no-cache',
                        headers: { 'Cache-Control': 'no-cache' }
                    });
                    const directData = await directResponse.json();
                    console.log('📊 Réponse fetch direct:', directData);
                    
                    if (directData.success) {
                        const serverVersion = directData.data;
                        
                        // Mettre à jour l'affichage
                        const versionInfo = document.getElementById('versionInfo');
                        if (versionInfo) {
                            versionInfo.textContent = `v${serverVersion.app_version}`;
                        }
                        
                        if (hasNewVersion(serverVersion)) {
                            console.log('🆕 NOUVELLE VERSION DÉTECTÉE (fetch direct) !');
                            showUpdateButton();
                            showUpdateNotification(serverVersion);
                        }
                        
                        return serverVersion;
                    }
                } catch (fetchError) {
                    console.error('❌ Erreur fetch direct:', fetchError);
                }
            }
        }
        
        // Vérifier s'il y a une nouvelle version
        function hasNewVersion(serverVersion) {
            console.log('🔍 Analyse nouvelle version...');
            console.log('📊 Version actuelle:', currentVersion);
            console.log('📊 Version serveur:', serverVersion.app_version);
            
            // 1. Comparer les versions du manifest
            if (serverVersion.app_version !== currentVersion) {
                console.log(`🆕 Version différente détectée: ${currentVersion} → ${serverVersion.app_version}`);
                // Mettre à jour la version courante
                currentVersion = serverVersion.app_version;
                return true;
            }
            
            // 2. Comparer les timestamps des fichiers (dans les 10 dernières minutes)
            if (serverVersion.files) {
                const now = new Date();
                console.log('📅 Maintenant:', now.toLocaleString());
                
                for (const [fileName, fileInfo] of Object.entries(serverVersion.files)) {
                    const fileDate = new Date(fileInfo.last_modified);
                    const timeDiff = now - fileDate;
                    const minutesDiff = Math.floor(timeDiff / (1000 * 60));
                    
                    console.log(`📄 ${fileName}:`, {
                        modified: fileInfo.last_modified,
                        timeDiff_minutes: minutesDiff,
                        size: fileInfo.size
                    });
                    
                    // Si un fichier a été modifié dans les 10 dernières minutes
                    if (timeDiff < 10 * 60 * 1000) {
                        console.log(`🆕 Fichier récemment modifié: ${fileName} (il y a ${minutesDiff} minutes)`);
                        return true;
                    }
                }
            }
            
            // 3. Vérifier le build number si disponible
            if (serverVersion.build_number) {
                const storedBuild = localStorage.getItem('lastBuildNumber');
                console.log('🏗️ Build stocké:', storedBuild, 'Build serveur:', serverVersion.build_number);
                
                if (storedBuild && storedBuild !== serverVersion.build_number) {
                    console.log(`🆕 Nouveau build détecté: ${storedBuild} → ${serverVersion.build_number}`);
                    localStorage.setItem('lastBuildNumber', serverVersion.build_number);
                    return true;
                } else if (!storedBuild) {
                    // Première fois, stocker le build number
                    localStorage.setItem('lastBuildNumber', serverVersion.build_number);
                }
            }
            
            console.log('✅ Aucune nouvelle version détectée');
            return false;
        }
        
        // Afficher le bouton de mise à jour
        function showUpdateButton() {
            const updateButton = document.getElementById('updateButton');
            if (updateButton) {
                updateButton.style.display = 'block';
                updateButton.style.animation = 'pulse 2s infinite';
                
                // Style pour l'animation pulse
                if (!document.getElementById('pulseAnimation')) {
                    const style = document.createElement('style');
                    style.id = 'pulseAnimation';
                    style.textContent = `
                        @keyframes pulse {
                            0% { box-shadow: 0 0 0 0 rgba(231, 76, 60, 0.7); }
                            70% { box-shadow: 0 0 0 10px rgba(231, 76, 60, 0); }
                            100% { box-shadow: 0 0 0 0 rgba(231, 76, 60, 0); }
                        }
                    `;
                    document.head.appendChild(style);
                }
            }
        }
        
        // Afficher une notification de mise à jour
        function showUpdateNotification(serverVersion) {
            const notification = document.createElement('div');
            notification.style.cssText = `
                position: fixed;
                top: 80px;
                right: 20px;
                background: linear-gradient(135deg, #e74c3c, #c0392b);
                color: white;
                padding: 16px 20px;
                border-radius: 12px;
                box-shadow: 0 10px 30px rgba(0,0,0,0.3);
                z-index: 10001;
                max-width: 350px;
                font-family: inherit;
                animation: slideInRight 0.4s ease-out;
                cursor: pointer;
            `;
            
            notification.innerHTML = `
                <div style="display: flex; align-items: flex-start; gap: 12px;">
                    <div style="font-size: 1.2em;">🔄</div>
                    <div style="flex: 1;">
                        <div style="font-weight: bold; margin-bottom: 4px; font-size: 15px;">Nouvelle version disponible !</div>
                        <div style="font-size: 13px; opacity: 0.9; line-height: 1.3;">Cliquer pour mettre à jour l'application</div>
                    </div>
                    <button onclick="this.parentElement.parentElement.remove()" style="
                        background: rgba(255,255,255,0.2);
                        border: none;
                        color: white;
                        border-radius: 50%;
                        width: 26px;
                        height: 26px;
                        cursor: pointer;
                        font-size: 14px;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                    ">×</button>
                </div>
            `;
            
            notification.addEventListener('click', (e) => {
                if (e.target.tagName !== 'BUTTON') {
                    forceUpdate();
                    notification.remove();
                }
            });
            
            document.body.appendChild(notification);
            
            // Auto-supprimer après 10 secondes
            setTimeout(() => {
                if (notification.parentElement) {
                    notification.remove();
                }
            }, 10000);
        }
        
        // Forcer la mise à jour de l'application
        async function forceUpdate() {
            try {
                showTemporaryMessage('🔄 Mise à jour en cours...', 'warning');
                
                // Vider tous les caches
                if ('caches' in window) {
                    const cacheNames = await caches.keys();
                    await Promise.all(cacheNames.map(name => caches.delete(name)));
                    console.log('✅ Caches vidés');
                }
                
                // Désinscrire le service worker
                if ('serviceWorker' in navigator) {
                    const registrations = await navigator.serviceWorker.getRegistrations();
                    await Promise.all(registrations.map(reg => reg.unregister()));
                    console.log('✅ Service Workers désinscits');
                }
                
                // Attendre un peu puis recharger
                setTimeout(() => {
                    showTemporaryMessage('🔄 Rechargement de l\'application...', 'info');
                    setTimeout(() => {
                        window.location.reload(true);
                    }, 500);
                }, 1000);
                
            } catch (error) {
                console.error('❌ Erreur mise à jour:', error);
                showTemporaryMessage('❌ Erreur lors de la mise à jour', 'error');
            }
        }
        
        // Vérification périodique des versions (toutes les 5 minutes)
        setInterval(checkVersion, 5 * 60 * 1000);
        
        // === SYSTÈME DE RAPPORTS ET ANALYTICS AVANCÉS ===
        let reportsData = {
            currentFilters: {
                period: '30d',
                site: 'all',
                client: 'all',
                startDate: null,
                endDate: null
            },
            charts: {}
        };
        
        // Initialiser les rapports
        async function initializeReports() {
            console.log('📊 Initialisation des rapports...');
            
            try {
                // Charger les options pour les filtres
                await loadReportFilters();
                
                // Charger les données et métriques
                await loadReportsData();
                
                // Créer les graphiques
                await createAdvancedCharts();
                
                console.log('✅ Rapports initialisés');
            } catch (error) {
                console.error('❌ Erreur initialisation rapports:', error);
                showTemporaryMessage('❌ Erreur chargement rapports', 'error');
            }
        }
        
        // Charger les options pour les filtres
        async function loadReportFilters() {
            try {
                const response = await apiRequest('pesees.php?action=options');
                if (response.ok && response.data.success) {
                    const options = response.data.data;
                    
                    // Remplir le filtre site
                    const siteFilter = document.getElementById('siteFilter');
                    if (siteFilter && options.sites) {
                        siteFilter.innerHTML = '<option value="all">Tous les sites</option>';
                        options.sites.forEach(site => {
                            const option = document.createElement('option');
                            option.value = site;
                            option.textContent = site;
                            siteFilter.appendChild(option);
                        });
                    }
                    
                    // Remplir le filtre client
                    const clientFilter = document.getElementById('clientFilter');
                    if (clientFilter && options.clients) {
                        clientFilter.innerHTML = '<option value="all">Tous les clients</option>';
                        options.clients.forEach(client => {
                            const option = document.createElement('option');
                            option.value = client;
                            option.textContent = client;
                            clientFilter.appendChild(option);
                        });
                    }
                }
            } catch (error) {
                console.error('❌ Erreur chargement filtres:', error);
            }
        }
        
        // Appliquer les filtres des rapports
        async function applyReportFilters() {
            const periodFilter = document.getElementById('periodFilter');
            const siteFilter = document.getElementById('siteFilter');
            const clientFilter = document.getElementById('clientFilter');
            const customDateRange = document.getElementById('customDateRange');
            
            // Gérer l'affichage des dates personnalisées
            if (periodFilter.value === 'custom') {
                customDateRange.style.display = 'flex';
            } else {
                customDateRange.style.display = 'none';
            }
            
            // Mettre à jour les filtres
            reportsData.currentFilters = {
                period: periodFilter.value,
                site: siteFilter.value,
                client: clientFilter.value,
                startDate: document.getElementById('startDate')?.value,
                endDate: document.getElementById('endDate')?.value
            };
            
            console.log('🔄 Application filtres:', reportsData.currentFilters);
            showTemporaryMessage('🔄 Mise à jour des rapports...', 'info');
            
            // Recharger les données avec les nouveaux filtres
            await loadReportsData();
            await updateAllCharts();
        }
        
        // Charger les données des rapports
        async function loadReportsData() {
            try {
                // Construire les paramètres de requête selon les filtres
                let dateFilter = '';
                const filters = reportsData.currentFilters;
                
                if (filters.period === 'custom' && filters.startDate && filters.endDate) {
                    dateFilter = `&dateDebut=${filters.startDate}&dateFin=${filters.endDate}`;
                } else {
                    // Calculer les dates selon la période
                    const endDate = new Date();
                    const startDate = new Date();
                    
                    switch (filters.period) {
                        case '7d':
                            startDate.setDate(endDate.getDate() - 7);
                            break;
                        case '30d':
                            startDate.setDate(endDate.getDate() - 30);
                            break;
                        case '90d':
                            startDate.setDate(endDate.getDate() - 90);
                            break;
                        case '1y':
                            startDate.setFullYear(endDate.getFullYear() - 1);
                            break;
                    }
                    
                    dateFilter = `&dateDebut=${startDate.toISOString().split('T')[0]}&dateFin=${endDate.toISOString().split('T')[0]}`;
                }
                
                // Ajouter les autres filtres
                let otherFilters = '';
                if (filters.site !== 'all') {
                    otherFilters += `&site=${encodeURIComponent(filters.site)}`;
                }
                if (filters.client !== 'all') {
                    otherFilters += `&client=${encodeURIComponent(filters.client)}`;
                }
                
                // Récupérer les données filtrées
                const response = await apiRequest(`pesees.php?action=search${dateFilter}${otherFilters}`);
                
                if (response.ok && response.data.success) {
                    const data = response.data.data;
                    console.log('📊 Données rapports reçues:', data.length, 'pesées');
                    
                    // Calculer les métriques
                    updateMetrics(data);
                    
                    // Mettre à jour le tableau détaillé
                    updateDetailedTable(data);
                    
                    // Calculer les comparaisons
                    await loadComparisons(data);
                    
                    return data;
                } else {
                    console.error('❌ Erreur données rapports:', response);
                    return [];
                }
            } catch (error) {
                console.error('❌ Erreur chargement données rapports:', error);
                return [];
            }
        }
        
        // Mettre à jour les métriques
        function updateMetrics(data) {
            const totalWeighings = data.length;
            const totalWeight = data.reduce((sum, item) => sum + (parseFloat(item.PoidsNet) || 0), 0) / 1000; // En tonnes
            const avgWeight = totalWeighings > 0 ? (totalWeight * 1000) / totalWeighings : 0; // En kg
            const activeClients = new Set(data.map(item => item.NomClient).filter(Boolean)).size;
            
            // Mettre à jour l'affichage
            document.getElementById('totalWeighingsMetric').textContent = totalWeighings.toLocaleString();
            document.getElementById('totalWeightMetric').textContent = totalWeight.toFixed(1) + ' T';
            document.getElementById('avgWeightMetric').textContent = avgWeight.toFixed(0) + ' kg';
            document.getElementById('activeClientsMetric').textContent = activeClients.toLocaleString();
            
            // Calculer les changements (simulé pour l'exemple)
            updateMetricChanges(totalWeighings, totalWeight, avgWeight, activeClients);
        }
        
        // Mettre à jour les indicateurs de changement
        function updateMetricChanges(weighings, weight, avg, clients) {
            // Simulation de changements (à remplacer par de vraies comparaisons)
            const changes = [
                { id: 'weighingsChange', value: Math.random() * 20 - 10 },
                { id: 'weightChange', value: Math.random() * 15 - 7.5 },
                { id: 'avgChange', value: Math.random() * 10 - 5 },
                { id: 'clientsChange', value: Math.random() * 25 - 12.5 }
            ];
            
            changes.forEach(change => {
                const element = document.getElementById(change.id);
                if (element) {
                    const value = change.value;
                    const sign = value >= 0 ? '+' : '';
                    element.textContent = `${sign}${value.toFixed(1)}%`;
                    
                    // Ajouter les classes CSS
                    element.className = 'metric-change';
                    if (value > 0) {
                        element.classList.add('positive');
                    } else if (value < 0) {
                        element.classList.add('negative');
                    } else {
                        element.classList.add('neutral');
                    }
                }
            });
        }
        
        // Créer les graphiques avancés
        async function createAdvancedCharts() {
            const data = await loadReportsData();
            
            // Graphique d'évolution
            createEvolutionChart(data);
            
            // Graphique des produits
            createProductsChart(data);
            
            // Graphique des top clients
            createTopClientsChart(data);
            
            // Graphique des sites
            createSitesChart(data);
        }
        
        // Graphique d'évolution des pesées
        function createEvolutionChart(data) {
            const ctx = document.getElementById('evolutionChart');
            if (!ctx || !data || data.length === 0) return;
            
            // Grouper les données par période
            const period = document.getElementById('evolutionPeriod')?.value || 'monthly';
            const groupedData = groupDataByPeriod(data, period);
            
            // Détruire le graphique existant s'il y en a un
            if (reportsData.charts.evolution) {
                reportsData.charts.evolution.destroy();
            }
            
            reportsData.charts.evolution = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: Object.keys(groupedData),
                    datasets: [{
                        label: 'Nombre de pesées',
                        data: Object.values(groupedData).map(group => group.count),
                        borderColor: '#667eea',
                        backgroundColor: 'rgba(102, 126, 234, 0.1)',
                        tension: 0.4,
                        fill: true
                    }, {
                        label: 'Poids total (T)',
                        data: Object.values(groupedData).map(group => (group.weight / 1000).toFixed(1)),
                        borderColor: '#764ba2',
                        backgroundColor: 'rgba(118, 75, 162, 0.1)',
                        tension: 0.4,
                        yAxisID: 'y1'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            labels: { color: '#f1f5f9' }
                        }
                    },
                    scales: {
                        x: {
                            ticks: { color: '#94a3b8' },
                            grid: { color: 'rgba(148, 163, 184, 0.1)' }
                        },
                        y: {
                            type: 'linear',
                            display: true,
                            position: 'left',
                            ticks: { color: '#94a3b8' },
                            grid: { color: 'rgba(148, 163, 184, 0.1)' }
                        },
                        y1: {
                            type: 'linear',
                            display: true,
                            position: 'right',
                            ticks: { color: '#94a3b8' },
                            grid: { drawOnChartArea: false }
                        }
                    }
                }
            });
        }
        
        // Grouper les données par période
        function groupDataByPeriod(data, period) {
            const grouped = {};
            
            data.forEach(item => {
                const date = new Date(item.dmv);
                let key;
                
                switch (period) {
                    case 'daily':
                        key = date.toISOString().split('T')[0];
                        break;
                    case 'weekly':
                        const weekStart = new Date(date);
                        weekStart.setDate(date.getDate() - date.getDay());
                        key = weekStart.toISOString().split('T')[0];
                        break;
                    case 'monthly':
                    default:
                        key = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`;
                        break;
                }
                
                if (!grouped[key]) {
                    grouped[key] = { count: 0, weight: 0 };
                }
                
                grouped[key].count++;
                grouped[key].weight += parseFloat(item.PoidsNet) || 0;
            });
            
            return grouped;
        }
        
        // Graphique des produits
        function createProductsChart(data) {
            const ctx = document.getElementById('productsChart');
            if (!ctx || !data || data.length === 0) return;
            
            // Grouper par produit
            const products = {};
            data.forEach(item => {
                const product = item.NomProduit || 'Non spécifié';
                products[product] = (products[product] || 0) + 1;
            });
            
            // Trier et prendre les top 8
            const sortedProducts = Object.entries(products)
                .sort(([,a], [,b]) => b - a)
                .slice(0, 8);
            
            if (reportsData.charts.products) {
                reportsData.charts.products.destroy();
            }
            
            reportsData.charts.products = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    labels: sortedProducts.map(([name]) => name),
                    datasets: [{
                        data: sortedProducts.map(([, count]) => count),
                        backgroundColor: [
                            '#667eea', '#764ba2', '#f093fb', '#f5576c',
                            '#4facfe', '#00f2fe', '#43e97b', '#38f9d7'
                        ]
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: { color: '#f1f5f9' }
                        }
                    }
                }
            });
        }
        
        // Graphique Top 10 clients
        function createTopClientsChart(data) {
            const ctx = document.getElementById('topClientsChart');
            if (!ctx || !data || data.length === 0) return;
            
            // Grouper par client avec poids total
            const clients = {};
            data.forEach(item => {
                const client = item.NomClient || 'Non spécifié';
                if (!clients[client]) {
                    clients[client] = { count: 0, weight: 0 };
                }
                clients[client].count++;
                clients[client].weight += parseFloat(item.PoidsNet) || 0;
            });
            
            // Trier par poids et prendre les top 10
            const sortedClients = Object.entries(clients)
                .sort(([,a], [,b]) => b.weight - a.weight)
                .slice(0, 10);
            
            if (reportsData.charts.topClients) {
                reportsData.charts.topClients.destroy();
            }
            
            reportsData.charts.topClients = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: sortedClients.map(([name]) => name.length > 15 ? name.substring(0, 15) + '...' : name),
                    datasets: [{
                        label: 'Poids total (kg)',
                        data: sortedClients.map(([, data]) => data.weight),
                        backgroundColor: '#667eea',
                        borderColor: '#764ba2',
                        borderWidth: 1
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    indexAxis: 'y',
                    plugins: {
                        legend: {
                            labels: { color: '#f1f5f9' }
                        }
                    },
                    scales: {
                        x: {
                            ticks: { color: '#94a3b8' },
                            grid: { color: 'rgba(148, 163, 184, 0.1)' }
                        },
                        y: {
                            ticks: { color: '#94a3b8' },
                            grid: { color: 'rgba(148, 163, 184, 0.1)' }
                        }
                    }
                }
            });
        }
        
        // Graphique performance par site
        function createSitesChart(data) {
            const ctx = document.getElementById('sitesChart');
            if (!ctx || !data || data.length === 0) return;
            
            // Grouper par site
            const sites = {};
            data.forEach(item => {
                const site = item.NomSite || item.CodeSite || 'Non spécifié';
                if (!sites[site]) {
                    sites[site] = { count: 0, weight: 0 };
                }
                sites[site].count++;
                sites[site].weight += parseFloat(item.PoidsNet) || 0;
            });
            
            if (reportsData.charts.sites) {
                reportsData.charts.sites.destroy();
            }
            
            reportsData.charts.sites = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: Object.keys(sites),
                    datasets: [{
                        label: 'Nombre de pesées',
                        data: Object.values(sites).map(s => s.count),
                        backgroundColor: '#667eea',
                        yAxisID: 'y'
                    }, {
                        label: 'Poids total (T)',
                        data: Object.values(sites).map(s => (s.weight / 1000).toFixed(1)),
                        backgroundColor: '#764ba2',
                        yAxisID: 'y1'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            labels: { color: '#f1f5f9' }
                        }
                    },
                    scales: {
                        x: {
                            ticks: { color: '#94a3b8' },
                            grid: { color: 'rgba(148, 163, 184, 0.1)' }
                        },
                        y: {
                            type: 'linear',
                            display: true,
                            position: 'left',
                            ticks: { color: '#94a3b8' },
                            grid: { color: 'rgba(148, 163, 184, 0.1)' }
                        },
                        y1: {
                            type: 'linear',
                            display: true,
                            position: 'right',
                            ticks: { color: '#94a3b8' },
                            grid: { drawOnChartArea: false }
                        }
                    }
                }
            });
        }
        
        // Mettre à jour le graphique d'évolution
        function updateEvolutionChart() {
            loadReportsData().then(data => {
                createEvolutionChart(data);
            });
        }
        
        // Mettre à jour tous les graphiques
        async function updateAllCharts() {
            const data = await loadReportsData();
            createEvolutionChart(data);
            createProductsChart(data);
            createTopClientsChart(data);
            createSitesChart(data);
        }
        
        // Actualiser les rapports
        async function refreshReports() {
            showTemporaryMessage('🔄 Actualisation des rapports...', 'info');
            await initializeReports();
            showTemporaryMessage('✅ Rapports actualisés', 'success');
        }
        
        // Mettre à jour le tableau détaillé
        function updateDetailedTable(data) {
            const tbody = document.getElementById('detailedReportsBody');
            if (!tbody) return;
            
            if (!data || data.length === 0) {
                tbody.innerHTML = '<tr><td colspan="6" class="loading-row">Aucune donnée disponible</td></tr>';
                return;
            }
            
            tbody.innerHTML = data.slice(0, 100).map(item => `
                <tr>
                    <td>${new Date(item.dmv).toLocaleDateString()}</td>
                    <td>${item.CodePesee || '-'}</td>
                    <td>${item.NomClient || '-'}</td>
                    <td>${item.NomProduit || '-'}</td>
                    <td>${item.NomSite || item.CodeSite || '-'}</td>
                    <td>${parseFloat(item.PoidsNet || 0).toLocaleString()} kg</td>
                </tr>
            `).join('');
        }
        
        // Filtrer le tableau détaillé
        function filterDetailedTable() {
            const searchTerm = document.getElementById('tableSearch').value.toLowerCase();
            const tbody = document.getElementById('detailedReportsBody');
            const rows = tbody.getElementsByTagName('tr');
            
            for (let row of rows) {
                const text = row.textContent.toLowerCase();
                row.style.display = text.includes(searchTerm) ? '' : 'none';
            }
        }
        
        // Grouper le tableau détaillé
        function groupDetailedTable() {
            const groupBy = document.getElementById('tableGroupBy').value;
            // Implementation du groupement (à développer selon les besoins)
            console.log('Groupement par:', groupBy);
            showTemporaryMessage(`📊 Groupement par ${groupBy}`, 'info');
        }
        
        // Trier le tableau
        function sortTable(columnIndex) {
            const table = document.getElementById('detailedReportsTable');
            const tbody = table.tBodies[0];
            const rows = Array.from(tbody.rows);
            
            rows.sort((a, b) => {
                const aVal = a.cells[columnIndex].textContent;
                const bVal = b.cells[columnIndex].textContent;
                return aVal.localeCompare(bVal);
            });
            
            rows.forEach(row => tbody.appendChild(row));
        }
        
        // Charger les comparaisons périodiques
        async function loadComparisons(currentData) {
            try {
                // Calculer les données de la semaine précédente
                const weekAgo = new Date();
                weekAgo.setDate(weekAgo.getDate() - 14);
                const lastWeekEnd = new Date();
                lastWeekEnd.setDate(lastWeekEnd.getDate() - 7);
                
                // Calculer les données du mois précédent
                const monthAgo = new Date();
                monthAgo.setMonth(monthAgo.getMonth() - 2);
                const lastMonthEnd = new Date();
                lastMonthEnd.setMonth(lastMonthEnd.getMonth() - 1);
                
                // Pour cette démo, on simule les comparaisons
                const weekComparison = {
                    weighings: Math.random() * 20 - 10,
                    weight: Math.random() * 15 - 7.5
                };
                
                const monthComparison = {
                    weighings: Math.random() * 25 - 12.5,
                    weight: Math.random() * 18 - 9
                };
                
                // Mettre à jour l'affichage
                updateComparisonDisplay('week', weekComparison);
                updateComparisonDisplay('month', monthComparison);
                
            } catch (error) {
                console.error('❌ Erreur chargement comparaisons:', error);
            }
        }
        
        // Mettre à jour l'affichage des comparaisons
        function updateComparisonDisplay(period, comparison) {
            const weighingsEl = document.getElementById(`${period}Weighings`);
            const weightEl = document.getElementById(`${period}Weight`);
            
            if (weighingsEl) {
                const value = comparison.weighings;
                const sign = value >= 0 ? '+' : '';
                weighingsEl.textContent = `${sign}${value.toFixed(1)}%`;
                weighingsEl.className = `comparison-value ${value >= 0 ? 'positive' : 'negative'}`;
            }
            
            if (weightEl) {
                const value = comparison.weight;
                const sign = value >= 0 ? '+' : '';
                weightEl.textContent = `${sign}${value.toFixed(1)}%`;
                weightEl.className = `comparison-value ${value >= 0 ? 'positive' : 'negative'}`;
            }
        }
        
        // Export PDF réel avec graphiques et données
        async function exportToPDF() {
            try {
                showTemporaryMessage('📄 Génération du PDF en cours...', 'warning');
                
                const { jsPDF } = window.jspdf;
                const pdf = new jsPDF('p', 'mm', 'a4');
                
                // Configuration
                const pageWidth = pdf.internal.pageSize.getWidth();
                const pageHeight = pdf.internal.pageSize.getHeight();
                const margin = 20;
                let currentY = margin;
                
                // En-tête
                pdf.setFontSize(20);
                pdf.setTextColor(102, 126, 234);
                pdf.text('KOMBAR FERD - Rapport de Pesées', margin, currentY);
                currentY += 15;
                
                // Date du rapport
                pdf.setFontSize(12);
                pdf.setTextColor(100, 100, 100);
                pdf.text(`Généré le ${new Date().toLocaleDateString('fr-FR')} à ${new Date().toLocaleTimeString('fr-FR')}`, margin, currentY);
                currentY += 10;
                
                // Filtres appliqués
                const filters = reportsData.currentFilters;
                pdf.text(`Période: ${filters.period === 'custom' ? `${filters.startDate} à ${filters.endDate}` : filters.period}`, margin, currentY);
                currentY += 5;
                if (filters.site !== 'all') {
                    pdf.text(`Site: ${filters.site}`, margin, currentY);
                    currentY += 5;
                }
                if (filters.client !== 'all') {
                    pdf.text(`Client: ${filters.client}`, margin, currentY);
                    currentY += 5;
                }
                currentY += 10;
                
                // Métriques clés
                pdf.setFontSize(16);
                pdf.setTextColor(0, 0, 0);
                pdf.text('Métriques Clés', margin, currentY);
                currentY += 10;
                
                pdf.setFontSize(12);
                const totalWeighings = document.getElementById('totalWeighingsMetric')?.textContent || '0';
                const totalWeight = document.getElementById('totalWeightMetric')?.textContent || '0 T';
                const avgWeight = document.getElementById('avgWeightMetric')?.textContent || '0 kg';
                const activeClients = document.getElementById('activeClientsMetric')?.textContent || '0';
                
                pdf.text(`• Total des pesées: ${totalWeighings}`, margin, currentY);
                currentY += 7;
                pdf.text(`• Poids total: ${totalWeight}`, margin, currentY);
                currentY += 7;
                pdf.text(`• Poids moyen: ${avgWeight}`, margin, currentY);
                currentY += 7;
                pdf.text(`• Clients actifs: ${activeClients}`, margin, currentY);
                currentY += 15;
                
                // Capture des graphiques
                const charts = ['evolutionChart', 'productsChart', 'topClientsChart', 'sitesChart'];
                
                for (let i = 0; i < charts.length; i++) {
                    const chartElement = document.getElementById(charts[i]);
                    if (chartElement && currentY < pageHeight - 80) {
                        try {
                            // Titre du graphique
                            pdf.setFontSize(14);
                            const chartTitles = {
                                'evolutionChart': 'Évolution des Pesées',
                                'productsChart': 'Répartition par Produit',
                                'topClientsChart': 'Top 10 Clients',
                                'sitesChart': 'Performance par Site'
                            };
                            pdf.text(chartTitles[charts[i]], margin, currentY);
                            currentY += 10;
                            
                            // Capture du graphique
                            const canvas = await html2canvas(chartElement, {
                                backgroundColor: '#ffffff',
                                scale: 2
                            });
                            
                            const imgData = canvas.toDataURL('image/png');
                            const imgWidth = pageWidth - (margin * 2);
                            const imgHeight = (canvas.height * imgWidth) / canvas.width;
                            
                            // Vérifier si on a assez de place, sinon nouvelle page
                            if (currentY + imgHeight > pageHeight - margin) {
                                pdf.addPage();
                                currentY = margin;
                            }
                            
                            pdf.addImage(imgData, 'PNG', margin, currentY, imgWidth, imgHeight);
                            currentY += imgHeight + 15;
                            
                        } catch (chartError) {
                            console.warn(`Erreur capture graphique ${charts[i]}:`, chartError);
                        }
                    }
                    
                    // Nouvelle page si nécessaire
                    if (i < charts.length - 1 && currentY > pageHeight - 100) {
                        pdf.addPage();
                        currentY = margin;
                    }
                }
                
                // Tableau des données (nouvelle page)
                pdf.addPage();
                currentY = margin;
                
                pdf.setFontSize(16);
                pdf.text('Données Détaillées', margin, currentY);
                currentY += 15;
                
                // En-têtes du tableau
                pdf.setFontSize(10);
                pdf.setTextColor(0, 0, 0);
                const colWidths = [25, 30, 40, 40, 30, 25];
                const headers = ['Date', 'Code', 'Client', 'Produit', 'Site', 'Poids (kg)'];
                let startX = margin;
                
                headers.forEach((header, index) => {
                    pdf.text(header, startX, currentY);
                    startX += colWidths[index];
                });
                currentY += 10;
                
                // Ligne de séparation
                pdf.line(margin, currentY, pageWidth - margin, currentY);
                currentY += 5;
                
                // Données du tableau (max 30 lignes)
                const tableBody = document.getElementById('detailedReportsBody');
                if (tableBody && tableBody.rows) {
                    const maxRows = Math.min(30, tableBody.rows.length);
                    
                    for (let i = 0; i < maxRows; i++) {
                        const row = tableBody.rows[i];
                        if (row.cells) {
                            startX = margin;
                            
                            for (let j = 0; j < Math.min(6, row.cells.length); j++) {
                                let cellText = row.cells[j].textContent.trim();
                                // Tronquer le texte si trop long
                                if (cellText.length > 15) {
                                    cellText = cellText.substring(0, 12) + '...';
                                }
                                pdf.text(cellText, startX, currentY);
                                startX += colWidths[j];
                            }
                            currentY += 5;
                            
                            // Nouvelle page si nécessaire
                            if (currentY > pageHeight - 30) {
                                pdf.addPage();
                                currentY = margin;
                            }
                        }
                    }
                }
                
                // Pied de page
                const totalPages = pdf.internal.getNumberOfPages();
                for (let i = 1; i <= totalPages; i++) {
                    pdf.setPage(i);
                    pdf.setFontSize(8);
                    pdf.setTextColor(150, 150, 150);
                    pdf.text(`Page ${i} sur ${totalPages}`, pageWidth - margin - 20, pageHeight - 10);
                }
                
                // Télécharger le fichier
                const fileName = `KOMBAR_FERD_Rapport_${new Date().toISOString().split('T')[0]}.pdf`;
                pdf.save(fileName);
                
                showTemporaryMessage('✅ PDF généré et téléchargé', 'success');
                console.log('📄 Export PDF réussi:', fileName);
                
            } catch (error) {
                console.error('❌ Erreur export PDF:', error);
                showTemporaryMessage('❌ Erreur lors de l\'export PDF', 'error');
            }
        }
        
        // Export Excel réel avec toutes les données
        async function exportToExcel() {
            try {
                showTemporaryMessage('📊 Génération du fichier Excel...', 'warning');
                
                // Récupérer toutes les données actuelles
                const data = await loadReportsData();
                if (!data || data.length === 0) {
                    showTemporaryMessage('⚠️ Aucune donnée à exporter', 'warning');
                    return;
                }
                
                // Créer un nouveau classeur
                const wb = XLSX.utils.book_new();
                
                // === FEUILLE 1: DONNÉES BRUTES ===
                const rawData = data.map(item => ({
                    'Date': new Date(item.dmv).toLocaleDateString('fr-FR'),
                    'Heure': new Date(item.dmv).toLocaleTimeString('fr-FR'),
                    'Code Pesée': item.CodePesee || '',
                    'Numéro Ticket': item.NumTicket || '',
                    'Client': item.NomClient || '',
                    'Fournisseur': item.NomFournisseur || '',
                    'Produit': item.NomProduit || '',
                    'Site': item.NomSite || item.CodeSite || '',
                    'Code Site': item.CodeSite || '',
                    'Poids Brut (kg)': parseFloat(item.Poids1) || 0,
                    'Tare (kg)': parseFloat(item.Poids2) || 0,
                    'Poids Net (kg)': parseFloat(item.PoidsNet) || 0,
                    'Immatriculation': item.Immatriculation || '',
                    'Peseur': item.NomPeseur1 || '',
                    'Provenance': item.Provenance || '',
                    'Destination': item.Destination || ''
                }));
                
                const ws1 = XLSX.utils.json_to_sheet(rawData);
                
                // Ajuster la largeur des colonnes
                const colWidths = [
                    { wch: 12 }, { wch: 10 }, { wch: 15 }, { wch: 15 },
                    { wch: 25 }, { wch: 25 }, { wch: 20 }, { wch: 20 },
                    { wch: 12 }, { wch: 12 }, { wch: 10 }, { wch: 12 },
                    { wch: 15 }, { wch: 20 }, { wch: 20 }, { wch: 20 }
                ];
                ws1['!cols'] = colWidths;
                
                XLSX.utils.book_append_sheet(wb, ws1, "Données Brutes");
                
                // === FEUILLE 2: RÉSUMÉ PAR CLIENT ===
                const clientSummary = {};
                data.forEach(item => {
                    const client = item.NomClient || 'Non spécifié';
                    if (!clientSummary[client]) {
                        clientSummary[client] = { count: 0, totalWeight: 0, avgWeight: 0 };
                    }
                    clientSummary[client].count++;
                    clientSummary[client].totalWeight += parseFloat(item.PoidsNet) || 0;
                });
                
                const clientData = Object.entries(clientSummary).map(([client, stats]) => ({
                    'Client': client,
                    'Nombre de Pesées': stats.count,
                    'Poids Total (kg)': Math.round(stats.totalWeight),
                    'Poids Total (T)': (stats.totalWeight / 1000).toFixed(2),
                    'Poids Moyen (kg)': Math.round(stats.totalWeight / stats.count)
                })).sort((a, b) => b['Poids Total (kg)'] - a['Poids Total (kg)']);
                
                const ws2 = XLSX.utils.json_to_sheet(clientData);
                ws2['!cols'] = [{ wch: 30 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }];
                XLSX.utils.book_append_sheet(wb, ws2, "Résumé par Client");
                
                // === FEUILLE 3: RÉSUMÉ PAR PRODUIT ===
                const productSummary = {};
                data.forEach(item => {
                    const product = item.NomProduit || 'Non spécifié';
                    if (!productSummary[product]) {
                        productSummary[product] = { count: 0, totalWeight: 0 };
                    }
                    productSummary[product].count++;
                    productSummary[product].totalWeight += parseFloat(item.PoidsNet) || 0;
                });
                
                const productData = Object.entries(productSummary).map(([product, stats]) => ({
                    'Produit': product,
                    'Nombre de Pesées': stats.count,
                    'Poids Total (kg)': Math.round(stats.totalWeight),
                    'Poids Total (T)': (stats.totalWeight / 1000).toFixed(2),
                    'Poids Moyen (kg)': Math.round(stats.totalWeight / stats.count)
                })).sort((a, b) => b['Nombre de Pesées'] - a['Nombre de Pesées']);
                
                const ws3 = XLSX.utils.json_to_sheet(productData);
                ws3['!cols'] = [{ wch: 25 }, { wch: 15 }, { wch: 15 }, { wch: 15 }, { wch: 15 }];
                XLSX.utils.book_append_sheet(wb, ws3, "Résumé par Produit");
                
                // === FEUILLE 4: MÉTRIQUES GLOBALES ===
                const totalWeighings = data.length;
                const totalWeight = data.reduce((sum, item) => sum + (parseFloat(item.PoidsNet) || 0), 0);
                const avgWeight = totalWeighings > 0 ? totalWeight / totalWeighings : 0;
                const uniqueClients = new Set(data.map(item => item.NomClient).filter(Boolean)).size;
                const uniqueProducts = new Set(data.map(item => item.NomProduit).filter(Boolean)).size;
                const uniqueSites = new Set(data.map(item => item.NomSite || item.CodeSite).filter(Boolean)).size;
                
                const metricsData = [
                    { 'Métrique': 'Nombre total de pesées', 'Valeur': totalWeighings, 'Unité': 'pesées' },
                    { 'Métrique': 'Poids total', 'Valeur': Math.round(totalWeight), 'Unité': 'kg' },
                    { 'Métrique': 'Poids total', 'Valeur': (totalWeight / 1000).toFixed(2), 'Unité': 'tonnes' },
                    { 'Métrique': 'Poids moyen par pesée', 'Valeur': Math.round(avgWeight), 'Unité': 'kg' },
                    { 'Métrique': 'Nombre de clients uniques', 'Valeur': uniqueClients, 'Unité': 'clients' },
                    { 'Métrique': 'Nombre de produits uniques', 'Valeur': uniqueProducts, 'Unité': 'produits' },
                    { 'Métrique': 'Nombre de sites uniques', 'Valeur': uniqueSites, 'Unité': 'sites' },
                    { 'Métrique': 'Période couverte', 'Valeur': reportsData.currentFilters.period, 'Unité': '' },
                    { 'Métrique': 'Date de génération', 'Valeur': new Date().toLocaleDateString('fr-FR'), 'Unité': '' },
                    { 'Métrique': 'Heure de génération', 'Valeur': new Date().toLocaleTimeString('fr-FR'), 'Unité': '' }
                ];
                
                const ws4 = XLSX.utils.json_to_sheet(metricsData);
                ws4['!cols'] = [{ wch: 30 }, { wch: 15 }, { wch: 15 }];
                XLSX.utils.book_append_sheet(wb, ws4, "Métriques Globales");
                
                // Télécharger le fichier
                const fileName = `KOMBAR_FERD_Données_${new Date().toISOString().split('T')[0]}.xlsx`;
                XLSX.writeFile(wb, fileName);
                
                showTemporaryMessage('✅ Fichier Excel généré et téléchargé', 'success');
                console.log('📊 Export Excel réussi:', fileName, `${data.length} lignes exportées`);
                
            } catch (error) {
                console.error('❌ Erreur export Excel:', error);
                showTemporaryMessage('❌ Erreur lors de l\'export Excel', 'error');
            }
        }
        
        // === FONCTIONS DE DEBUG ===
        // Fonction pour tester manuellement la détection de version
        window.testVersionCheck = function() {
            console.log('🧪 === TEST MANUEL VÉRIFICATION VERSION ===');
            checkVersion();
        };
        
        // Fonction pour forcer l'affichage du bouton de mise à jour
        window.testUpdateButton = function() {
            console.log('🧪 Test bouton mise à jour');
            showUpdateButton();
        };
        
        // Fonction pour réinitialiser les données de version stockées
        window.resetVersionData = function() {
            console.log('🧪 Réinitialisation données version');
            localStorage.removeItem('lastBuildNumber');
            currentVersion = '0.0.0'; // Force une différence
            console.log('✅ Données réinitialisées - testez maintenant checkVersion()');
        };
        
        // === FONCTIONS DE DEBUG TICKET ===
        // Fonction pour tester le chargement de ticket
        window.testTicketLoad = function(ticketId) {
            console.log('🧪 === TEST MANUEL CHARGEMENT TICKET ===');
            if (!ticketId) {
                console.log('Usage: testTicketLoad("ID_DU_TICKET")');
                return;
            }
            document.getElementById('ticketSearch').value = ticketId;
            loadTicket();
        };
        
        // Fonction pour lister les tickets disponibles
        window.listAvailableTickets = function() {
            console.log('🧪 === LISTE DES TICKETS DISPONIBLES ===');
            if (peseesData && peseesData.length > 0) {
                console.log('📊 Tickets dans les données actuelles:');
                peseesData.forEach((item, index) => {
                    console.log(`${index + 1}. NumTicket: "${item.NumTicket}" | CodePesee: "${item.CodePesee}" | Client: "${item.NomClient}"`);
                });
            } else {
                console.log('❌ Aucune donnée de pesée disponible. Faites d\'abord une recherche.');
            }
        };
        
        // Fonction pour tester l'API ticket directement
        window.testTicketAPI = async function(ticketId) {
            console.log('🧪 === TEST DIRECT API TICKET ===');
            if (!ticketId) {
                console.log('Usage: testTicketAPI("ID_DU_TICKET")');
                return;
            }
            
            try {
                const url = `pesees.php?action=ticket&numTicket=${encodeURIComponent(ticketId)}`;
                console.log('📡 URL:', url);
                
                const response = await fetch(url);
                const data = await response.json();
                
                console.log('📊 Réponse brute:', data);
                console.log('🔍 Status:', response.status);
                console.log('✅ Success:', data.success);
                console.log('📋 Data:', data.data);
                console.log('💬 Message:', data.message);
                
            } catch (error) {
                console.error('❌ Erreur test API:', error);
            }
        };
        
        // Initialisation
        document.addEventListener('DOMContentLoaded', async function() {
            // Enregistrer le Service Worker
            await registerServiceWorker();
            
            // Configurer la détection de connectivité
            setupConnectivityDetection();
            
            // Configurer les notifications push
            setupNotificationListeners();
            
            // Vérifier la version de l'application
            setTimeout(() => {
                checkVersion();
            }, 2000); // Attendre 2 secondes après le chargement
            
            const hasValidSession = await checkExistingSession();
            
            if (!hasValidSession) {
                document.getElementById('loginPage').style.display = 'flex';
                document.getElementById('dashboard').classList.remove('active');
            }
        });
    </script>
</body>
</html>