Ciao, da questo momento voglio che ti comporti come un esperto sviluppatore frontend con competenze avanzate in HTML, CSS, JavaScript e conoscenza delle integrazioni con codice Python (es. Jinja2 o Flask).
Contesto:
Sto lavorando su un file HTML che:
Contiene una sidebar laterale per la navigazione tra più sezioni.
Mostra i dati al centro della pagina, come tabelle, grafici o contenuti generati dinamicamente.
È integrato con un backend Python: le tabelle sono popolate tramite codice Python, e ci sono riferimenti diretti a variabili e strutture Python (come {{ variabile }} o {% for item in lista %}).
Include funzionalità di esportazione dati in Excel e formattazioni numeriche specifiche, che non devono essere modificate.
Obiettivo:
Migliorare graficamente e strutturalmente l’HTML, rendendolo moderno, ordinato e responsivo.
Suddividere i contenuti in più sezioni/pagine, collegate tramite la sidebar laterale.
Quando clicco su una voce della sidebar, devono essere mostrati solo i contenuti della sezione corrispondente (le altre sezioni devono scomparire).
La navigazione deve avvenire senza ricaricare la pagina: utilizza JavaScript per mostrare/nascondere i contenuti in modo dinamico.
Tutto il codice deve essere completo e funzionante, includendo:
HTML strutturato correttamente
CSS per lo stile (può essere interno o esterno, ma incluso)
JavaScript per la logica di navigazione
Requisiti fondamentali:
Non modificare in alcun modo i riferimenti al codice Python già presenti nel file (es. variabili, cicli, template).
Non alterare la logica di generazione delle tabelle e dei dati provenienti dal backend Python.
Mantieni inalterata la formattazione numerica e la funzionalità di esportazione in Excel.
Il codice deve essere pulito, leggibile e conforme alle buone pratiche di sviluppo frontend.
Genera il codice completo pronto all’uso.

<!DOCTYPE html>
<html lang="it">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title> Agente - {{ nome_agente }}</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/xlsx@0.18.5/dist/xlsx.full.min.js"></script>
    <style>
        :root {
            --sidebar-width: 220px;
            --sidebar-collapsed-width: 60px;
            --transition-speed: 0.3s;
            --primary-color: #020068;
            --secondary-color: #00d2ff;
            --light-bg: #f5f7fb;
            --dark-text: #212529;
            --header-height: 80px;
        }
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background-color: var(--light-bg);
            color: var(--dark-text);
            overflow-x: hidden;
        }
        .wrapper {
            display: flex;
            min-height: 100vh;
            padding-top: var(--header-height);
            transition: padding-left var(--transition-speed);
        }
        #sidebar {
            width: var(--sidebar-width);
            background: linear-gradient(135deg, var(--primary-color), var(--secondary-color));
            color: white;
            transition: all var(--transition-speed) ease;
            position: fixed;
            height: calc(100vh - var(--header-height));
            top: var(--header-height);
            left: 0;
            z-index: 990;
            box-shadow: 3px 0 10px rgba(0, 0, 0, 0.1);
            overflow-y: auto;
            transform: translateX(0);
        }
        .sidebar-collapsed #sidebar { width: var(--sidebar-collapsed-width);}
        .sidebar-header {
            padding: 15px;
            background: rgba(0, 0, 0, 0.1);
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        .logo-container {
            width: 80px;
            height: 80px;
            border-radius: 50%;
            background: white;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 10px;
            overflow: hidden;
            border: 3px solid white;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        .logo-container img { max-width: 100%; max-height: 100%;}
        .sidebar-content { padding: 15px 0;}
        .sidebar-menu { list-style: none; padding: 0; margin: 0;}
        .sidebar-menu li { padding: 0;}
        .sidebar-menu a {
            color: rgba(255, 255, 255, 0.9);
            text-decoration: none;
            display: flex;
            align-items: center;
            padding: 10px 15px;
            transition: all 0.2s;
            font-size: 0.95rem;
        }
        .sidebar-menu a:hover, .sidebar-menu a.active {
            background: rgba(255, 255, 255, 0.1);
            color: white;
            border-left: 4px solid white;
        }
        .sidebar-menu i {
            margin-right: 12px;
            font-size: 1.1rem;
            min-width: 22px;
            text-align: center;
        }
        .sidebar-collapsed .menu-text { display: none;}
        .sidebar-collapsed .sidebar-header h3 { display: none;}
        .sidebar-collapsed .sidebar-menu a { justify-content: center;}
        .sidebar-collapsed .sidebar-menu i { margin-right: 0;}
        .sidebar-collapsed .logo-container { width: 40px; height: 40px; margin-bottom: 5px;}
        #content {
            flex: 1;
            padding: 15px;
            padding-top: 0;
            transition: margin-left var(--transition-speed) ease;
            margin-left: var(--sidebar-width);
        }
        .sidebar-collapsed #content { margin-left: var(--sidebar-collapsed-width);}
        .main-header {
            position: fixed;
            top: 0; left: 0; right: 0;
            height: var(--header-height);
            background: white;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
            z-index: 1000;
            display: flex;
            align-items: center;
            padding: 0 20px;
            justify-content: space-between;
            transition: left var(--transition-speed);
        }
        .header-left { display: flex; align-items: center; gap: 15px;}
        .toggle-btn {
            background: var(--primary-color);
            color: white;
            border: none;
            border-radius: 5px;
            padding: 7px 12px;
            cursor: pointer;
            transition: background 0.3s;
            display: flex;
            align-items: center;
            font-size: 0.9rem;
        }
        .toggle-btn:hover { background: #2a5ba4;}
        .page-title h1 {
            font-weight: 600;
            color: var(--primary-color);
            margin: 0;
            font-size: 1.5rem;
            transition: all var(--transition-speed);
        }
        .page-title small { color: #6c757d; font-size: 0.9rem; transition: all var(--transition-speed);}
        .section-card {
            background: white;
            border-radius: 8px;
            box-shadow: 0 3px 5px rgba(0, 0, 0, 0.05);
            margin-bottom: 25px;
            overflow: hidden;
            transition: all var(--transition-speed);
        }
        .card-header {
            background: linear-gradient(to right, var(--primary-color), var(--secondary-color));
            color: white;
            padding: 12px 15px;
            font-weight: 600;
            display: flex;
            align-items: center;
            justify-content: space-between;
            font-size: 1.05rem;
        }
        .card-header-actions { display: flex; gap: 8px; align-items: center;}
        .card-body { padding: 15px;}
        .search-container { margin-bottom: 12px; display: flex; gap: 8px;}
        .search-box {
            flex: 1;
            padding: 7px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 0.9rem;
        }
        .table-container {
            overflow-x: auto;
            max-height: 500px;
            overflow-y: auto;
            border: 1px solid #eee;
            border-radius: 6px;
        }
        .table { width: 100%; border-collapse: collapse; font-size: 0.9rem;}
        .table th {
            background-color: #e9f0f9;
            color: var(--primary-color);
            font-weight: 600;
            text-align: left;
            padding: 10px 12px;
            border-bottom: 2px solid #d0e1f9;
            position: sticky;
            top: 0;
        }
        .table td { padding: 10px 12px; border-bottom: 1px solid #eee;}
        .table tr:last-child td { border-bottom: none;}
        .table tr:hover { background-color: #f8fbff;}
        .positive { color: #28a745; font-weight: 600;}
        .negative { color: #dc3545; font-weight: 600;}
        .total-row {
            background-color: #e9f0f9 !important;
            font-weight: 700;
        }
        .total-row td { font-weight: 700 !important; }
        .btn-export {
            background: #28a745;
            color: white;
            border: none;
            border-radius: 4px;
            padding: 5px 10px;
            font-size: 0.85rem;
            display: inline-flex;
            align-items: center;
            transition: background 0.3s;
        }
        .btn-export:hover { background: #218838;}
        .btn-export i { margin-right: 5px;}
        .btn-search {
            background: #17a2b8;
            color: white;
            border: none;
            border-radius: 4px;
            padding: 7px 12px;
            cursor: pointer;
            transition: background 0.3s;
            font-size: 0.9rem;
        }
        .btn-search:hover { background: #138496;}
        .kpi-row {
            display: flex;
            gap: 1.5rem;
            margin-bottom: 2rem;
            flex-wrap: wrap;
        }
        .kpi-card {
            flex: 1 1 180px;
            background: linear-gradient(135deg, #020068 60%, #00d2ff 100%);
            color: #fff;
            border-radius: 12px;
            box-shadow: 0 2px 8px #0001;
            padding: 1.2rem 1.5rem;
            min-width: 180px;
            display: flex;
            align-items: center;
            gap: 1rem;
            transition: transform 0.2s;
        }
        .kpi-card:hover { transform: translateY(-4px) scale(1.03);}
        .kpi-icon { font-size: 2.2rem; opacity: 0.8;}
        .kpi-label { font-size: 1.1rem; opacity: 0.85;}
        .kpi-value { font-size: 1.5rem; font-weight: bold;}
        .dark-mode body { background: #181a1b; color: #e0e0e0;}
        .dark-mode .section-card, .dark-mode .chart-container { background: #23272b; color: #e0e0e0;}
        .dark-mode .main-header { background: #23272b; }
        .dark-mode .sidebar-header, .dark-mode #sidebar { background: linear-gradient(135deg, #23272b, #020068);}
        .dark-mode .table th { background: #23272b; color: #00d2ff;}
        .dark-mode .table tr:hover { background: #23272b;}
        .dark-mode .kpi-card { background: linear-gradient(135deg, #23272b 60%, #00d2ff 100%);}
        .dark-mode .btn-export { background: #00d2ff; color: #23272b;}
        .dark-mode .btn-export:hover { background: #00aacc;}
        .dark-mode .btn-search { background: #00d2ff; color: #23272b;}
        .dark-mode .btn-search:hover { background: #00aacc;}
        .dark-toggle {
            position: fixed; right: 20px; top: 90px; z-index: 2000;
            background: #fff; color: #020068; border: none; border-radius: 50%;
            width: 44px; height: 44px; box-shadow: 0 2px 8px #0002;
            display: flex; align-items: center; justify-content: center;
            font-size: 1.5rem; cursor: pointer; transition: background 0.2s;
        }
        .dark-mode .dark-toggle { background: #23272b; color: #00d2ff;}
        #toast { position: fixed; bottom: 30px; right: 30px; z-index: 3000; min-width: 200px; display: none;}
        #toast.show { display: block; animation: fadein 0.5s, fadeout 0.5s 2.5s;}
        @keyframes fadein { from {bottom: 0; opacity: 0;} to {bottom: 30px; opacity: 1;} }
        @keyframes fadeout { from {bottom: 30px; opacity: 1;} to {bottom: 0; opacity: 0;} }
        @media (max-width: 992px) {
            .sidebar-collapsed #sidebar { transform: translateX(0);}
            .sidebar-collapsed #content { margin-left: var(--sidebar-collapsed-width);}
            .sidebar-header h3, .menu-text { display: block;}
        }
        @media (max-width: 768px) {
            :root { --header-height: 70px;}
            .main-header { flex-direction: column; height: auto; padding: 10px;}
            .header-left { width: 100%; justify-content: space-between; margin-bottom: 10px;}
            .wrapper { padding-top: 120px;}
            #sidebar { top: 120px; height: calc(100vh - 120px);}
            .chart-container { height: 280px;}
        }
        @media (max-width: 576px) {
            .card-header { flex-direction: column; align-items: flex-start; gap: 10px;}
            .card-header-actions { width: 100%; justify-content: flex-end;}
            .search-container { flex-direction: column;}
            .table th, .table td { padding: 8px 10px; font-size: 0.85rem;}
        }
        .section-anchor {
            display: block;
            position: relative;
            top: calc(-1 * var(--header-height) - 15px);
            visibility: hidden;
        }
        .dashboard-charts-row {
            display: flex;
            gap: 2rem;
            margin-bottom: 2rem;
            flex-wrap: wrap;
        }
        .dashboard-charts-row .chart-card {
            flex: 1 1 350px;
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 8px #0001;
            padding: 1.5rem 1.5rem 1rem 1.5rem;
            min-width: 320px;
            min-height: 340px;
            display: flex;
            flex-direction: column;
            align-items: stretch;
            justify-content: flex-start;
        }
        .dashboard-charts-row .chart-title {
            font-size: 1.1rem;
            font-weight: 600;
            color: var(--primary-color);
            margin-bottom: 1rem;
            display: flex;
            align-items: center;
            gap: 0.5rem;
        }
        .dashboard-charts-row canvas {
            width: 100% !important;
            height: 260px !important;
            max-height: 260px;
        }
        @media (max-width: 1100px) {
            .dashboard-charts-row { flex-direction: column; gap: 1.5rem;}
            .dashboard-charts-row .chart-card { min-width: 0; }
        }
    </style>
</head>
<body>
    <!-- Dark mode toggle -->
    <button class="dark-toggle" id="darkToggle" title="Attiva/disattiva dark mode"><i class="bi bi-moon"></i></button>
    <div id="toast" class="alert alert-success py-2 px-3">Esportazione completata!</div>
    <!-- Header fisso -->
    <header class="main-header">
        <div class="header-left">
            <button id="sidebarToggle" class="toggle-btn">
                <i class="bi bi-list"></i> Menu
            </button>
            <div class="page-title">
                <h1>Report Agente: {{ nome_agente }}</h1>
                <small>Analisi delle performance</small>
            </div>
        </div>
    </header>
    <div class="wrapper">
        <!-- Sidebar -->
        <nav id="sidebar">
            <div class="sidebar-header">
                <div class="logo-container">
                    <img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRIlNe3WWF6sGbPEOWXCZIKd7d0xdzUGncS6Q&s" alt="Company Logo">
                </div>
                <h3>Menù</h3>
            </div>
            <div class="sidebar-content">
                <ul class="sidebar-menu">
                    <li><a href="#kpi" class="active"><i class="bi bi-bar-chart-fill"></i> <span class="menu-text">KPI</span></a></li>
                    <li><a href="#clienti"><i class="bi bi-people-fill"></i> <span class="menu-text">Clienti</span></a></li>
                    <li><a href="#famiglie"><i class="bi bi-diagram-3-fill"></i> <span class="menu-text">Famiglie</span></a></li>
                    <li><a href="#mensile"><i class="bi bi-calendar-month-fill"></i> <span class="menu-text">Mensile</span></a></li>
                    <li><a href="#grafico"><i class="bi bi-bar-chart-line-fill"></i> <span class="menu-text">Grafici</span></a></li>
                    <li><a href="#analisi"><i class="bi bi-lightbulb-fill"></i> <span class="menu-text">Analisi Extra</span></a></li>
                </ul>
            </div>
        </nav>
        <!-- Contenuto principale -->
        <div id="content">
            <!-- KPI Cards -->
            <div id="kpi-anchor" class="section-anchor"></div>
            <div id="kpi" class="kpi-row">
                {% set tot = tabella_fatturato[-1] if tabella_fatturato %}
                <div class="kpi-card">
                    <span class="kpi-icon"><i class="bi bi-cash-stack"></i></span>
                    <div>
                        <div class="kpi-label">Fatturato 2024</div>
                        <div class="kpi-value">{{ '{:,.2f}'.format(tot['Fatturato 2024']) }} €</div>
                    </div>
                </div>
                <div class="kpi-card">
                    <span class="kpi-icon"><i class="bi bi-cash-coin"></i></span>
                    <div>
                        <div class="kpi-label">Fatturato 2025</div>
                        <div class="kpi-value">{{ '{:,.2f}'.format(tot['Fatturato 2025']) }} €</div>
                    </div>
                </div>
                <div class="kpi-card">
                    <span class="kpi-icon"><i class="bi bi-arrow-up-right-circle"></i></span>
                    <div>
                        <div class="kpi-label">Var. Assoluta</div>
                        <div class="kpi-value {{ 'positive' if tot['Var (€)'] >= 0 else 'negative' }}">
                            {{ '{:+,.2f}'.format(tot['Var (€)']) }} €
                        </div>
                    </div>
                </div>
                <div class="kpi-card">
                    <span class="kpi-icon"><i class="bi bi-percent"></i></span>
                    <div>
                        <div class="kpi-label">Var. %</div>
                        <div class="kpi-value {{ 'positive' if tot['Var (%)'] >= 0 else 'negative' }}">
                            {{ '{:+,.2f}'.format(tot['Var (%)']) }}%
                        </div>
                    </div>
                </div>
                <div class="kpi-card">
                    <span class="kpi-icon"><i class="bi bi-trophy"></i></span>
                    <div>
                        <div class="kpi-label">Top Cliente 2025</div>
                        {% set top_cliente = (tabella_fatturato[:-1]|sort(attribute='Fatturato 2025', reverse=True))[0] %}
                        <div class="kpi-value">{{ top_cliente['Ragione Sociale'] }}</div>
                    </div>
                </div>
            </div>
            <!-- Sezione Clienti -->
            <div id="clienti-anchor" class="section-anchor"></div>
            <div id="clienti" class="section-card">
                <div class="card-header">
                    <span><i class="bi bi-people-fill"></i> Confronto Fatturato Clienti</span>
                    <div class="card-header-actions">
                        <button class="btn-export" onclick="exportTableToExcel('clientiTable', 'Fatturato_Clienti')">
                            <i class="bi bi-download"></i> Esporta
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <div class="search-container">
                        <input type="text" id="searchClienti" class="search-box" placeholder="Cerca per cliente..." onkeyup="searchTable('searchClienti', 'clientiTable')">
                        <button class="btn-search" onclick="searchTable('searchClienti', 'clientiTable')">
                            <i class="bi bi-search"></i> Cerca
                        </button>
                    </div>
                    <div class="table-container">
                        <table id="clientiTable" class="table">
                            <thead>
                                <tr>
                                    <th>Ragione Sociale</th>
                                    <th>Fatturato 2024 (€)</th>
                                    <th>Fatturato 2025 (€)</th>
                                    <th>Var (€)</th>
                                    <th>Var (%)</th>
                                </tr>
                            </thead>
                            <tbody>
                            {% for row in tabella_fatturato %}
                            <tr {% if row['Ragione Sociale'] == 'Totale' %}class="total-row"{% endif %}>
                                <td>{{ row['Ragione Sociale'] }}</td>
                                <td>
                                {% if row['Fatturato 2024'] == 0 %}
                                    &nbsp;
                                {% else %}
                                    {{ '{:,.2f}'.format(row['Fatturato 2024']) }}
                                {% endif %}
                                </td>
                                <td>
                                {% if row['Fatturato 2025'] == 0 %}
                                    &nbsp;
                                {% else %}
                                    {{ '{:,.2f}'.format(row['Fatturato 2025']) }}
                                {% endif %}
                                </td>
                                <td class="{{ 'positive' if row['Var (€)'] >= 0 else 'negative' }}">
                                {% if row['Var (€)'] == 0 %}
                                    &nbsp;
                                {% else %}
                                    {{ '{:+,.2f}'.format(row['Var (€)']) }}
                                {% endif %}
                                </td>
                                <td class="{{ 'positive' if row['Var (%)'] >= 0 else 'negative' }}">
                                {% if row['Var (%)'] == 0 %}
                                    &nbsp;
                                {% else %}
                                    {{ '{:+,.2f}'.format(row['Var (%)']) }}%
                                {% endif %}
                                </td>
                            </tr>
                            {% endfor %}
                            </tbody>

                        </table>
                    </div>
                </div>
            </div>
            <!-- Sezione Famiglie -->
            <div id="famiglie-anchor" class="section-anchor"></div>
            <div id="famiglie" class="section-card">
                <div class="card-header">
                    <span><i class="bi bi-diagram-3-fill"></i> Fatturato Betacavi - Betanet 2025</span>
                    <div class="card-header-actions">
                        <button class="btn-export" onclick="exportTableToExcel('famiglieTable', 'Fatturato_Famiglie')">
                            <i class="bi bi-download"></i> Esporta
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <div class="search-container">
                        <input type="text" id="searchFamiglie" class="search-box" placeholder="Cerca per famiglia, sottofamiglia..." onkeyup="searchTable('searchFamiglie', 'famiglieTable')">
                        <button class="btn-search" onclick="searchTable('searchFamiglie', 'famiglieTable')">
                            <i class="bi bi-search"></i> Cerca
                        </button>
                    </div>
                    <div class="table-container">
                        <table id="famiglieTable" class="table">
                            <thead>
                                <tr>
                                    <th>Famiglia</th>
                                    <th>Sottofamiglia</th>
                                    {% for marca in marche %}
                                    <th>{{ marca }} (€)</th>
                                    {% endfor %}
                                    <th>Totale (€)</th>
                                </tr>
                            </thead>
                            <tbody>
                            {% set last_row = tabella_marca[-1] %}
                            {% for row in tabella_marca[:-1] %}
                            <tr>
                                <td>{{ row['Famiglia'] }}</td>
                                <td>{{ row['Descrizione Sottofamiglia'] }}</td>
                                {% for marca in marche %}
                                <td>
                                {% if row[marca] == 0 %}
                                    &nbsp;
                                {% else %}
                                    {{ '{:,.2f}'.format(row[marca]) }}
                                {% endif %}
                                </td>
                                {% endfor %}
                                <td>
                                {% if row['Totale (€)'] == 0 %}
                                    &nbsp;
                                {% else %}
                                    {{ '{:,.2f}'.format(row['Totale (€)']) }}
                                {% endif %}
                                </td>
                            </tr>
                            {% endfor %}

                            <!-- Riga totale -->
                            <tr class="total-row">
                                <td>TOTALE</td>
                                <td></td>
                                {% for marca in marche %}
                                <td>
                                {% if last_row[marca] == 0 %}
                                    &nbsp;
                                {% else %}
                                    <strong>{{ '{:,.2f}'.format(last_row[marca]) }}</strong>
                                {% endif %}
                                </td>
                                {% endfor %}
                                <td>
                                {% if last_row['Totale (€)'] == 0 %}
                                    &nbsp;
                                {% else %}
                                    <strong>{{ '{:,.2f}'.format(last_row['Totale (€)']) }}</strong>
                                {% endif %}
                                </td>
                            </tr>
                            </tbody>

                        </table>
                    </div>
                </div>
            </div>
            <!-- Sezione Mensile -->
            <div id="mensile-anchor" class="section-anchor"></div>
            <div id="mensile" class="section-card">
                <div class="card-header">
                    <span><i class="bi bi-calendar-month-fill"></i> Fatturato Mensile</span>
                    <div class="card-header-actions">
                        <button class="btn-export" onclick="exportTableToExcel('mensileTable', 'Fatturato_Mensile')">
                            <i class="bi bi-download"></i> Esporta
                        </button>
                    </div>
                </div>
                <div class="card-body">
                    <div class="search-container">
                        <input type="text" id="searchMensile" class="search-box" placeholder="Cerca per mese..." onkeyup="searchTable('searchMensile', 'mensileTable')">
                        <button class="btn-search" onclick="searchTable('searchMensile', 'mensileTable')">
                            <i class="bi bi-search"></i> Cerca
                        </button>
                    </div>
                    <div class="table-container">
                        <table id="mensileTable" class="table">
                            <thead>
                                <tr>
                                    <th>Mese</th>
                                    <th>Fatturato 2024 (€)</th>
                                    <th>Fatturato 2025 (€)</th>
                                    <th>Var (€)</th>
                                    <th>Var (%)</th>
                                </tr>
                            </thead>
                            <tbody>
                                {% for row in tabella_mensile %}
                                <tr {% if row['Mese'] == 'Totale' %}class="total-row"{% endif %}>
                                    <td>{{ row['Mese'] }}</td>
                                    <td>{{ '{:,.2f}'.format(row['Fatturato 2024']) }}</td>
                                    <td>{{ '{:,.2f}'.format(row['Fatturato 2025']) }}</td>
                                    <td class="{{ 'positive' if row['Var (€)'] >= 0 else 'negative' }}">
                                        {{ '{:+,.2f}'.format(row['Var (€)']) }}
                                    </td>
                                    <td class="{{ 'positive' if row['Var (%)'] >= 0 else 'negative' }}">
                                        {{ '{:+,.2f}'.format(row['Var (%)']) }}%
                                    </td>
                                </tr>
                                {% endfor %}
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
            <!-- Sezione Grafico: Confronto Fatturato Mensile -->
            <div id="grafico-anchor" class="section-anchor"></div>
            <div id="grafico" class="dashboard-charts-row">
                <div class="chart-card">
                    <div class="chart-title"><i class="bi bi-bar-chart-line-fill"></i> Fatturato Mensile (Barre)</div>
                    <canvas id="salesChartBar"></canvas>
                </div>
                <div class="chart-card">
                    <div class="chart-title"><i class="bi bi-graph-up"></i> Fatturato Mensile (Linee)</div>
                    <canvas id="salesChartLine"></canvas>
                </div>
            </div>
            <!-- Analisi Extra -->
            <div id="analisi-anchor" class="section-anchor"></div>
            <div id="analisi" class="dashboard-charts-row">
                <div class="chart-card">
                    <div class="chart-title"><i class="bi bi-diagram-3-fill"></i>Famiglie (2025)</div>
                    <canvas id="chartFamiglie"></canvas>
                </div>
                <div class="chart-card">
                    <div class="chart-title"><i class="bi bi-pie-chart-fill"></i> Ripartizione Fatturato per Marca (2025)</div>
                    <canvas id="chartMarche"></canvas>
                </div>
            </div>
        </div>
    </div>
   <!-- Modal Dettaglio Cliente -->
<div class="modal fade" id="clienteModal" tabindex="-1" aria-labelledby="clienteModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-xl modal-dialog-centered">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="clienteModalLabel">Dettaglio Cliente</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Chiudi"></button>
      </div>
      <div class="modal-body">
        <!-- Sezione KPI dinamici -->
        <div class="mb-3" id="clienteSummary">
          <!-- Riempito via JS -->
        </div>

        <!-- Tabella articoli -->
         <div class="d-flex justify-content-between align-items-center mb-2">
             <h5 class="mb-0">Articoli acquistati</h5>
            <button class="btn btn-success btn-sm" onclick="exportArticoliToExcel()">
            <i class="bi bi-download"></i> Esporta Excel
             </button>
        </div>
        <div class="table-responsive">
          <table class="table table-sm table-bordered align-middle" id="tabellaArticoliCliente">
            <thead class="table-light">
              <tr>
                <th>Codice</th>
                <th>Descrizione</th>
                <th>Quantità 2024</th>
                <th>Valore 2024 (€)</th>
                <th>Quantità 2025</th>
                <th>Valore 2025 (€)</th>
                <th>Var (€)</th>
                <th>Var (%)</th>
              </tr>
            </thead>
            <tbody>
              <!-- Riempito via JS -->
            </tbody>
          </table>
        </div>
      </div>
    </div>
  </div>
</div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        // Dark mode toggle
        document.getElementById('darkToggle').onclick = function() {
            document.body.classList.toggle('dark-mode');
            localStorage.setItem('darkMode', document.body.classList.contains('dark-mode'));
        };
        if(localStorage.getItem('darkMode') === 'true') document.body.classList.add('dark-mode');
        // Toast
        function showToast(msg) {
            var toast = document.getElementById('toast');
            toast.textContent = msg;
            toast.className = "alert alert-success show";
            setTimeout(function(){ toast.className = toast.className.replace("show", ""); }, 3000);
        }
        // Esporta tabella
        function exportTableToExcel(tableId, filename) {
            const table = document.getElementById(tableId);
            const wb = XLSX.utils.table_to_book(table, {sheet: "Dati"});
            XLSX.writeFile(wb, `${filename}.xlsx`);
            showToast("Esportazione completata!");
        }
        // Ricerca
        function searchTable(inputId, tableId) {
            const input = document.getElementById(inputId);
            const filter = input.value.toUpperCase();
            const table = document.getElementById(tableId);
            const rows = table.getElementsByTagName('tbody')[0].getElementsByTagName('tr');
            for (let i = 0; i < rows.length; i++) {
                const cells = rows[i].getElementsByTagName('td');
                let found = false;
                for (let j = 0; j < cells.length; j++) {
                    const cell = cells[j];
                    if (cell) {
                        const txtValue = cell.textContent || cell.innerText;
                        if (txtValue.toUpperCase().indexOf(filter) > -1) {
                            found = true; break;
                        }
                    }
                }
                rows[i].style.display = found ? '' : 'none';
            }
        }

        // Chart.js instances
        let salesChartBarInstance = null;
        let salesChartLineInstance = null;
        let marcheChartInstance = null;
        let famiglieChartInstance = null;

        // Funzione per (re)inizializzare i grafici
        function renderCharts() {
            // Dati mensili
            const months = [];
            const sales2024 = [];
            const sales2025 = [];
            const rows = Array.from(document.querySelectorAll('#mensileTable tbody tr')).filter(r => r.style.display !== 'none' && r.cells[0].textContent !== 'Totale');
            rows.forEach(row => {
                months.push(row.cells[0].textContent);
                sales2024.push(parseFloat(row.cells[1].textContent.replace(/,/g, '').replace('€','')));
                sales2025.push(parseFloat(row.cells[2].textContent.replace(/,/g, '').replace('€','')));
            });

            // Bar Chart
            if (salesChartBarInstance) salesChartBarInstance.destroy();
            salesChartBarInstance = new Chart(document.getElementById('salesChartBar').getContext('2d'), {
                type: 'bar',
                data: {
                    labels: months,
                    datasets: [
                        {
                            label: 'Fatturato 2024',
                            data: sales2024,
                            backgroundColor: 'rgba(58, 123, 213, 0.7)',
                            borderColor: 'rgba(58, 123, 213, 1)',
                            borderWidth: 1
                        },
                        {
                            label: 'Fatturato 2025',
                            data: sales2025,
                            backgroundColor: 'rgba(0, 210, 255, 0.7)',
                            borderColor: 'rgba(0, 210, 255, 1)',
                            borderWidth: 1
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    animation: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            grid: { color: 'rgba(0, 0, 0, 0.05)' },
                            ticks: { callback: function(value) { return '€' + value.toLocaleString(); } }
                        },
                        x: { grid: { display: false } }
                    },
                    plugins: {
                        legend: { position: 'top' },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    return context.dataset.label + ': €' + context.parsed.y.toLocaleString();
                                }
                            }
                        }
                    }
                }
            });

            // Line Chart
            if (salesChartLineInstance) salesChartLineInstance.destroy();
            salesChartLineInstance = new Chart(document.getElementById('salesChartLine').getContext('2d'), {
                type: 'line',
                data: {
                    labels: months,
                    datasets: [
                        {
                            label: 'Fatturato 2024',
                            data: sales2024,
                            borderColor: 'rgba(58, 123, 213, 1)',
                            backgroundColor: 'rgba(58, 123, 213, 0.1)',
                            fill: true,
                            tension: 0.3,
                            pointRadius: 4
                        },
                        {
                            label: 'Fatturato 2025',
                            data: sales2025,
                            borderColor: 'rgba(0, 210, 255, 1)',
                            backgroundColor: 'rgba(0, 210, 255, 0.1)',
                            fill: true,
                            tension: 0.3,
                            pointRadius: 4
                        }
                    ]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    animation: false,
                    scales: {
                        y: {
                            beginAtZero: true,
                            grid: { color: 'rgba(0, 0, 0, 0.05)' },
                            ticks: { callback: function(value) { return '€' + value.toLocaleString(); } }
                        },
                        x: { grid: { display: false } }
                    },
                    plugins: {
                        legend: { position: 'top' },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    return context.dataset.label + ': €' + context.parsed.y.toLocaleString();
                                }
                            }
                        }
                    }
                }
            });

            // Marche Chart
            const marche = {{ marche|tojson }};
            const tabellaMarca = {{ tabella_marca|tojson }};
            let totaliMarche = marche.map(marca =>
            tabellaMarca
                .filter(row => row.Famiglia !== "") // Esclude la riga di totale
                .reduce((acc, row) => acc + (row[marca] || 0), 0)
            );
            if (marcheChartInstance) marcheChartInstance.destroy();
            marcheChartInstance = new Chart(document.getElementById('chartMarche'), {
                type: 'doughnut',
                data: {
                    labels: marche,
                    datasets: [{
                        data: totaliMarche,
                        backgroundColor: [
                            '#020068', '#00d2ff', '#28a745', '#ffc107', '#dc3545', '#6f42c1', '#fd7e14', '#20c997'
                        ]
                    }]
                },
                options: {
                    responsive: true,
                    plugins: { legend: { position: 'bottom' } }
                }
            });

            // Top 5 Famiglie Chart (senza TOTALE)
            const famiglie = {};
            tabellaMarca.forEach(row => {
                if (row['Famiglia'] && row['Famiglia'] !== 'TOTALE') {
                    famiglie[row['Famiglia']] = (famiglie[row['Famiglia']] || 0) + row['Totale (€)'];
                }
            });
            const famiglieSorted = Object.entries(famiglie).sort((a, b) => b[1] - a[1]).slice(0, 5);
            if (famiglieChartInstance) famiglieChartInstance.destroy();
            famiglieChartInstance = new Chart(document.getElementById('chartFamiglie'), {
                type: 'bar',
                data: {
                    labels: famiglieSorted.map(f => f[0]),
                    datasets: [{
                        label: 'Fatturato',
                        data: famiglieSorted.map(f => f[1]),
                        backgroundColor: [
                            '#020068', '#00d2ff', '#28a745', '#ffc107', '#dc3545'
                        ]
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: { display: false },
                        tooltip: {
                            callbacks: {
                                label: function(context) {
                                    return '€' + context.parsed.y.toLocaleString();
                                }
                            }
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            ticks: { callback: function(value) { return '€' + value.toLocaleString(); } }
                        }
                    }
                }
            });
        }

        // Chiamata iniziale
        document.addEventListener('DOMContentLoaded', function() {
            renderCharts();
        });

        // Sidebar toggle: resize i grafici dopo la transizione
        document.getElementById('sidebarToggle').addEventListener('click', function() {
            const wrapper = document.querySelector('.wrapper');
            wrapper.classList.toggle('sidebar-collapsed');
            if (wrapper.classList.contains('sidebar-collapsed')) {
                wrapper.classList.remove('sidebar-open-optimization');
            } else {
                wrapper.classList.add('sidebar-open-optimization');
            }
            localStorage.setItem('sidebarCollapsed', wrapper.classList.contains('sidebar-collapsed'));
            setTimeout(function() {
                if (salesChartBarInstance) salesChartBarInstance.resize();
                if (salesChartLineInstance) salesChartLineInstance.resize();
                if (marcheChartInstance) marcheChartInstance.resize();
                if (famiglieChartInstance) famiglieChartInstance.resize();
            }, 350);
        });

        // Ridisegna i grafici anche su resize finestra
        window.addEventListener('resize', function() {
            if (salesChartBarInstance) salesChartBarInstance.resize();
            if (salesChartLineInstance) salesChartLineInstance.resize();
            if (marcheChartInstance) marcheChartInstance.resize();
            if (famiglieChartInstance) famiglieChartInstance.resize();
        });

       // Modal dettaglio cliente
       
    document.addEventListener('DOMContentLoaded', function () {
    const articoliPerCliente = {{ articoli_per_cliente | tojson }};

    document.querySelectorAll('#clientiTable tbody tr').forEach(row => {
        row.addEventListener('click', function () {
            const nome = this.cells[0].textContent;
            const fatt24 = this.cells[1].textContent;
            const fatt25 = this.cells[2].textContent;
            const varE = this.cells[3].textContent;
            const varP = this.cells[4].textContent;

            // Imposta il titolo
            document.getElementById('clienteModalLabel').textContent = "Dettaglio: " + nome;

            // Mostra i KPI
            document.getElementById('clienteSummary').innerHTML = `
                <ul class="list-group mb-3">
                    <li class="list-group-item"><strong>Fatturato 2024:</strong> ${fatt24} €</li>
                    <li class="list-group-item"><strong>Fatturato 2025:</strong> ${fatt25} €</li>
                    <li class="list-group-item"><strong>Var. Assoluta:</strong> ${varE} €</li>
                    <li class="list-group-item"><strong>Var. %:</strong> ${varP}</li>
                </ul>
            `;
const tbody = document.querySelector('#tabellaArticoliCliente tbody');
tbody.innerHTML = ''; // Pulisci

const articoli = articoliPerCliente[nome];
if (articoli && articoli.length > 0) {
    articoli.forEach(art => {
        const formatVal = (num) => {
            if (num === 0) return '';
            return num.toLocaleString('it-IT', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
        };
        const formatQty = (num) => {
            return num === 0 ? '' : num.toLocaleString('it-IT', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
        };

        const row = document.createElement('tr');
        row.innerHTML = `
            <td>${art['Codice']}</td>
            <td>${art['Descrizione']}</td>
            <td data-value="${art['Quantità 2024']}">${formatQty(art['Quantità 2024'])}</td>
            <td data-value="${art['Valore 2024']}">${formatVal(art['Valore 2024'])}</td>
            <td data-value="${art['Quantità 2025']}">${formatQty(art['Quantità 2025'])}</td>
            <td data-value="${art['Valore 2025']}">${formatVal(art['Valore 2025'])}</td>
            <td data-value="${art['Var (€)']}" class="${art['Var (€)'] >= 0 ? 'positive' : 'negative'}">
                ${art['Var (€)'] >= 0 ? '+' : ''}${formatVal(art['Var (€)'])}
            </td>
            <td data-value="${art['Var (%)']}" class="${art['Var (%)'] >= 0 ? 'positive' : 'negative'}">
                ${art['Var (%)'] >= 0 ? '+' : ''}${art['Var (%)'].toFixed(2)}%
            </td>
        `;
        tbody.appendChild(row);
    });



                    } else {
                        const row = document.createElement('tr');
                        row.innerHTML = `<td colspan="8" class="text-center text-muted">Nessun articolo disponibile per questo cliente.</td>`;
                        tbody.appendChild(row);
                    }

                    const modal = new bootstrap.Modal(document.getElementById('clienteModal'));
                    modal.show();
                });
            });
        });

        // Sidebar stato e smooth scroll
        document.addEventListener('DOMContentLoaded', function() {
            const wrapper = document.querySelector('.wrapper');
            const isCollapsed = localStorage.getItem('sidebarCollapsed') === 'true';
            if (isCollapsed) {
                wrapper.classList.add('sidebar-collapsed');
                wrapper.classList.remove('sidebar-open-optimization');
            } else {
                wrapper.classList.remove('sidebar-collapsed');
                wrapper.classList.add('sidebar-open-optimization');
            }
        });
        document.querySelectorAll('.sidebar-menu a').forEach(anchor => {
            anchor.addEventListener('click', function(e) {
                e.preventDefault();
                document.querySelectorAll('.sidebar-menu a').forEach(a => { a.classList.remove('active'); });
                this.classList.add('active');
                const targetId = this.getAttribute('href').substring(1);
                const targetAnchor = document.getElementById(`${targetId}-anchor`);
                if (targetAnchor) {
                    const headerHeight = document.querySelector('.main-header').offsetHeight;
                    const offsetPosition = targetAnchor.offsetTop - headerHeight;
                    window.scrollTo({ top: offsetPosition, behavior: 'smooth' });
                }
            });
        });

       function exportArticoliToExcel() {
  const table = document.getElementById('tabellaArticoliCliente');

  const rows = [];
  const trs = table.querySelectorAll('tbody tr');
  if (trs.length === 0) return alert("Nessuna riga da esportare.");

  // Intestazione
  const headers = Array.from(table.querySelectorAll('thead th')).map(th => th.textContent.trim());
  rows.push(headers);

  // Riga per riga
  trs.forEach(tr => {
    const cells = Array.from(tr.querySelectorAll('td')).map(td => {
      const raw = td.getAttribute('data-value');
      if (raw !== null) {
        const val = parseFloat(raw);
        return isNaN(val) ? td.textContent.trim() : val;
      }
      return td.textContent.trim();
    });
    rows.push(cells);
  });

  const worksheet = XLSX.utils.aoa_to_sheet(rows);
  const workbook = XLSX.utils.book_new();
  XLSX.utils.book_append_sheet(workbook, worksheet, "Articoli Cliente");

  const nomeCliente = document.getElementById('clienteModalLabel').textContent.replace('Dettaglio: ', '').replace(/[^a-zA-Z0-9]/g, '_');
  XLSX.writeFile(workbook, `Articoli_${nomeCliente}.xlsx`);
}
    </script>
</body>
</html>