<!DOCTYPE html>
<html lang="fr-FR">
<head>
    <meta charset="utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>Système Avancé de Gestion de Stock</title>
    <!-- Importations de Bibliothèques Externes -->
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" rel="stylesheet"/>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;500;700&display=swap" rel="stylesheet"/>
    <link rel="stylesheet" href="https://unpkg.com/tippy.js@6/animations/scale.css"/>
    <script src="https://cdn.tailwindcss.com" defer></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js" defer></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js" defer></script>
    <script src="https://unpkg.com/@popperjs/core@2" defer></script>
    <script src="https://unpkg.com/tippy.js@6" defer></script>
    <style>
        /* Styles CSS pour accessibilité et amélioration de la lisibilité */
        body { 
            font-family: 'Roboto', sans-serif; 
            scroll-behavior: smooth; /* Défilement fluide */
            line-height: 1.6; /* Amélioration de la lisibilité */
        }
        .glass-effect { 
            background: rgba(255, 255, 255, 0.15); 
            backdrop-filter: blur(8px); 
            border: 1px solid rgba(255, 255, 255, 0.3); 
            transition: backdrop-filter 0.3s ease, background 0.3s ease; /* Transition fluide */
        }
        .neon-text { 
            color: #fff; 
            text-shadow: 
                0 0 5px rgba(255, 255, 255, 0.5), 
                0 0 10px rgba(255, 255, 255, 0.5), 
                0 0 20px rgba(255, 255, 255, 0.5); 
        }
        .hidden { display: none; }
        .modal { 
            position: fixed; 
            top: 0; 
            left: 0; 
            width: 100%; 
            height: 100%; 
            background: rgba(0, 0, 0, 0.5); 
            display: flex; 
            justify-content: center; 
            align-items: center; 
            z-index: 50; 
            transition: opacity 0.3s ease; /* Transition fluide */
        }
        .modal-content { 
            background: rgba(255, 255, 255, 0.1); 
            backdrop-filter: blur(10px); 
            border: 1px solid rgba(255, 255, 255, 0.2); 
            padding: 2rem; 
            border-radius: 0.5rem; 
            width: 90%; 
            max-width: 600px; 
            color: #fff; 
            animation: fadeIn 0.3s ease; /* Animation d'entrée */
        }
        .error-message { 
            color: #f87171; 
            font-size: 0.875rem; 
            margin-top: 0.25rem; 
        }
        :root {
            --color-light-bg: #f9fafb;
            --color-light-text: #1f2937;
            --color-dark-bg: #111827;
            --color-dark-text: #d1d5db;
        }
        .theme-light body {
            background-color: var(--color-light-bg);
            color: var(--color-light-text);
        }
        .theme-dark body {
            background-color: var(--color-dark-bg);
            color: var(--color-dark-text);
        }
        @media (max-width: 768px) {
            /* Ajustements pour les petits écrans */
            .header__title {
                font-size: 1.25rem;
            }
            .sidebar {
                width: 100%;
                height: auto;
                order: 2; /* Positionner la barre latérale en dessous sur mobile */
            }
            .main-content {
                order: 1; /* Contenu principal en premier sur mobile */
            }
        }
        @keyframes fadeIn {
            from { opacity: 0; transform: scale(0.95); }
            to { opacity: 1; transform: scale(1); }
        }
        /* Styles pour Accessibilité et Convivialité */
        .accessible-focus:focus {
            outline: 2px dashed #fff;
            outline-offset: 2px;
        }
    </style>
</head>
<body class="bg-gray-900 text-gray-100 theme-dark">
    <!-- En-tête -->
    <header class="header bg-gray-800 shadow-md p-4 flex justify-between items-center glass-effect">
        <div class="header__left flex items-center">
            <i class="fas fa-warehouse text-green-500 text-3xl mr-2" aria-hidden="true" role="img" aria-label="Entrepôt"></i>
            <h1 class="header__title text-xl font-bold">Système Avancé de Gestion de Stock</h1>
        </div>
        <div class="header__right flex items-center space-x-4">
            <button class="header__button text-gray-400 hover:text-gray-200 accessible-focus" aria-label="Notifications" data-tippy-content="Notifications">
                <i class="fas fa-bell" aria-hidden="true"></i>
            </button>
            <button id="profileButton" class="header__button text-gray-400 hover:text-gray-200 accessible-focus" aria-label="Profil de l'Utilisateur" data-tippy-content="Profil de l'Utilisateur">
                <i class="fas fa-user-circle" aria-hidden="true"></i>
            </button>
            <button class="header__button text-gray-400 hover:text-gray-200 accessible-focus" aria-label="Aide" data-tippy-content="Aide">
                <i class="fas fa-question-circle" aria-hidden="true"></i>
            </button>
            <button id="loginButton" class="header__button header__button--login bg-blue-500 text-white px-4 py-2 rounded-md hover:bg-blue-600 transition duration-300 accessible-focus" aria-label="Connexion" data-tippy-content="Connexion">Connexion</button>
            <button id="signupButton" class="header__button header__button--signup bg-purple-500 text-white px-4 py-2 rounded-md hover:bg-purple-600 transition duration-300 accessible-focus" aria-label="Inscription" data-tippy-content="Inscription">Inscription</button>
        </div>
    </header>

    <!-- Disposition -->
    <div class="layout flex flex-col lg:flex-row">
        <!-- Barre Latérale -->
        <nav class="sidebar bg-gray-800 w-full lg:w-80 h-auto lg:h-screen shadow-md p-4 glass-effect">
            <ul class="sidebar__menu space-y-4">
                <li>
                    <a href="#" id="dashboardMenu" class="sidebar__item flex items-center text-gray-100 p-4 rounded-lg bg-blue-500 hover:bg-blue-600 transition duration-300 active:bg-blue-700 accessible-focus" aria-label="Tableau de Bord" data-tippy-content="Tableau de Bord">
                        <i class="fas fa-tachometer-alt mr-2" aria-hidden="true" role="img" aria-label="Tableau de Bord"></i>Tableau de Bord
                    </a>
                </li>
                <li>
                    <a href="#" id="inventoryMenu" class="sidebar__item flex items-center text-gray-100 p-4 rounded-lg bg-green-500 hover:bg-green-600 transition duration-300 accessible-focus" aria-label="Inventaire" data-tippy-content="Inventaire">
                        <i class="fas fa-boxes mr-2" aria-hidden="true" role="img" aria-label="Inventaire"></i>Inventaire
                    </a>
                </li>
                <li>
                    <a href="#" id="favoritesMenu" class="sidebar__item flex items-center text-gray-100 p-4 rounded-lg bg-yellow-500 hover:bg-yellow-600 transition duration-300 accessible-focus" aria-label="Favoris" data-tippy-content="Favoris">
                        <i class="fas fa-star mr-2" aria-hidden="true" role="img" aria-label="Favoris"></i>Favoris
                    </a>
                </li>
                <li>
                    <a href="#" id="analyticsMenu" class="sidebar__item flex items-center text-gray-100 p-4 rounded-lg bg-red-500 hover:bg-red-600 transition duration-300 accessible-focus" aria-label="Analyses" data-tippy-content="Analyses">
                        <i class="fas fa-chart-bar mr-2" aria-hidden="true" role="img" aria-label="Analyses"></i>Analyses
                    </a>
                </li>
                <li>
                    <a href="#" id="backupMenu" class="sidebar__item flex items-center text-gray-100 p-4 rounded-lg bg-purple-500 hover:bg-purple-600 transition duration-300 accessible-focus" aria-label="Sauvegarde et Exportation" data-tippy-content="Sauvegarde et Exportation">
                        <i class="fas fa-database mr-2" aria-hidden="true" role="img" aria-label="Sauvegarde et Exportation"></i>Sauvegarde et Exportation
                    </a>
                </li>
                <li>
                    <a href="#" id="settingsMenu" class="sidebar__item flex items-center text-gray-100 p-4 rounded-lg bg-pink-500 hover:bg-pink-600 transition duration-300 accessible-focus" aria-label="Paramètres" data-tippy-content="Paramètres">
                        <i class="fas fa-cog mr-2" aria-hidden="true" role="img" aria-label="Paramètres"></i>Paramètres
                    </a>
                </li>
                <li>
                    <a href="#" id="profileMenu" class="sidebar__item flex items-center text-gray-100 p-4 rounded-lg bg-teal-500 hover:bg-teal-600 transition duration-300 accessible-focus" aria-label="Profil" data-tippy-content="Profil">
                        <i class="fas fa-user mr-2" aria-hidden="true" role="img" aria-label="Profil"></i>Profil
                    </a>
                </li>
                <li>
                    <a href="#" id="historyMenu" class="sidebar__item flex items-center text-gray-100 p-4 rounded-lg bg-indigo-500 hover:bg-indigo-600 transition duration-300 accessible-focus" aria-label="Historique" data-tippy-content="Historique">
                        <i class="fas fa-history mr-2" aria-hidden="true" role="img" aria-label="Historique"></i>Historique
                    </a>
                </li>
                <li>
                    <a href="#" id="logoutMenu" class="sidebar__item flex items-center text-gray-100 p-4 rounded-lg bg-red-600 hover:bg-red-700 transition duration-300 accessible-focus" aria-label="Déconnexion" data-tippy-content="Déconnexion">
                        <i class="fas fa-sign-out-alt mr-2" aria-hidden="true" role="img" aria-label="Déconnexion"></i>Déconnexion
                    </a>
                </li>
            </ul>
        </nav>

        <!-- Contenu Principal -->
        <main class="main-content flex-1 p-6">
            <!-- Tableau de Bord -->
            <section id="dashboard" class="section">
                <h2 class="section__title text-xl font-semibold mb-4">Tableau de Bord</h2>
                <div class="dashboard__stats grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-6 mb-6">
                    <div class="dashboard__card bg-gray-700 p-4 rounded-lg shadow-md flex items-center glass-effect">
                        <i class="fas fa-boxes text-blue-500 text-3xl mr-4" aria-hidden="true" role="img" aria-label="Total des Articles"></i>
                        <div>
                            <h3 class="dashboard__card-title text-lg font-semibold">Total des Articles</h3>
                            <p class="dashboard__card-value text-2xl font-bold" id="totalItems">0</p>
                        </div>
                    </div>
                    <div class="dashboard__card bg-gray-700 p-4 rounded-lg shadow-md flex items-center glass-effect">
                        <i class="fas fa-check-circle text-green-500 text-3xl mr-4" aria-hidden="true" role="img" aria-label="Articles en Utilisation"></i>
                        <div>
                            <h3 class="dashboard__card-title text-lg font-semibold">Articles en Utilisation</h3>
                            <p class="dashboard__card-value text-2xl font-bold" id="itemsInUse">0</p>
                        </div>
                    </div>
                    <div class="dashboard__card bg-gray-700 p-4 rounded-lg shadow-md flex items-center glass-effect">
                        <i class="fas fa-warehouse text-yellow-500 text-3xl mr-4" aria-hidden="true" role="img" aria-label="Disponibles"></i>
                        <div>
                            <h3 class="dashboard__card-title text-lg font-semibold">Disponibles</h3>
                            <p class="dashboard__card-value text-2xl font-bold" id="itemsInStock">0</p>
                        </div>
                    </div>
                    <div class="dashboard__card bg-gray-700 p-4 rounded-lg shadow-md flex items-center glass-effect">
                        <i class="fas fa-tools text-red-500 text-3xl mr-4" aria-hidden="true" role="img" aria-label="En Maintenance"></i>
                        <div>
                            <h3 class="dashboard__card-title text-lg font-semibold">En Maintenance</h3>
                            <p class="dashboard__card-value text-2xl font-bold" id="itemsUnderMaintenance">0</p>
                        </div>
                    </div>
                </div>
                <div class="dashboard__activities bg-gray-800 p-6 rounded-lg shadow-md mb-6 glass-effect" aria-live="polite">
                    <h3 class="dashboard__activities-title text-xl font-semibold mb-4">Activités Récentes</h3>
                    <ul class="dashboard__activities-list space-y-4" id="recentActivities"></ul>
                </div>
                <!-- Tableau de Bord - Graphiques Statistiques -->
                <div class="dashboard__charts grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                    <div class="dashboard__chart bg-gray-800 p-4 rounded-lg shadow-md glass-effect">
                        <h3 class="dashboard__chart-title text-lg font-semibold mb-2">Répartition par Type d'Article</h3>
                        <canvas id="typeChart" tabindex="0" aria-label="Graphique des Types d'Articles montrant une répartition entre Téléphones, Ordinateurs, Tablettes et PC" role="img"></canvas>
                    </div>
                    <div class="dashboard__chart bg-gray-800 p-4 rounded-lg shadow-md glass-effect">
                        <h3 class="dashboard__chart-title text-lg font-semibold mb-2">Répartition par Statut</h3>
                        <canvas id="statusChart" tabindex="0" aria-label="Graphique des Statuts" role="img"></canvas>
                    </div>
                    <div class="dashboard__chart bg-gray-800 p-4 rounded-lg shadow-md glass-effect">
                        <h3 class="dashboard__chart-title text-lg font-semibold mb-2">Répartition par Localisation</h3>
                        <canvas id="locationChart" tabindex="0" aria-label="Graphique des Localisations" role="img"></canvas>
                    </div>
                </div>
            </section>

            <!-- Inventaire -->
            <section id="inventory" class="section hidden">
                <div class="inventory__header flex flex-col md:flex-row justify-between items-center mb-6 space-y-4 md:space-y-0">
                    <h2 class="section__title text-xl font-semibold">Inventaire</h2>
                    <div class="inventory__actions flex space-x-2">
                        <button id="addItemButton" class="inventory__button inventory__button--add bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-md flex items-center transition duration-300 accessible-focus" aria-label="Ajouter un Nouvel Article" data-tippy-content="Ajouter un Nouvel Article">
                            <i class="fas fa-plus mr-2" aria-hidden="true" role="img" aria-label="Ajouter"></i>Nouvel Article
                        </button>
                        <button id="importButton" class="inventory__button inventory__button--import bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md flex items-center transition duration-300 accessible-focus" aria-label="Importer des Articles" data-tippy-content="Importer des Articles">
                            <i class="fas fa-file-import mr-2" aria-hidden="true" role="img" aria-label="Importer"></i>Importer
                        </button>
                        <button id="exportJsonButton" class="inventory__button inventory__button--export-json bg-purple-500 hover:bg-purple-600 text-white px-4 py-2 rounded-md flex items-center transition duration-300 accessible-focus" aria-label="Exporter en JSON" data-tippy-content="Exporter en JSON">
                            <i class="fas fa-download mr-2" aria-hidden="true" role="img" aria-label="Exporter en JSON"></i>Exporter JSON
                        </button>
                        <button id="exportCsvButton" class="inventory__button inventory__button--export-csv bg-purple-500 hover:bg-purple-600 text-white px-4 py-2 rounded-md flex items-center transition duration-300 accessible-focus" aria-label="Exporter en CSV" data-tippy-content="Exporter en CSV">
                            <i class="fas fa-download mr-2" aria-hidden="true" role="img" aria-label="Exporter en CSV"></i>Exporter CSV
                        </button>
                        <button id="generateReportButton" class="inventory__button inventory__button--generate-report bg-gray-500 hover:bg-gray-600 text-white px-4 py-2 rounded-md flex items-center transition duration-300 accessible-focus" aria-label="Générer un Rapport" data-tippy-content="Générer un Rapport">
                            <i class="fas fa-chart-bar mr-2" aria-hidden="true" role="img" aria-label="Générer un Rapport"></i>Rapport
                        </button>
                        <input type="file" id="importFileInput" accept=".csv,.json" class="hidden" aria-hidden="true" />
                    </div>
                </div>
                <div class="inventory__filters bg-gray-800 p-4 rounded-lg mb-6">
                    <div class="inventory__filters-grid grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
                        <input type="text" id="searchInput" name="search" placeholder="Rechercher par ID, type, tag..." class="inventory__search-input w-full p-2 rounded-md bg-gray-700 border border-gray-600 focus:outline-none focus:ring-2 focus:ring-blue-500 transition duration-300 accessible-focus" aria-label="Recherche" />
                        <select id="filterStatus" name="filterStatus" class="inventory__filter bg-gray-700 p-2 rounded-md border border-gray-600 focus:outline-none focus:ring-2 focus:ring-blue-500 transition duration-300 accessible-focus" aria-label="Filtrer par Statut">
                            <option value="">Statut</option>
                            <option>En Exploitation</option>
                            <option>Disponible</option>
                            <option>Pending Repair</option>
                            <option>Pending Disposal</option>
                            <option>Indisponible Temporairement</option>
                            <option>Inconnu</option>
                            <option>En Utilisation</option>
                        </select>
                        <select id="filterLocation" name="filterLocation" class="inventory__filter bg-gray-700 p-2 rounded-md border border-gray-600 focus:outline-none focus:ring-2 focus:ring-blue-500 transition duration-300 accessible-focus" aria-label="Filtrer par Localisation">
                            <option value="">Localisation</option>
                            <option>IT BAR</option>
                            <option>En Stock</option>
                            <option>Hors Stock</option>
                            <option>Inconnu</option>
                        </select>
                        <select id="filterCondition" name="filterCondition" class="inventory__filter bg-gray-700 p-2 rounded-md border border-gray-600 focus:outline-none focus:ring-2 focus:ring-blue-500 transition duration-300 accessible-focus" aria-label="Filtrer par Condition">
                            <option value="">Condition</option>
                            <option>Neuf</option>
                            <option>Bon</option>
                            <option>Moyen</option>
                            <option>Mauvais</option>
                        </select>
                    </div>
                </div>
                <div class="inventory__table bg-gray-800 rounded-lg overflow-hidden">
                    <div class="inventory__table-container overflow-x-auto">
                        <table class="inventory__table min-w-full divide-y divide-gray-700">
                            <thead class="inventory__table-header bg-gray-700">
                                <tr>
                                    <th class="p-3 text-left">
                                        <input type="checkbox" class="form-checkbox accessible-focus" id="selectAll" aria-label="Tout Sélectionner" data-tippy-content="Tout Sélectionner" />
                                    </th>
                                    <th class="p-3 text-left cursor-pointer accessible-focus" data-column="id" tabindex="0" role="button" aria-sort="none">ID <i class="fas fa-sort"></i></th>
                                    <th class="p-3 text-left cursor-pointer accessible-focus" data-column="type" tabindex="0" role="button" aria-sort="none">Type d'Article <i class="fas fa-sort"></i></th>
                                    <th class="p-3 text-left cursor-pointer accessible-focus" data-column="tag" tabindex="0" role="button" aria-sort="none">Tag <i class="fas fa-sort"></i></th>
                                    <th class="p-3 text-left cursor-pointer accessible-focus" data-column="status" tabindex="0" role="button" aria-sort="none">Statut <i class="fas fa-sort"></i></th>
                                    <th class="p-3 text-left cursor-pointer accessible-focus" data-column="location" tabindex="0" role="button" aria-sort="none">Localisation <i class="fas fa-sort"></i></th>
                                    <th class="p-3 text-left cursor-pointer accessible-focus" data-column="serial_number" tabindex="0" role="button" aria-sort="none">Numéro de Série <i class="fas fa-sort"></i></th>
                                    <th class="p-3 text-left cursor-pointer accessible-focus" data-column="incident_number" tabindex="0" role="button" aria-sort="none">Numéro d'Incident <i class="fas fa-sort"></i></th>
                                    <th class="p-3 text-left cursor-pointer accessible-focus" data-column="problem_description" tabindex="0" role="button" aria-sort="none">Description de Panne <i class="fas fa-sort"></i></th>
                                    <th class="p-3 text-left cursor-pointer accessible-focus" data-column="last_update" tabindex="0" role="button" aria-sort="none">Dernière Mise à Jour <i class="fas fa-sort"></i></th>
                                    <th class="p-3 text-left cursor-pointer accessible-focus" data-column="favorite" tabindex="0" role="button" aria-sort="none">Favori <i class="fas fa-sort"></i></th>
                                    <th class="p-3 text-left">Actions</th>
                                </tr>
                            </thead>
                            <tbody class="inventory__table-body divide-y divide-gray-700" id="inventoryTableBody"></tbody>
                        </table>
                    </div>
                    <div class="inventory__pagination flex justify-between items-center p-4 border-t border-gray-700">
                        <div class="inventory__pagination-info text-sm text-gray-400" id="paginationInfo">Affichage 0-0 de 0 articles</div>
                        <div class="inventory__pagination-controls flex space-x-2">
                            <button class="inventory__pagination-button px-3 py-1 rounded bg-gray-700 hover:bg-gray-600 transition duration-300 accessible-focus" id="prevPage" aria-label="Page Précédente" data-tippy-content="Page Précédente">Précédente</button>
                            <span class="inventory__current-page text-sm text-gray-400" id="currentPage">1</span>
                            <button class="inventory__pagination-button px-3 py-1 rounded bg-gray-700 hover:bg-gray-600 transition duration-300 accessible-focus" id="nextPage" aria-label="Page Suivante" data-tippy-content="Page Suivante">Suivante</button>
                        </div>
                    </div>
                </div>
                <div id="bulkActions" class="inventory__bulk-actions hidden space-x-2 mt-4 flex flex-wrap">
                    <button id="deleteSelected" class="inventory__bulk-button inventory__bulk-button--delete bg-red-500 hover:bg-red-600 text-white px-4 py-2 rounded-md flex items-center transition duration-300 accessible-focus" aria-label="Supprimer Sélectionnés" data-tippy-content="Supprimer Sélectionnés">
                        <i class="fas fa-trash mr-2" aria-hidden="true" role="img" aria-label="Supprimer"></i>Supprimer Sélectionnés
                    </button>
                    <button id="changeStatusSelected" class="inventory__bulk-button inventory__bulk-button--change-status bg-yellow-500 hover:bg-yellow-600 text-white px-4 py-2 rounded-md flex items-center transition duration-300 accessible-focus" aria-label="Modifier le Statut" data-tippy-content="Modifier le Statut">
                        <i class="fas fa-edit mr-2" aria-hidden="true" role="img" aria-label="Modifier"></i>Modifier le Statut
                    </button>
                    <button id="changeLocationSelected" class="inventory__bulk-button inventory__bulk-button--change-location bg-purple-500 hover:bg-purple-600 text-white px-4 py-2 rounded-md flex items-center transition duration-300 accessible-focus" aria-label="Modifier la Localisation" data-tippy-content="Modifier la Localisation">
                        <i class="fas fa-map-marker-alt mr-2" aria-hidden="true" role="img" aria-label="Modifier la Localisation"></i>Modifier la Localisation
                    </button>
                </div>
            </section>

            <!-- Favoris -->
            <section id="favorites" class="section hidden">
                <div class="favorites__header flex justify-between items-center mb-6">
                    <h2 class="section__title text-xl font-semibold">Favoris</h2>
                    <button id="refreshFavorites" class="favorites__refresh-button bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md flex items-center transition duration-300 accessible-focus" aria-label="Actualiser les Favoris" data-tippy-content="Actualiser les Favoris">
                        <i class="fas fa-sync mr-2" aria-hidden="true" role="img" aria-label="Actualiser"></i>Actualiser
                    </button>
                </div>
                <div class="favorites__table bg-gray-800 rounded-lg overflow-hidden">
                    <div class="favorites__table-container overflow-x-auto">
                        <table class="favorites__table min-w-full divide-y divide-gray-700">
                            <thead class="favorites__table-header bg-gray-700">
                                <tr>
                                    <th class="p-3 text-left">ID</th>
                                    <th class="p-3 text-left">Type d'Article</th>
                                    <th class="p-3 text-left">Tag</th>
                                    <th class="p-3 text-left">Statut</th>
                                    <th class="p-3 text-left">Localisation</th>
                                    <th class="p-3 text-left">Numéro de Série</th>
                                    <th class="p-3 text-left">Numéro d'Incident</th>
                                    <th class="p-3 text-left">Description de Panne</th>
                                    <th class="p-3 text-left">Dernière Mise à Jour</th>
                                    <th class="p-3 text-left">Actions</th>
                                </tr>
                            </thead>
                            <tbody class="favorites__table-body divide-y divide-gray-700" id="favoritesTableBody"></tbody>
                        </table>
                    </div>
                </div>
            </section>

            <!-- Analyses -->
            <section id="analytics" class="section hidden">
                <h2 class="section__title text-xl font-semibold mb-4">Analyses</h2>
                <div class="analytics__charts grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                    <div class="analytics__chart bg-gray-800 p-4 rounded-lg shadow-md glass-effect">
                        <h3 class="analytics__chart-title text-lg font-semibold mb-2">Répartition par Type d'Article</h3>
                        <canvas id="typeChart" tabindex="0" aria-label="Graphique des Types d'Articles montrant une répartition entre Téléphones, Ordinateurs, Tablettes et PC" role="img"></canvas>
                    </div>
                    <div class="analytics__chart bg-gray-800 p-4 rounded-lg shadow-md glass-effect">
                        <h3 class="analytics__chart-title text-lg font-semibold mb-2">Répartition par Statut</h3>
                        <canvas id="statusChart" tabindex="0" aria-label="Graphique des Statuts" role="img"></canvas>
                    </div>
                    <div class="analytics__chart bg-gray-800 p-4 rounded-lg shadow-md glass-effect">
                        <h3 class="analytics__chart-title text-lg font-semibold mb-2">Répartition par Localisation</h3>
                        <canvas id="locationChart" tabindex="0" aria-label="Graphique des Localisations" role="img"></canvas>
                    </div>
                </div>
            </section>

            <!-- Sauvegarde et Exportation -->
            <section id="backup" class="section hidden">
                <h2 class="section__title text-xl font-semibold mb-4">Sauvegarde et Exportation</h2>
                <div class="backup__container bg-gray-800 p-6 rounded-lg shadow-md glass-effect">
                    <div class="backup__options flex flex-col md:flex-row md:space-x-4">
                        <div class="backup__option flex-1 mb-4 md:mb-0">
                            <h3 class="backup__option-title text-lg font-semibold mb-2">Faire une Sauvegarde</h3>
                            <div class="backup__buttons flex space-x-2">
                                <button id="backupJson" class="backup__button bg-green-500 hover:bg-green-600 text-white px-4 py-2 rounded-md flex items-center transition duration-300 accessible-focus" aria-label="Exporter en JSON" data-tippy-content="Exporter en JSON">
                                    <i class="fas fa-download mr-2" aria-hidden="true" role="img" aria-label="Exporter en JSON"></i>Exporter JSON
                                </button>
                                <button id="backupCsv" class="backup__button bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded-md flex items-center transition duration-300 accessible-focus" aria-label="Exporter en CSV" data-tippy-content="Exporter en CSV">
                                    <i class="fas fa-download mr-2" aria-hidden="true" role="img" aria-label="Exporter en CSV"></i>Exporter CSV
                                </button>
                            </div>
                        </div>
                        <div class="backup__option flex-1">
                            <h3 class="backup__option-title text-lg font-semibold mb-2">Restaurer une Sauvegarde</h3>
                            <button id="restoreBackup" class="backup__button bg-red-500 hover:bg-red-600 text-white px-4 py-2 rounded-md flex items-center transition duration-300 accessible-focus" aria-label="Restaurer une Sauvegarde" data-tippy-content="Restaurer une Sauvegarde">
                                <i class="fas fa-upload mr-2" aria-hidden="true" role="img" aria-label="Restaurer"></i>Restaurer la Sauvegarde
                            </button>
                            <input type="file" id="restoreFileInput" accept=".json,.csv" class="hidden" aria-hidden="true" />
                        </div>
                    </div>
                </div>
            </section>

            <!-- Paramètres -->
            <section id="settings" class="section hidden">
                <h2 class="section__title text-xl font-semibold mb-4">Paramètres</h2>
                <div class="settings__container bg-gray-800 p-6 rounded-lg shadow-md glass-effect">
                    <form id="settingsForm">
                        <div class="settings__field mb-4">
                            <label class="block mb-2 font-semibold" for="theme">Thème</label>
                            <div class="settings__theme-options flex items-center space-x-4">
                                <label class="flex items-center">
                                    <input type="radio" name="theme" value="light" class="form-radio accessible-focus" onchange="toggleTheme('light')" aria-label="Thème Clair" data-tippy-content="Thème Clair"/>
                                    <span class="ml-2">Clair</span>
                                </label>
                                <label class="flex items-center">
                                    <input type="radio" name="theme" value="dark" class="form-radio accessible-focus" onchange="toggleTheme('dark')" aria-label="Thème Sombre" data-tippy-content="Thème Sombre"/>
                                    <span class="ml-2">Sombre</span>
                                </label>
                            </div>
                        </div>
                        <div class="settings__field mb-4">
                            <label class="block mb-2 font-semibold" for="notifications">Notifications</label>
                            <label class="flex items-center">
                                <input type="checkbox" id="notifications" class="form-checkbox accessible-focus" aria-label="Activer les Notifications" data-tippy-content="Activer les Notifications"/>
                                <span class="ml-2">Activer les Notifications</span>
                            </label>
                        </div>
                        <div class="settings__field mb-4">
                            <label class="block mb-2 font-semibold" for="additionalPreferences">Préférences Supplémentaires</label>
                            <textarea id="additionalPreferences" name="additionalPreferences" rows="4" placeholder="Décrivez vos préférences..." class="settings__textarea w-full p-2 rounded-md bg-gray-700 border border-gray-600 focus:outline-none focus:ring-2 focus:ring-blue-500 transition duration-300 accessible-focus"></textarea>
                        </div>
                        <div class="settings__actions flex justify-end space-x-2">
                            <button type="button" onclick="saveSettings()" class="settings__button settings__button--save px-4 py-2 bg-blue-500 rounded-md hover:bg-blue-600 transition duration-300 accessible-focus" aria-label="Sauvegarder les Paramètres" data-tippy-content="Sauvegarder les Paramètres">Sauvegarder les Paramètres</button>
                            <button type="button" onclick="resetSettings()" class="settings__button settings__button--reset px-4 py-2 bg-gray-600 rounded-md hover:bg-gray-700 transition duration-300 accessible-focus" aria-label="Restaurer les Paramètres par Défaut" data-tippy-content="Restaurer les Paramètres par Défaut">Restaurer les Paramètres par Défaut</button>
                        </div>
                    </form>
                </div>
            </section>

            <!-- Profil -->
            <section id="profile" class="section hidden">
                <h2 class="section__title text-xl font-semibold mb-4">Profil</h2>
                <div class="profile__container bg-gray-800 p-6 rounded-lg shadow-md glass-effect">
                    <form id="profileForm">
                        <div class="profile__field mb-4">
                            <label for="profileName" class="block mb-2">Nom</label>
                            <input type="text" id="profileName" name="profileName" required class="profile__input w-full p-2 rounded-md bg-gray-700 border border-gray-600 focus:outline-none focus:ring-2 focus:ring-purple-500 transition duration-300 accessible-focus" aria-label="Nom" />
                            <div id="profileNameError" class="error-message hidden">Veuillez entrer votre nom.</div>
                        </div>
                        <div class="profile__field mb-4">
                            <label for="profileEmail" class="block mb-2">E-mail</label>
                            <input type="email" id="profileEmail" name="profileEmail" required class="profile__input w-full p-2 rounded-md bg-gray-700 border border-gray-600 focus:outline-none focus:ring-2 focus:ring-purple-500 transition duration-300 accessible-focus" aria-label="E-mail" />
                            <div id="profileEmailError" class="error-message hidden">Veuillez entrer un e-mail valide.</div>
                        </div>
                        <div class="profile__field mb-4">
                            <label for="profilePassword" class="block mb-2">Mot de Passe</label>
                            <input type="password" id="profilePassword" name="profilePassword" minlength="6" class="profile__input w-full p-2 rounded-md bg-gray-700 border border-gray-600 focus:outline-none focus:ring-2 focus:ring-purple-500 transition duration-300 accessible-focus" aria-label="Mot de Passe" />
                            <div id="profilePasswordError" class="error-message hidden">Le mot de passe doit contenir au moins 6 caractères.</div>
                        </div>
                        <div class="profile__actions flex justify-end space-x-2">
                            <button type="button" onclick="updateProfile()" class="profile__button profile__button--update px-4 py-2 bg-green-500 rounded-md hover:bg-green-600 transition duration-300 accessible-focus" aria-label="Mettre à Jour le Profil" data-tippy-content="Mettre à Jour le Profil">Mettre à Jour le Profil</button>
                        </div>
                    </form>
                </div>
            </section>

            <!-- Historique -->
            <section id="history" class="section hidden">
                <h2 class="section__title text-xl font-semibold mb-4">Historique</h2>
                <div class="history__content bg-gray-800 p-6 rounded-lg shadow-md glass-effect">
                    <p>Contenu de la section Historique.</p>
                </div>
            </section>

            <!-- Déconnexion -->
            <section id="logout" class="section hidden">
                <h2 class="section__title text-xl font-semibold mb-4">Déconnexion</h2>
                <div class="logout__container bg-gray-800 p-6 rounded-lg shadow-md glass-effect">
                    <p>Vous êtes sur le point de quitter le système.</p>
                    <button id="confirmLogout" class="logout__button mt-4 bg-red-500 text-white px-4 py-2 rounded-md hover:bg-red-600 transition duration-300 accessible-focus" aria-label="Confirmer la Déconnexion" data-tippy-content="Confirmer la Déconnexion">Confirmer la Déconnexion</button>
                </div>
            </section>
        </main>
    </div>

    <!-- Pied de Page -->
    <footer class="footer bg-gray-800 shadow-md p-4 flex justify-between items-center glass-effect">
        <div class="footer__links flex space-x-4">
            <button class="footer__link text-gray-400 hover:text-gray-200 accessible-focus" aria-label="Paramètres de Notifications" data-tippy-content="Paramètres de Notifications">Paramètres de Notifications</button>
            <button class="footer__link text-gray-400 hover:text-gray-200 accessible-focus" aria-label="Envoyer des Commentaires" data-tippy-content="Envoyer des Commentaires">Envoyer des Commentaires</button>
        </div>
    </footer>

    <!-- Modaux -->
    <!-- Modal de Connexion -->
    <div id="loginModal" class="modal hidden" tabindex="-1" aria-hidden="true">
        <div class="modal-content" role="dialog" aria-modal="true" aria-labelledby="loginModalTitle">
            <h2 class="modal__title text-2xl mb-4" id="loginModalTitle">Connexion</h2>
            <form id="loginForm">
                <div class="modal__field mb-4">
                    <label for="loginEmail" class="block mb-2">E-mail</label>
                    <input type="email" id="loginEmail" name="loginEmail" required class="modal__input w-full p-2 rounded-md bg-gray-700 border border-gray-600 focus:outline-none focus:ring-2 focus:ring-blue-500 transition duration-300 accessible-focus"/>
                    <div id="loginEmailError" class="error-message hidden">Veuillez entrer un e-mail valide.</div>
                </div>
                <div class="modal__field mb-4">
                    <label for="loginPassword" class="block mb-2">Mot de Passe</label>
                    <input type="password" id="loginPassword" name="loginPassword" required class="modal__input w-full p-2 rounded-md bg-gray-700 border border-gray-600 focus:outline-none focus:ring-2 focus:ring-blue-500 transition duration-300 accessible-focus"/>
                    <div id="loginPasswordError" class="error-message hidden">Veuillez entrer votre mot de passe.</div>
                </div>
                <div id="loginError" class="error-message mb-4 hidden">Identifiants invalides. Veuillez réessayer.</div>
                <div class="modal__actions flex justify-end space-x-2">
                    <button type="button" onclick="closeModal('loginModal')" class="modal__button modal__button--cancel px-4 py-2 bg-gray-600 rounded-md hover:bg-gray-700 transition duration-300 accessible-focus" aria-label="Annuler la Connexion" data-tippy-content="Annuler la Connexion">Annuler</button>
                    <button type="submit" class="modal__button modal__button--submit px-4 py-2 bg-blue-500 rounded-md hover:bg-blue-600 transition duration-300 accessible-focus" aria-label="Envoyer la Connexion" data-tippy-content="Envoyer la Connexion">Se Connecter</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Modal d'Inscription -->
    <div id="signupModal" class="modal hidden" tabindex="-1" aria-hidden="true">
        <div class="modal-content" role="dialog" aria-modal="true" aria-labelledby="signupModalTitle">
            <h2 class="modal__title text-2xl mb-4" id="signupModalTitle">Inscription</h2>
            <form id="signupForm">
                <div class="modal__field mb-4">
                    <label for="signupName" class="block mb-2">Nom</label>
                    <input type="text" id="signupName" name="signupName" required class="modal__input w-full p-2 rounded-md bg-gray-700 border border-gray-600 focus:outline-none focus:ring-2 focus:ring-purple-500 transition duration-300 accessible-focus"/>
                    <div id="signupNameError" class="error-message hidden">Veuillez entrer votre nom.</div>
                </div>
                <div class="modal__field mb-4">
                    <label for="signupEmail" class="block mb-2">E-mail</label>
                    <input type="email" id="signupEmail" name="signupEmail" required class="modal__input w-full p-2 rounded-md bg-gray-700 border border-gray-600 focus:outline-none focus:ring-2 focus:ring-purple-500 transition duration-300 accessible-focus"/>
                    <div id="signupEmailError" class="error-message hidden">Veuillez entrer un e-mail valide.</div>
                </div>
                <div class="modal__field mb-4">
                    <label for="signupPassword" class="block mb-2">Mot de Passe</label>
                    <input type="password" id="signupPassword" name="signupPassword" required minlength="6" class="modal__input w-full p-2 rounded-md bg-gray-700 border border-gray-600 focus:outline-none focus:ring-2 focus:ring-purple-500 transition duration-300 accessible-focus"/>
                    <div id="signupPasswordError" class="error-message hidden">Le mot de passe doit contenir au moins 6 caractères.</div>
                </div>
                <div id="signupError" class="error-message mb-4 hidden">Erreur lors de l'inscription. Veuillez réessayer.</div>
                <div class="modal__actions flex justify-end space-x-2">
                    <button type="button" onclick="closeModal('signupModal')" class="modal__button modal__button--cancel px-4 py-2 bg-gray-600 rounded-md hover:bg-gray-700 transition duration-300 accessible-focus" aria-label="Annuler l'Inscription" data-tippy-content="Annuler l'Inscription">Annuler</button>
                    <button type="submit" class="modal__button modal__button--submit px-4 py-2 bg-purple-500 rounded-md hover:bg-purple-600 transition duration-300 accessible-focus" aria-label="Envoyer l'Inscription" data-tippy-content="Envoyer l'Inscription">S'inscrire</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Modal d'Article -->
    <div id="itemModal" class="modal hidden" tabindex="-1" aria-hidden="true">
        <div class="modal-content" role="dialog" aria-modal="true" aria-labelledby="itemModalTitle">
            <h2 class="modal__title text-2xl mb-4" id="itemModalTitle">Ajouter un Article</h2>
            <form id="itemForm">
                <div class="modal__fields grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div class="modal__field mb-4">
                        <label for="itemType" class="block mb-2">Type d'Article</label>
                        <select id="itemType" name="itemType" required class="modal__select w-full p-2 rounded-md bg-gray-700 border border-gray-600 focus:outline-none focus:ring-2 focus:ring-green-500 transition duration-300 accessible-focus" aria-required="true">
                            <option value="">Sélectionnez le type</option>
                            <option>Ordinateur</option>
                            <option>Téléphone</option>
                            <option>Tablette</option>
                            <option>PC</option>
                        </select>
                        <div id="itemTypeError" class="error-message hidden">Veuillez sélectionner le type d'article.</div>
                    </div>
                    <div class="modal__field mb-4">
                        <label for="itemTag" class="block mb-2">Tag/Code</label>
                        <input type="text" id="itemTag" name="itemTag" required class="modal__input w-full p-2 rounded-md bg-gray-700 border border-gray-600 focus:outline-none focus:ring-2 focus:ring-green-500 transition duration-300 accessible-focus" aria-label="Tag/Code" />
                        <div id="itemTagError" class="error-message hidden">Veuillez entrer le Tag/Code.</div>
                    </div>
                    <div class="modal__field mb-4">
                        <label for="itemStatus" class="block mb-2">Statut</label>
                        <select id="itemStatus" name="itemStatus" required class="modal__select w-full p-2 rounded-md bg-gray-700 border border-gray-600 focus:outline-none focus:ring-2 focus:ring-green-500 transition duration-300 accessible-focus" onchange="toggleMaintenanceFields()" aria-required="true">
                            <option value="">Sélectionnez le statut</option>
                            <option>En Exploitation</option>
                            <option>Disponible</option>
                            <option>Pending Repair</option>
                            <option>Pending Disposal</option>
                            <option>Indisponible Temporairement</option>
                            <option>Inconnu</option>
                            <option>En Utilisation</option>
                        </select>
                        <div id="itemStatusError" class="error-message hidden">Veuillez sélectionner le statut.</div>
                    </div>
                    <div class="modal__field mb-4">
                        <label for="itemLocation" class="block mb-2">Localisation</label>
                        <select id="itemLocation" name="itemLocation" required class="modal__select w-full p-2 rounded-md bg-gray-700 border border-gray-600 focus:outline-none focus:ring-2 focus:ring-green-500 transition duration-300 accessible-focus" aria-required="true">
                            <option value="">Sélectionnez la localisation</option>
                            <option>IT BAR</option>
                            <option>En Stock</option>
                            <option>Hors Stock</option>
                            <option>Inconnu</option>
                        </select>
                        <div id="itemLocationError" class="error-message hidden">Veuillez sélectionner la localisation.</div>
                    </div>
                    <div class="modal__field mb-4">
                        <label for="itemSerialNumber" class="block mb-2">Numéro de Série</label>
                        <input type="text" id="itemSerialNumber" name="itemSerialNumber" required class="modal__input w-full p-2 rounded-md bg-gray-700 border border-gray-600 focus:outline-none focus:ring-2 focus:ring-green-500 transition duration-300 accessible-focus" aria-label="Numéro de Série" />
                        <div id="itemSerialNumberError" class="error-message hidden">Veuillez entrer le numéro de série.</div>
                    </div>
                </div>
                <div id="maintenanceFields" class="modal__maintenance-fields hidden grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div class="modal__field mb-4">
                        <label for="incidentNumber" class="block mb-2">Numéro d'Incident</label>
                        <input type="text" id="incidentNumber" name="incidentNumber" class="modal__input w-full p-2 rounded-md bg-gray-700 border border-gray-600 focus:outline-none focus:ring-2 focus:ring-red-500 transition duration-300 accessible-focus" aria-required="false"/>
                        <div id="incidentNumberError" class="error-message hidden">Veuillez entrer le numéro d'incident.</div>
                    </div>
                    <div class="modal__field mb-4">
                        <label for="problemDescription" class="block mb-2">Description de Panne</label>
                        <textarea id="problemDescription" name="problemDescription" rows="3" class="modal__textarea w-full p-2 rounded-md bg-gray-700 border border-gray-600 focus:outline-none focus:ring-2 focus:ring-red-500 transition duration-300 accessible-focus" aria-required="false"></textarea>
                        <div id="problemDescriptionError" class="error-message hidden">Veuillez décrire le problème.</div>
                    </div>
                </div>
                <div class="modal__field mb-4">
                    <label for="itemFavorite" class="block mb-2">Favori</label>
                    <input type="checkbox" id="itemFavorite" name="itemFavorite" class="modal__checkbox rounded-md bg-gray-700 border border-gray-600 focus:outline-none focus:ring-2 focus:ring-yellow-500 transition duration-300 accessible-focus" aria-label="Marquer comme Favori" data-tippy-content="Marquer comme Favori"/>
                </div>
                <div class="modal__field mb-4">
                    <label for="itemDescription" class="block mb-2">Description</label>
                    <textarea id="itemDescription" name="itemDescription" rows="3" placeholder="Description de l'article..." class="modal__textarea w-full p-2 rounded-md bg-gray-700 border border-gray-600 focus:outline-none focus:ring-2 focus:ring-blue-500 transition duration-300 accessible-focus" aria-label="Description"></textarea>
                </div>
                <div class="modal__actions flex justify-end space-x-2">
                    <button type="button" onclick="closeModal('itemModal')" class="modal__button modal__button--cancel px-4 py-2 bg-gray-600 rounded-md hover:bg-gray-700 transition duration-300 accessible-focus" aria-label="Annuler" data-tippy-content="Annuler">Annuler</button>
                    <button type="submit" class="modal__button modal__button--submit px-4 py-2 bg-green-500 rounded-md hover:bg-green-600 transition duration-300 accessible-focus" aria-label="Enregistrer l'Article" data-tippy-content="Enregistrer l'Article">Enregistrer</button>
                </div>
            </form>
        </div>
    </div>

    <!-- Modal de Confirmation -->
    <div id="confirmModal" class="modal hidden" tabindex="-1" aria-hidden="true">
        <div class="modal-content" role="dialog" aria-modal="true" aria-labelledby="confirmModalTitle">
            <h2 class="modal__title text-2xl mb-4" id="confirmModalTitle">Confirmation</h2>
            <p id="confirmMessage" class="modal__message">Voulez-vous vraiment effectuer cette action ?</p>
            <div class="modal__actions flex justify-end space-x-2 mt-4">
                <button onclick="closeModal('confirmModal')" class="modal__button modal__button--cancel px-4 py-2 bg-gray-600 rounded-md hover:bg-gray-700 transition duration-300 accessible-focus" aria-label="Annuler la Confirmation" data-tippy-content="Annuler">Annuler</button>
                <button id="confirmActionButton" class="modal__button modal__button--confirm px-4 py-2 bg-red-500 rounded-md hover:bg-red-600 transition duration-300 accessible-focus" aria-label="Confirmer l'Action" data-tippy-content="Confirmer">Confirmer</button>
            </div>
        </div>
    </div>

    <!-- Scripts -->
    <script>
        // Initialiser Tippy.js pour les tooltips
        document.addEventListener('DOMContentLoaded', function() {
            tippy('[data-tippy-content]', {
                animation: 'scale',
                theme: 'light',
            });
        });

        // Fonctions Utilitaires
        const Utils = {
            getElement: (id) => document.getElementById(id),
            getElementValue: (id) => Utils.getElement(id).value,
            setRequired: (id, required) => Utils.getElement(id).required = required,
            toggleClass: (id, className, condition) => {
                const element = Utils.getElement(id);
                if (element) {
                    element.classList.toggle(className, condition);
                }
            },
            showElement: (id) => Utils.toggleClass(id, 'hidden', false),
            hideElement: (id) => Utils.toggleClass(id, 'hidden', true),
            clearInput: (id) => {
                const element = Utils.getElement(id);
                if (element.type !== 'checkbox' && element.type !== 'radio') element.value = '';
                if (element.type === 'checkbox' || element.type === 'radio') element.checked = false;
            },
            debounce: (func, wait = 300) => {
                let timeout;
                return function(...args) {
                    clearTimeout(timeout);
                    timeout = setTimeout(() => func.apply(this, args), wait);
                };
            },
            validateEmail: (email) => /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@(([^<>()[\]\\.,;:\s@"]+\.)+[^<>()[\]\\.,;:\s@"]{2,})$/i.test(String(email).toLowerCase()),
            hashPassword: async (password) => {
                const msgUint8 = new TextEncoder().encode(password);
                const hashBuffer = await crypto.subtle.digest('SHA-256', msgUint8);
                const hashArray = Array.from(new Uint8Array(hashBuffer));
                return hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
            }
        };

        // Objet Gestionnaire d'Inventaire
        const inventoryManager = {
            currentPage: 1,
            itemsPerPage: 10,
            sortColumn: 'id',
            sortDirection: 'asc',
            selectedItems: new Set(),
            items: [],
            typeChartInstance: null,
            statusChartInstance: null,
            locationChartInstance: null,

            // Charger les articles depuis localStorage
            loadItems() {
                try {
                    this.items = JSON.parse(localStorage.getItem('inventoryItems')) || [];
                } catch (error) {
                    console.error('Erreur lors du chargement des articles dans l\'inventaire :', error);
                    this.items = [];
                }
            },

            // Sauvegarder les articles dans localStorage
            saveItems() {
                try {
                    localStorage.setItem('inventoryItems', JSON.stringify(this.items));
                } catch (error) {
                    console.error('Erreur lors de la sauvegarde des articles dans l\'inventaire :', error);
                }
            },

            // Ajouter un article
            addItem(item) {
                this.items.push(item);
                this.saveItems();
                this.refreshTable();
                this.updateDashboard();
                this.addActivity(`Article ajouté : ${item.type} (${item.id})`);
            },

            // Mettre à jour un article
            async updateItem(updatedItem) {
                const index = this.items.findIndex(item => item.id === updatedItem.id);
                if (index !== -1) {
                    this.items[index] = updatedItem;
                    this.saveItems();
                    this.refreshTable();
                    this.updateDashboard();
                    this.addActivity(`Article mis à jour : ${updatedItem.type} (${updatedItem.id})`);
                }
            },

            // Supprimer des articles
            removeItems(ids) {
                this.items = this.items.filter(item => !ids.includes(item.id));
                this.saveItems();
                this.refreshTable();
                this.updateDashboard();
                this.addActivity(`${ids.length} article(s) supprimé(s)`);
            },

            // Basculer le favori
            toggleFavorite(id) {
                const item = this.items.find(item => item.id === id);
                if (item) {
                    item.favorite = !item.favorite;
                    this.saveItems();
                    this.refreshTable();
                    this.addActivity(`Article ${item.favorite ? 'marqué comme favori' : 'retiré des favoris'} : ${item.type} (${item.id})`);
                }
            },

            // Importer des articles depuis un fichier
            async importItems(file) {
                try {
                    const text = await this.readFileAsync(file);
                    let importedItems = [];
                    const fileExtension = file.name.split('.').pop().toLowerCase();
                    if (fileExtension === 'csv') {
                        importedItems = this.parseCSV(text);
                    } else if (fileExtension === 'json') {
                        importedItems = this.parseJSON(text);
                    } else {
                        alert('Format de fichier non pris en charge. Veuillez sélectionner un fichier CSV ou JSON.');
                        return;
                    }
                    this.items = this.items.concat(importedItems);
                    this.saveItems();
                    this.refreshTable();
                    this.updateDashboard();
                    this.addActivity(`Importation de ${importedItems.length} article(s)`);
                    alert('Importation terminée avec succès.');
                } catch (error) {
                    console.error('Erreur lors de l\'importation des articles :', error);
                    alert('Une erreur est survenue lors de l\'importation des articles. Veuillez réessayer.');
                }
            },

            // Lecture de fichier asynchrone
            readFileAsync(file) {
                return new Promise((resolve, reject) => {
                    const reader = new FileReader();
                    reader.onload = () => resolve(reader.result);
                    reader.onerror = () => reject(reader.error);
                    reader.readAsText(file);
                });
            },

            // Parser CSV
            parseCSV(text) {
                const rows = text.split('\n').filter(row => row.trim() !== '');
                const headers = rows[0].split(',').map(header => header.trim().toLowerCase().replace(/ /g, '_'));
                const importedItems = [];
                for (let i = 1; i < rows.length; i++) {
                    const values = rows[i].split(',').map(value => value.trim());
                    if (values.length < headers.length) continue;
                    const item = {};
                    headers.forEach((header, index) => {
                        item[header] = values[index];
                    });
                    item.id = this.generateId();
                    item.last_update = new Date().toLocaleString();
                    // Gestion des relations entre Localisation et Statut
                    if (item.status === 'En Exploitation' && item.location === 'Hors Stock') {
                        item.status = 'En Utilisation';
                    }
                    if (['Pending Disposal', 'Perdu', 'En Utilisation'].includes(item.status)) {
                        item.incident_number = item.incident_number || '';
                        item.problem_description = item.problem_description || '';
                    } else {
                        item.incident_number = '';
                        item.problem_description = '';
                    }
                    item.favorite = (item.favorite === 'true' || item.favorite === 'Oui') ? true : false;
                    importedItems.push(item);
                }
                return importedItems;
            },

            // Parser JSON
            parseJSON(text) {
                try {
                    let parsedItems = JSON.parse(text);
                    parsedItems = parsedItems.map(item => {
                        item.id = this.generateId();
                        item.last_update = new Date().toLocaleString();
                        // Gestion des relations entre Localisation et Statut
                        if (item.status === 'En Exploitation' && item.location === 'Hors Stock') {
                            item.status = 'En Utilisation';
                        }
                        if (['Pending Disposal', 'Perdu', 'En Utilisation'].includes(item.status)) {
                            item.incident_number = item.incident_number || '';
                            item.problem_description = item.problem_description || '';
                        } else {
                            item.incident_number = '';
                            item.problem_description = '';
                        }
                        item.favorite = item.favorite ? true : false;
                        return item;
                    });
                    return parsedItems;
                } catch (error) {
                    console.error('Erreur lors de l\'analyse du JSON :', error);
                    alert('Erreur lors de l\'importation du fichier JSON. Vérifiez le format du fichier.');
                    return [];
                }
            },

            // Exporter les données
            exportData(format) {
                try {
                    if (this.items.length === 0) {
                        alert('Aucun article à exporter.');
                        return;
                    }
                    if (format === 'json') {
                        const dataStr = JSON.stringify(this.items, null, 2);
                        const blob = new Blob([dataStr], { type: 'application/json' });
                        const url = URL.createObjectURL(blob);
                        const a = document.createElement('a');
                        a.href = url;
                        a.download = 'inventaire_sauvegarde.json';
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);
                    } else if (format === 'csv') {
                        const headers = ["id", "type", "tag", "status", "location", "serial_number", "incident_number", "problem_description", "favorite", "last_update", "description"];
                        const csvRows = [headers.join(',')];
                        this.items.forEach(item => {
                            const values = headers.map(header => {
                                let val = item[header] || '';
                                if (typeof val === 'string') {
                                    if (val.includes(',') || val.includes('"')) val = `"${val.replace(/"/g, '""')}"`;
                                }
                                if (header === 'favorite') val = item.favorite ? 'Oui' : 'Non';
                                return val;
                            });
                            csvRows.push(values.join(','));
                        });
                        const csvContent = csvRows.join('\n');
                        const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
                        const url = URL.createObjectURL(blob);
                        const a = document.createElement('a');
                        a.href = url;
                        a.download = 'inventaire_sauvegarde.csv';
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);
                    }
                } catch (error) {
                    console.error('Erreur lors de l\'exportation des données :', error);
                    alert('Une erreur est survenue lors de l\'exportation des données. Veuillez réessayer.');
                }
            },

            // Importer une sauvegarde
            async importBackup(file) {
                if (file) {
                    try {
                        if (confirm('La restauration de la sauvegarde remplacera les données actuelles. Voulez-vous continuer ?')) {
                            await this.importItems(file);
                            Utils.getElement('restoreFileInput').value = '';
                        } else {
                            Utils.getElement('restoreFileInput').value = '';
                        }
                    } catch (error) {
                        console.error('Erreur lors de la restauration de la sauvegarde :', error);
                        alert('Une erreur est survenue lors de la restauration de la sauvegarde.');
                    }
                }
            },

            // Générer un rapport PDF
            async generateReport() {
                try {
                    if (this.items.length === 0) {
                        alert('Aucun article pour générer le rapport.');
                        return;
                    }
                    const { jsPDF } = window.jspdf;
                    const doc = new jsPDF();
                    doc.setFontSize(18);
                    doc.text('Rapport d\'Inventaire', 14, 22);
                    doc.setFontSize(12);
                    doc.text(`Date : ${new Date().toLocaleString()}`, 14, 30);
                    const tableColumn = ["ID", "Type d'Article", "Tag", "Statut", "Localisation", "Numéro de Série", "Numéro d'Incident", "Description de Panne", "Favori", "Dernière Mise à Jour"];
                    const tableRows = [];
                    this.items.forEach(item => {
                        tableRows.push([
                            item.id,
                            item.type,
                            item.tag,
                            item.status,
                            item.location,
                            item.serial_number,
                            item.incident_number || 'N/A',
                            item.problem_description || 'N/A',
                            item.favorite ? 'Oui' : 'Non',
                            item.last_update
                        ]);
                    });
                    doc.autoTable({ head: [tableColumn], body: tableRows, startY: 40, styles: { fontSize: 8 }, headStyles: { fillColor: [100, 100, 100] } });
                    doc.save('rapport_inventaire.pdf');
                    this.addActivity('Rapport généré');
                } catch (error) {
                    console.error('Erreur lors de la génération du rapport :', error);
                    alert('Une erreur est survenue lors de la génération du rapport.');
                }
            },

            // Trier les articles
            sortItems(column) {
                if (this.sortColumn === column) {
                    this.sortDirection = this.sortDirection === 'asc' ? 'desc' : 'asc';
                } else {
                    this.sortColumn = column;
                    this.sortDirection = 'asc';
                }
                this.refreshTable();
            },

            // Changer de page
            changePage(page) {
                const totalPages = this.totalPages();
                if (page < 1 || page > totalPages) return;
                this.currentPage = page;
                this.refreshTable();
            },

            // Mettre à jour la sélection des articles
            updateSelection(checkbox) {
                if (checkbox.checked) this.selectedItems.add(checkbox.value);
                else this.selectedItems.delete(checkbox.value);
                this.updateBulkActions();
            },

            // Sélectionner ou désélectionner tous les articles
            toggleAllItems(checked) {
                const checkboxes = document.querySelectorAll('.item-checkbox');
                checkboxes.forEach(checkbox => {
                    checkbox.checked = checked;
                    if (checked) this.selectedItems.add(checkbox.value);
                    else this.selectedItems.delete(checkbox.value);
                });
                this.updateBulkActions();
            },

            // Exécuter des actions en masse
            executeBulkAction(action) {
                if (this.selectedItems.size === 0) return;
                switch(action) {
                    case 'delete':
                        openConfirmModal(`Voulez-vous supprimer ${this.selectedItems.size} article(s) ?`, () => {
                            this.removeItems(Array.from(this.selectedItems));
                            this.updateDashboard();
                            this.addActivity(`${this.selectedItems.size} article(s) supprimé(s) en masse`);
                            this.selectedItems.clear();
                            this.updateBulkActions();
                        });
                        break;
                    case 'status':
                        const newStatus = prompt('Entrez le nouveau statut (En Exploitation, Disponible, Pending Repair, Pending Disposal, Indisponible Temporairement, Inconnu, En Utilisation):');
                        if (newStatus && ['En Exploitation', 'Disponible', 'Pending Repair', 'Pending Disposal', 'Indisponible Temporairement', 'Inconnu', 'En Utilisation'].includes(newStatus)) {
                            this.items.forEach(item => {
                                if (this.selectedItems.has(item.id)) {
                                    item.status = newStatus;
                                    item.last_update = new Date().toLocaleString();
                                    if (['Pending Disposal', 'Perdu', 'Pending Repair', 'Indisponible Temporairement'].includes(newStatus)) {
                                        item.incident_number = item.incident_number || '';
                                        item.problem_description = item.problem_description || '';
                                    } else {
                                        item.incident_number = '';
                                        item.problem_description = '';
                                    }
                                }
                            });
                            this.saveItems();
                            this.refreshTable();
                            this.updateDashboard();
                            this.addActivity(`Statut mis à jour en ${newStatus} pour ${this.selectedItems.size} article(s)`);
                            this.selectedItems.clear();
                            this.updateBulkActions();
                            alert('Statut mis à jour avec succès.');
                        } else {
                            alert('Statut invalide.');
                        }
                        break;
                    case 'location':
                        const newLocation = prompt('Entrez la nouvelle localisation (IT BAR, En Stock, Hors Stock, Inconnu):');
                        if (newLocation && ['IT BAR', 'En Stock', 'Hors Stock', 'Inconnu'].includes(newLocation)) {
                            this.items.forEach(item => {
                                if (this.selectedItems.has(item.id)) {
                                    item.location = newLocation;
                                    item.last_update = new Date().toLocaleString();
                                    // Ajuster le statut si nécessaire
                                    if (newLocation === 'Hors Stock' && ['Pending Disposal', 'Perdu', 'En Utilisation'].includes(item.status)) {
                                        // Statut valide pour Hors Stock
                                    } else if (newLocation !== 'Hors Stock' && item.status === 'En Utilisation') {
                                        item.status = 'En Exploitation';
                                    }
                                }
                            });
                            this.saveItems();
                            this.refreshTable();
                            this.updateDashboard();
                            this.addActivity(`Localisation mise à jour en ${newLocation} pour ${this.selectedItems.size} article(s)`);
                            this.selectedItems.clear();
                            this.updateBulkActions();
                            alert('Localisation mise à jour avec succès.');
                        } else {
                            alert('Localisation invalide.');
                        }
                        break;
                }
            },

            // Mettre à jour le tableau de bord
            updateDashboard() {
                Utils.getElement('totalItems').textContent = this.items.length;
                Utils.getElement('itemsInUse').textContent = this.items.filter(item => item.status === 'En Utilisation').length;
                Utils.getElement('itemsInStock').textContent = this.items.filter(item => item.status === 'Disponible').length;
                Utils.getElement('itemsUnderMaintenance').textContent = this.items.filter(item => ['Pending Repair', 'En Maintenance'].includes(item.status)).length;
            },

            // Rendre les favoris
            renderFavorites() {
                this.loadItems();
                const favoriteItems = this.items.filter(item => item.favorite);
                const tableBody = Utils.getElement('favoritesTableBody');
                tableBody.innerHTML = '';
                if (favoriteItems.length === 0) {
                    tableBody.innerHTML = `<tr><td colspan="10" class="p-3 text-center">Aucun article favori trouvé.</td></tr>`;
                    return;
                }
                favoriteItems.forEach(item => {
                    const row = this.createTableRow(item, true);
                    tableBody.appendChild(row);
                });
            },

            // Rendre les analyses
            renderAnalytics() {
                this.loadItems();
                const types = {}, statuses = {}, locations = {};
                this.items.forEach(item => {
                    types[item.type] = (types[item.type] || 0) + 1;
                    statuses[item.status] = (statuses[item.status] || 0) + 1;
                    locations[item.location] = (locations[item.location] || 0) + 1;
                });
                const typeLabels = Object.keys(types), typeData = Object.values(types);
                const statusLabels = Object.keys(statuses), statusData = Object.values(statuses);
                const locationLabels = Object.keys(locations), locationData = Object.values(locations);
                const ctxType = Utils.getElement('typeChart').getContext('2d');
                if (this.typeChartInstance) this.typeChartInstance.destroy();
                this.typeChartInstance = new Chart(ctxType, {
                    type: 'pie',
                    data: { labels: typeLabels, datasets: [{ data: typeData, backgroundColor: ['rgba(54,162,235,0.7)','rgba(255,99,132,0.7)','rgba(255,206,86,0.7)','rgba(75,192,192,0.7)','rgba(153,102,255,0.7)','rgba(255,159,64,0.7)'], borderColor: ['rgba(54,162,235,1)','rgba(255,99,132,1)','rgba(255,206,86,1)','rgba(75,192,192,1)','rgba(153,102,255,1)','rgba(255,159,64,1)'], borderWidth: 1 }] },
                    options: { responsive: true, plugins: { legend: { position: 'bottom' }, title: { display: false } } }
                });
                const ctxStatus = Utils.getElement('statusChart').getContext('2d');
                if (this.statusChartInstance) this.statusChartInstance.destroy();
                this.statusChartInstance = new Chart(ctxStatus, {
                    type: 'bar',
                    data: { labels: statusLabels, datasets: [{ label: 'Répartition par Statut', data: statusData, backgroundColor: 'rgba(255,99,132,0.7)', borderColor: 'rgba(255,99,132,1)', borderWidth: 1 }] },
                    options: { responsive: true, plugins: { legend: { display: false }, title: { display: false } }, scales: { y: { beginAtZero: true, ticks: { precision:0 } } } }
                });
                const ctxLocation = Utils.getElement('locationChart').getContext('2d');
                if (this.locationChartInstance) this.locationChartInstance.destroy();
                this.locationChartInstance = new Chart(ctxLocation, {
                    type: 'bar',
                    data: { labels: locationLabels, datasets: [{ label: 'Répartition par Localisation', data: locationData, backgroundColor: 'rgba(75,192,192,0.7)', borderColor: 'rgba(75,192,192,1)', borderWidth: 1 }] },
                    options: { responsive: true, plugins: { legend: { display: false }, title: { display: false } }, scales: { y: { beginAtZero: true, ticks: { precision:0 } } } }
                });
            },

            // Créer une ligne de tableau (Composant Réutilisable)
            createTableRow(item, isFavoriteSection = false) {
                const row = document.createElement('tr');
                row.classList.add('hover:bg-gray-700', 'transition', 'duration-200');
                row.innerHTML = `
                    <td class="p-3"><input type="checkbox" class="form-checkbox item-checkbox accessible-focus" value="${item.id}" aria-label="Sélectionner l'Article ${item.id}" data-tippy-content="Sélectionner l'Article"></td>
                    <td class="p-3">${item.id}</td>
                    <td class="p-3">${item.type}</td>
                    <td class="p-3">${item.tag}</td>
                    <td class="p-3">${item.status}</td>
                    <td class="p-3">${item.location}</td>
                    <td class="p-3">${item.serial_number}</td>
                    <td class="p-3">${item.incident_number || 'N/A'}</td>
                    <td class="p-3">${item.problem_description || 'N/A'}</td>
                    <td class="p-3">${item.last_update}</td>
                    <td class="p-3">${item.favorite ? 'Oui' : 'Non'}</td>
                    <td class="p-3 flex space-x-2">
                        <button onclick="inventoryManager.toggleFavorite('${item.id}')" class="item__favorite-button text-yellow-500 hover:text-yellow-300 accessible-focus" aria-label="${item.favorite ? 'Retirer des Favoris' : 'Marquer comme Favori'}" data-tippy-content="${item.favorite ? 'Retirer des Favoris' : 'Marquer comme Favori'}">
                            <i class="${item.favorite ? 'fas fa-star' : 'far fa-star'}" aria-hidden="true" role="img" aria-label="${item.favorite ? 'Favori' : 'Non Favori'}"></i>
                        </button>
                        <button onclick="inventoryManager.editItem('${item.id}')" class="item__edit-button bg-blue-500 hover:bg-blue-600 text-white px-2 py-1 rounded-md transition duration-300 accessible-focus" aria-label="Éditer l'Article" data-tippy-content="Éditer l'Article">
                            <i class="fas fa-edit" aria-hidden="true" role="img" aria-label="Éditer"></i>
                        </button>
                        <button onclick="inventoryManager.deleteItem('${item.id}')" class="item__delete-button bg-red-500 hover:bg-red-600 text-white px-2 py-1 rounded-md transition duration-300 accessible-focus" aria-label="Supprimer l'Article" data-tippy-content="Supprimer l'Article">
                            <i class="fas fa-trash" aria-hidden="true" role="img" aria-label="Supprimer"></i>
                        </button>
                    </td>
                `;
                return row;
            },

            // Mettre à jour le tableau avec filtres, recherche et tri
            refreshTable() {
                this.loadItems();
                let filteredItems = [...this.items];

                // Appliquer la recherche
                const searchQuery = Utils.getElementValue('searchInput').trim().toLowerCase();
                if (searchQuery) {
                    filteredItems = filteredItems.filter(item =>
                        item.id.toLowerCase().includes(searchQuery) ||
                        item.type.toLowerCase().includes(searchQuery) ||
                        item.tag.toLowerCase().includes(searchQuery)
                    );
                }

                // Appliquer les filtres
                const filterStatus = Utils.getElementValue('filterStatus');
                const filterLocation = Utils.getElementValue('filterLocation');
                const filterCondition = Utils.getElementValue('filterCondition');
                if (filterStatus) filteredItems = filteredItems.filter(item => item.status === filterStatus);
                if (filterLocation) filteredItems = filteredItems.filter(item => item.location === filterLocation);
                if (filterCondition) filteredItems = filteredItems.filter(item => item.condition === filterCondition);

                // Trier les articles
                filteredItems.sort((a, b) => {
                    let aVal = a[this.sortColumn];
                    let bVal = b[this.sortColumn];

                    if (this.sortColumn === 'favorite') {
                        aVal = aVal ? 1 : 0;
                        bVal = bVal ? 1 : 0;
                    } else {
                        aVal = aVal.toString().toLowerCase();
                        bVal = bVal.toString().toLowerCase();
                    }

                    if (typeof aVal === 'string' && typeof bVal === 'string') {
                        return this.sortDirection === 'asc' ? aVal.localeCompare(bVal) : bVal.localeCompare(aVal);
                    }

                    return this.sortDirection === 'asc' ? aVal - bVal : bVal - aVal;
                });

                // Pagination
                const totalItems = filteredItems.length;
                const totalPages = this.totalPages();
                if (this.currentPage > totalPages) this.currentPage = totalPages || 1;
                const startIndex = (this.currentPage - 1) * this.itemsPerPage;
                const endIndex = startIndex + this.itemsPerPage;
                const paginatedItems = filteredItems.slice(startIndex, endIndex);

                // Rendre le tableau
                const tableBody = Utils.getElement('inventoryTableBody');
                tableBody.innerHTML = '';
                if (paginatedItems.length === 0) {
                    tableBody.innerHTML = `<tr><td colspan="11" class="p-3 text-center">Aucun article trouvé.</td></tr>`;
                    return;
                }
                paginatedItems.forEach(item => {
                    const row = this.createTableRow(item);
                    tableBody.appendChild(row);
                });

                // Mettre à jour les informations de pagination
                Utils.getElement('paginationInfo').textContent = `Affichage ${startIndex + 1}-${Math.min(endIndex, totalItems)} de ${totalItems} articles`;
                Utils.getElement('currentPage').textContent = this.currentPage;

                // Mettre à jour les actions en masse
                this.updateBulkActions();

                // Mettre à jour les graphiques statistiques
                if (document.getElementById('analytics').classList.contains('hidden') === false) {
                    this.renderAnalytics();
                }
            },

            // Calculer le total des pages
            totalPages() {
                return Math.ceil(this.items.length / this.itemsPerPage);
            },

            // Mettre à jour les actions en masse
            updateBulkActions() {
                const bulkActions = Utils.getElement('bulkActions');
                if (this.selectedItems.size > 0) Utils.showElement('bulkActions');
                else Utils.hideElement('bulkActions');
            },

            // Ajouter une activité récente
            addActivity(message) {
                const recentActivities = Utils.getElement('recentActivities');
                const activity = document.createElement('li');
                activity.classList.add('flex', 'items-center');
                activity.innerHTML = `
                    <i class="fas fa-history text-gray-400 text-xl mr-4" aria-hidden="true" role="img" aria-label="Activité"></i>
                    <div>
                        <p class="font-semibold">${message}</p>
                        <p class="text-sm text-gray-400">${new Date().toLocaleString()}</p>
                    </div>
                `;
                recentActivities.prepend(activity);
                if (recentActivities.children.length > 5) recentActivities.removeChild(recentActivities.lastChild);
            },

            // Générer un ID unique
            generateId() {
                return 'ARTICLE-' + Date.now() + '-' + Math.floor(Math.random() * 1000);
            },

            // Éditer un article
            editItem(id) {
                const item = this.items.find(item => item.id === id);
                if (!item) return;
                openModal('itemModal');
                Utils.getElement('itemModalTitle').textContent = 'Éditer l\'Article';
                Utils.getElement('itemForm').dataset.editing = id;
                Utils.getElement('itemType').value = item.type;
                Utils.getElement('itemTag').value = item.tag;
                Utils.getElement('itemStatus').value = item.status;
                Utils.getElement('itemLocation').value = item.location;
                Utils.getElement('itemSerialNumber').value = item.serial_number;
                Utils.getElement('itemDescription').value = item.description;
                Utils.getElement('itemFavorite').checked = item.favorite;
                this.toggleMaintenanceFields();
                if (['Pending Disposal', 'Perdu', 'Pending Repair', 'Indisponible Temporairement', 'En Utilisation'].includes(item.status)) {
                    Utils.getElement('incidentNumber').value = item.incident_number || '';
                    Utils.getElement('problemDescription').value = item.problem_description || '';
                }
            },

            // Supprimer un article
            deleteItem(id) {
                openConfirmModal('Voulez-vous vraiment supprimer cet article ?', () => {
                    this.removeItems([id]);
                    this.updateDashboard();
                    this.addActivity(`Article supprimé : ID ${id}`);
                });
            },

            // Gérer le chargement des sections
            handleSectionLoad(sectionId) {
                switch(sectionId) {
                    case 'dashboard':
                        this.updateDashboard();
                        this.renderAnalytics();
                        break;
                    case 'inventory':
                        this.refreshTable();
                        break;
                    case 'favorites':
                        this.renderFavorites();
                        break;
                    case 'analytics':
                        this.renderAnalytics();
                        break;
                }
            },

            // Toggle Maintenance Fields (Fonction Simplifiée)
            toggleMaintenanceFields() {
                const status = Utils.getElementValue('itemStatus');
                const location = Utils.getElementValue('itemLocation');
                const maintenanceFields = Utils.getElement('maintenanceFields');

                if (status === 'En Exploitation' && location === 'Hors Stock') {
                    Utils.showElement('maintenanceFields');
                    Utils.setRequired('incidentNumber', false);
                    Utils.setRequired('problemDescription', false);
                } else if (['Pending Disposal', 'Perdu', 'Pending Repair', 'Indisponible Temporairement'].includes(status)) {
                    Utils.showElement('maintenanceFields');
                    Utils.setRequired('incidentNumber', true);
                    Utils.setRequired('problemDescription', true);
                } else {
                    Utils.hideElement('maintenanceFields');
                    Utils.setRequired('incidentNumber', false);
                    Utils.setRequired('problemDescription', false);
                    Utils.clearInput('incidentNumber');
                    Utils.clearInput('problemDescription');
                    Utils.hideElement('incidentNumberError');
                    Utils.hideElement('problemDescriptionError');
                }
            }
        };

        // Initialiser l'Inventaire
        inventoryManager.loadItems();
        inventoryManager.updateDashboard();

        // Fonction pour afficher la section souhaitée
        function showSection(sectionId) {
            const sections = document.querySelectorAll('.section');
            sections.forEach(section => {
                section.classList.toggle('hidden', section.id !== sectionId);
            });
            const menuItems = document.querySelectorAll('nav a');
            menuItems.forEach(item => {
                if (item.id === sectionId + 'Menu') {
                    item.classList.add('bg-opacity-80');
                    item.setAttribute('aria-current', 'page');
                } else {
                    item.classList.remove('bg-opacity-80');
                    item.removeAttribute('aria-current');
                }
            });
            inventoryManager.handleSectionLoad(sectionId);
        }

        // Fonction pour ouvrir un modal
        function openModal(modalId) {
            Utils.showElement(modalId);
            Utils.getElement(modalId).setAttribute('aria-hidden', 'false');
            // Focus pour l'accessibilité
            Utils.getElement(modalId).querySelector('.modal-content').focus();
        }

        // Fonction pour fermer un modal
        function closeModal(modalId) {
            Utils.hideElement(modalId);
            Utils.getElement(modalId).setAttribute('aria-hidden', 'true');
            // Réinitialiser les erreurs et les champs
            const errorMessages = Utils.getElement(modalId).querySelectorAll('.error-message');
            errorMessages.forEach(msg => msg.classList.add('hidden'));
            const inputs = Utils.getElement(modalId).querySelectorAll('input, textarea, select');
            inputs.forEach(input => {
                if (input.type !== 'checkbox' && input.type !== 'radio') input.value = '';
                if (input.type === 'checkbox' || input.type === 'radio') input.checked = false;
            });
            if (modalId === 'itemModal') inventoryManager.toggleMaintenanceFields();
        }

        // Fonction pour fermer les modaux en cliquant à l'extérieur
        window.addEventListener('click', function(event) {
            const modals = document.querySelectorAll('.modal');
            modals.forEach(modal => {
                if (event.target === modal) {
                    closeModal(modal.id);
                }
            });
        });

        // Fonction de debounce pour optimiser la recherche
        const debouncedRefreshTable = Utils.debounce(() => inventoryManager.refreshTable(), 300);

        // Fonction de validation de l'e-mail
        function validateEmail(email) {
            return Utils.validateEmail(email);
        }

        // Gestionnaire des événements de navigation
        document.addEventListener('DOMContentLoaded', function() {
            showSection('dashboard');
            inventoryManager.refreshTable();
        });

        document.querySelectorAll('nav a').forEach(menu => {
            menu.addEventListener('click', (e) => {
                e.preventDefault();
                const sectionId = menu.id.replace('Menu', '');
                showSection(sectionId);
            });
        });

        // Gestion des événements de recherche et filtres
        Utils.getElement('searchInput').addEventListener('input', debouncedRefreshTable);
        Utils.getElement('filterStatus').addEventListener('change', () => inventoryManager.refreshTable());
        Utils.getElement('filterLocation').addEventListener('change', () => inventoryManager.refreshTable());
        Utils.getElement('filterCondition').addEventListener('change', () => inventoryManager.refreshTable());

        // Gestion des événements de pagination
        Utils.getElement('prevPage').addEventListener('click', () => inventoryManager.changePage(inventoryManager.currentPage - 1));
        Utils.getElement('nextPage').addEventListener('click', () => inventoryManager.changePage(inventoryManager.currentPage + 1));

        // Gestion de la sélection de tous les articles
        Utils.getElement('selectAll').addEventListener('change', (e) => inventoryManager.toggleAllItems(e.target.checked));

        // Gestion des actions en masse
        Utils.getElement('deleteSelected').addEventListener('click', () => inventoryManager.executeBulkAction('delete'));
        Utils.getElement('changeStatusSelected').addEventListener('click', () => inventoryManager.executeBulkAction('status'));
        Utils.getElement('changeLocationSelected').addEventListener('click', () => inventoryManager.executeBulkAction('location'));

        // Gestion des événements d'importation et exportation
        Utils.getElement('importButton').addEventListener('click', () => Utils.getElement('importFileInput').click());
        Utils.getElement('importFileInput').addEventListener('change', (e) => inventoryManager.importItems(e.target.files[0]));
        Utils.getElement('backupJson').addEventListener('click', () => inventoryManager.exportData('json'));
        Utils.getElement('backupCsv').addEventListener('click', () => inventoryManager.exportData('csv'));
        Utils.getElement('restoreBackup').addEventListener('click', () => Utils.getElement('restoreFileInput').click());
        Utils.getElement('restoreFileInput').addEventListener('change', (e) => inventoryManager.importBackup(e.target.files[0]));

        // Gestion de l'événement de génération de rapport
        Utils.getElement('generateReportButton').addEventListener('click', () => inventoryManager.generateReport());

        // Gestion des événements de connexion et inscription
        Utils.getElement('loginButton').addEventListener('click', () => openModal('loginModal'));
        Utils.getElement('signupButton').addEventListener('click', () => openModal('signupModal'));
        Utils.getElement('profileButton').addEventListener('click', () => showSection('profile'));

        // Gestion de la déconnexion
        Utils.getElement('logoutMenu').addEventListener('click', () => {
            openConfirmModal('Voulez-vous vraiment quitter le système ?', () => {
                localStorage.removeItem('loggedInUser');
                alert('Vous avez été déconnecté.');
                showSection('dashboard');
                inventoryManager.updateDashboard();
            });
        });
        Utils.getElement('confirmLogout').addEventListener('click', () => {
            openConfirmModal('Voulez-vous vraiment quitter le système ?', () => {
                localStorage.removeItem('loggedInUser');
                alert('Vous avez été déconnecté.');
                showSection('dashboard');
                inventoryManager.updateDashboard();
            });
        });

        // Gestion du formulaire de connexion
        Utils.getElement('loginForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            const email = Utils.getElementValue('loginEmail').trim();
            const password = Utils.getElementValue('loginPassword').trim();
            // Réinitialiser les messages d'erreur
            Utils.hideElement('loginEmailError');
            Utils.hideElement('loginPasswordError');
            Utils.hideElement('loginError');
            let hasError = false;
            if (!validateEmail(email)) {
                Utils.getElement('loginEmailError').classList.remove('hidden');
                hasError = true;
            }
            if (password === '') {
                Utils.getElement('loginPasswordError').classList.remove('hidden');
                hasError = true;
            }
            if (hasError) return;
            try {
                const users = JSON.parse(localStorage.getItem('users')) || [];
                const hashedPassword = await Utils.hashPassword(password);
                const user = users.find(u => u.email === email && u.password === hashedPassword);
                if (user) {
                    localStorage.setItem('loggedInUser', JSON.stringify(user));
                    alert('Connexion réussie.');
                    closeModal('loginModal');
                    showSection('dashboard');
                    inventoryManager.updateDashboard();
                } else {
                    Utils.hideElement('loginEmailError');
                    Utils.hideElement('loginPasswordError');
                    Utils.getElement('loginError').classList.remove('hidden');
                }
            } catch (error) {
                console.error('Erreur lors de la connexion :', error);
                alert('Une erreur est survenue lors de la connexion. Veuillez réessayer.');
            }
        });

        // Gestion du formulaire d'inscription
        Utils.getElement('signupForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            const name = Utils.getElementValue('signupName').trim();
            const email = Utils.getElementValue('signupEmail').trim();
            const password = Utils.getElementValue('signupPassword').trim();
            // Réinitialiser les messages d'erreur
            Utils.hideElement('signupNameError');
            Utils.hideElement('signupEmailError');
            Utils.hideElement('signupPasswordError');
            Utils.hideElement('signupError');
            let hasError = false;
            if (name === '') {
                Utils.getElement('signupNameError').classList.remove('hidden');
                hasError = true;
            }
            if (!validateEmail(email)) {
                Utils.getElement('signupEmailError').classList.remove('hidden');
                hasError = true;
            }
            if (password.length < 6) {
                Utils.getElement('signupPasswordError').classList.remove('hidden');
                hasError = true;
            }
            if (hasError) return;
            try {
                const users = JSON.parse(localStorage.getItem('users')) || [];
                if (users.find(u => u.email === email)) {
                    Utils.getElement('signupError').textContent = 'E-mail déjà enregistré.';
                    Utils.getElement('signupError').classList.remove('hidden');
                    return;
                }
                const hashedPassword = await Utils.hashPassword(password);
                users.push({ name, email, password: hashedPassword });
                localStorage.setItem('users', JSON.stringify(users));
                alert('Inscription réussie.');
                closeModal('signupModal');
            } catch (error) {
                console.error('Erreur lors de l\'inscription :', error);
                Utils.getElement('signupError').textContent = 'Erreur lors de l\'inscription. Veuillez réessayer.';
                Utils.getElement('signupError').classList.remove('hidden');
            }
        });

        // Gestion du formulaire de mise à jour du profil
        Utils.getElement('profileForm').addEventListener('submit', function(e) {
            e.preventDefault();
        });

        async function updateProfile() {
            const name = Utils.getElementValue('profileName').trim();
            const email = Utils.getElementValue('profileEmail').trim();
            const password = Utils.getElementValue('profilePassword').trim();
            // Réinitialiser les messages d'erreur
            Utils.hideElement('profileNameError');
            Utils.hideElement('profileEmailError');
            Utils.hideElement('profilePasswordError');
            let hasError = false;
            if (name === '') { 
                Utils.getElement('profileNameError').classList.remove('hidden'); 
                hasError = true; 
            }
            if (!validateEmail(email)) { 
                Utils.getElement('profileEmailError').classList.remove('hidden'); 
                hasError = true; 
            }
            if (password.length > 0 && password.length < 6) { 
                Utils.getElement('profilePasswordError').classList.remove('hidden'); 
                hasError = true; 
            }
            if (hasError) return;
            try {
                const users = JSON.parse(localStorage.getItem('users')) || [];
                const loggedInUser = JSON.parse(localStorage.getItem('loggedInUser'));
                if (loggedInUser) {
                    const userIndex = users.findIndex(u => u.email === loggedInUser.email);
                    if (userIndex !== -1) {
                        users[userIndex].name = name;
                        users[userIndex].email = email;
                        if (password.length >= 6) users[userIndex].password = await Utils.hashPassword(password);
                        localStorage.setItem('users', JSON.stringify(users));
                        const updatedUser = { ...users[userIndex] };
                        localStorage.setItem('loggedInUser', JSON.stringify(updatedUser));
                        alert('Profil mis à jour avec succès.');
                        inventoryManager.addActivity(`Profil mis à jour : ${updatedUser.name} (${updatedUser.email})`);
                    }
                }
            } catch (error) {
                console.error('Erreur lors de la mise à jour du profil :', error);
                alert('Une erreur est survenue lors de la mise à jour du profil. Veuillez réessayer.');
            }
        }

        // Fonction pour charger le profil de l'utilisateur
        function loadProfile() {
            const user = JSON.parse(localStorage.getItem('loggedInUser'));
            if (user) {
                Utils.getElement('profileName').value = user.name;
                Utils.getElement('profileEmail').value = user.email;
                Utils.getElement('profilePassword').value = '';
            } else {
                alert('Vous devez vous connecter pour accéder au profil.');
                showSection('dashboard');
            }
        }

        // Fonction pour sauvegarder les paramètres
        async function saveSettings() {
            const theme = document.querySelector('input[name="theme"]:checked')?.value || 'light';
            const notifications = Utils.getElement('notifications').checked;
            const additionalPreferences = Utils.getElementValue('additionalPreferences').trim();
            const settings = { theme, notifications, additionalPreferences };
            try {
                localStorage.setItem('userSettings', JSON.stringify(settings));
                toggleTheme(theme);
                alert('Paramètres sauvegardés avec succès.');
            } catch (error) {
                console.error('Erreur lors de la sauvegarde des paramètres :', error);
                alert('Une erreur est survenue lors de la sauvegarde des paramètres.');
            }
        }

        // Fonction pour réinitialiser les paramètres
        function resetSettings() {
            if (confirm('Voulez-vous restaurer les paramètres par défaut ?')) {
                try {
                    localStorage.removeItem('userSettings');
                    Utils.getElement('settingsForm').reset();
                    toggleTheme('light');
                    alert('Paramètres restaurés par défaut.');
                } catch (error) {
                    console.error('Erreur lors de la réinitialisation des paramètres :', error);
                    alert('Une erreur est survenue lors de la réinitialisation des paramètres.');
                }
            }
        }

        // Fonction pour charger les paramètres
        function loadSettings() {
            try {
                const settings = JSON.parse(localStorage.getItem('userSettings'));
                if (settings) {
                    if (settings.theme) {
                        document.querySelector(`input[name="theme"][value="${settings.theme}"]`).checked = true;
                        toggleTheme(settings.theme);
                    }
                    if (typeof settings.notifications !== 'undefined') {
                        Utils.getElement('notifications').checked = settings.notifications;
                    }
                    if (settings.additionalPreferences) {
                        Utils.getElement('additionalPreferences').value = settings.additionalPreferences;
                    }
                } else {
                    toggleTheme('light');
                }
            } catch (error) {
                console.error('Erreur lors du chargement des paramètres :', error);
                toggleTheme('light');
            }
        }

        // Fonction pour basculer le thème
        function toggleTheme(theme) {
            if (theme === 'dark') {
                document.documentElement.classList.add('theme-dark');
                document.documentElement.classList.remove('theme-light');
            } else {
                document.documentElement.classList.remove('theme-dark');
                document.documentElement.classList.add('theme-light');
            }
        }

        // Initialiser les paramètres lors du chargement de la page
        window.addEventListener('DOMContentLoaded', loadSettings);

        // Fonction pour ouvrir le modal de confirmation avec un message personnalisé
        function openConfirmModal(message, actionCallback) {
            Utils.getElement('confirmMessage').textContent = message;
            const confirmButton = Utils.getElement('confirmActionButton');
            confirmButton.onclick = () => {
                actionCallback();
                closeModal('confirmModal');
            };
            openModal('confirmModal');
        }

        // Attribution de l'événement de soumission du formulaire d'article
        Utils.getElement('itemForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            const id = this.dataset.editing;
            const type = Utils.getElementValue('itemType').trim();
            const tag = Utils.getElementValue('itemTag').trim();
            const status = Utils.getElementValue('itemStatus');
            const location = Utils.getElementValue('itemLocation');
            const serialNumber = Utils.getElementValue('itemSerialNumber').trim();
            const description = Utils.getElementValue('itemDescription').trim();
            const incidentNumber = Utils.getElementValue('incidentNumber') || '';
            const problemDescription = Utils.getElementValue('problemDescription') || '';
            const favorite = Utils.getElement('itemFavorite').checked;
            let hasError = false;
            // Valider les champs
            if (type === '') { Utils.getElement('itemTypeError').classList.remove('hidden'); hasError = true; }
            if (tag === '') { Utils.getElement('itemTagError').classList.remove('hidden'); hasError = true; }
            if (status === '') { Utils.getElement('itemStatusError').classList.remove('hidden'); hasError = true; }
            if (location === '') { Utils.getElement('itemLocationError').classList.remove('hidden'); hasError = true; }
            if (serialNumber === '') { Utils.getElement('itemSerialNumberError').classList.remove('hidden'); hasError = true; }
            if (['Pending Disposal', 'Perdu', 'Pending Repair', 'Indisponible Temporairement', 'En Utilisation'].includes(status)) {
                if (incidentNumber === '') { Utils.getElement('incidentNumberError').classList.remove('hidden'); hasError = true; }
                if (problemDescription === '') { Utils.getElement('problemDescriptionError').classList.remove('hidden'); hasError = true; }
            }
            if (hasError) return;
            try {
                if (id) {
                    // Mettre à jour l'article existant
                    const updatedItem = {
                        id,
                        type,
                        tag,
                        status,
                        location,
                        serial_number: serialNumber,
                        incident_number: (['Pending Disposal', 'Perdu', 'Pending Repair', 'Indisponible Temporairement', 'En Utilisation'].includes(status)) ? incidentNumber : '',
                        problem_description: (['Pending Disposal', 'Perdu', 'Pending Repair', 'Indisponible Temporairement', 'En Utilisation'].includes(status)) ? problemDescription : '',
                        description,
                        favorite,
                        last_update: new Date().toLocaleString()
                    };
                    await inventoryManager.updateItem(updatedItem);
                    alert('Article mis à jour avec succès.');
                } else {
                    // Ajouter un nouvel article
                    const newItem = {
                        id: inventoryManager.generateId(),
                        type,
                        tag,
                        status,
                        location,
                        serial_number: serialNumber,
                        incident_number: (['Pending Disposal', 'Perdu', 'Pending Repair', 'Indisponible Temporairement', 'En Utilisation'].includes(status)) ? incidentNumber : '',
                        problem_description: (['Pending Disposal', 'Perdu', 'Pending Repair', 'Indisponible Temporairement', 'En Utilisation'].includes(status)) ? problemDescription : '',
                        description,
                        favorite,
                        last_update: new Date().toLocaleString()
                    };
                    inventoryManager.addItem(newItem);
                    alert('Article ajouté avec succès.');
                }
                this.dataset.editing = '';
                closeModal('itemModal');
            } catch (error) {
                console.error('Erreur lors de l\'enregistrement de l\'article :', error);
                alert('Une erreur est survenue lors de l\'enregistrement de l\'article. Veuillez réessayer.');
            }
        });

        // Fonction pour ajouter un nouvel article
        function openAddItemModal() {
            Utils.getElement('itemModalTitle').textContent = 'Ajouter un Article';
            Utils.getElement('itemForm').dataset.editing = '';
            Utils.getElement('itemForm').reset();
            inventoryManager.toggleMaintenanceFields();
            openModal('itemModal');
        }

        Utils.getElement('addItemButton').addEventListener('click', openAddItemModal);

        // Gestion des événements de mise à jour des favoris
        Utils.getElement('refreshFavorites').addEventListener('click', () => inventoryManager.renderFavorites());

        // Initialiser les tableaux et les graphiques lors du chargement de la page
        document.addEventListener('DOMContentLoaded', function() {
            showSection('dashboard');
            inventoryManager.refreshTable();
        });

        // Gestion des Graphiques et Statistiques
        // Déjà implémentés dans renderAnalytics

        // Fonction pour ajuster la taille de la police pour l'accessibilité
        function adjustFontSize(increment) {
            const body = document.body;
            const currentSize = parseFloat(window.getComputedStyle(body).fontSize);
            body.style.fontSize = (currentSize + increment) + 'px';
        }

        // Ajouter des contrôles pour ajuster la taille de la police
        const fontControls = document.createElement('div');
        fontControls.classList.add('fixed', 'bottom-4', 'right-4', 'flex', 'space-x-2');
        fontControls.innerHTML = `
            <button onclick="adjustFontSize(2)" class="px-3 py-2 bg-gray-700 text-white rounded-md hover:bg-gray-600 transition duration-300 accessible-focus" aria-label="Augmenter la Taille de la Police" data-tippy-content="Augmenter la Taille de la Police">
                <i class="fas fa-plus"></i>
            </button>
            <button onclick="adjustFontSize(-2)" class="px-3 py-2 bg-gray-700 text-white rounded-md hover:bg-gray-600 transition duration-300 accessible-focus" aria-label="Diminuer la Taille de la Police" data-tippy-content="Diminuer la Taille de la Police">
                <i class="fas fa-minus"></i>
            </button>
        `;
        document.body.appendChild(fontControls);
    </script>
</body>
</html>
/melhore