<!DOCTYPE html>
<html lang="it">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Expires" content="0">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Studio Console | Optlyx Prisma</title>
    <meta name="description"
        content="Optlyx Prisma — la console AI per studi professionali. Gestione clienti, fatturazione elettronica, documenti, inbox e automazione intelligente in un'unica piattaforma.">
    <meta name="robots" content="noindex, nofollow">
    <link rel="canonical" href="https://prisma-optlyx.web.app/">
    <link rel="icon" type="image/png"
        href="https://firebasestorage.googleapis.com/v0/b/playground-optlyx.firebasestorage.app/o/optlyxAssets%2Flogo%20grad.png?alt=media&token=151c2e9c-8e41-4829-864d-8163239180bd">
    <link rel="apple-touch-icon"
        href="https://firebasestorage.googleapis.com/v0/b/playground-optlyx.firebasestorage.app/o/optlyxAssets%2Flogo%20grad.png?alt=media&token=151c2e9c-8e41-4829-864d-8163239180bd">
    <link rel="manifest" href="/public/manifest.json">
    <meta name="theme-color" content="#0f172a">
    <style>
        #main-nav::-webkit-scrollbar {
            display: none
        }
    </style>
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">

    <!-- Google Fonts: Plus Jakarta Sans -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap"
        rel="stylesheet">

    <!-- [REMOVED] Driver.js — replaced by unified OnboardingWizard -->

    <!-- Open Graph -->
    <meta property="og:type" content="website">
    <meta property="og:title" content="Studio Console | Optlyx Prisma">
    <meta property="og:description"
        content="La console AI per studi professionali. Gestione clienti, fatturazione elettronica, documenti e automazione intelligente.">
    <meta property="og:url" content="https://prisma-optlyx.web.app/">
    <meta property="og:image"
        content="https://firebasestorage.googleapis.com/v0/b/playground-optlyx.firebasestorage.app/o/optlyxAssets%2Flogo%20grad.png?alt=media&token=151c2e9c-8e41-4829-864d-8163239180bd">
    <meta property="og:site_name" content="Optlyx Prisma">
    <meta property="og:locale" content="it_IT">

    <!-- Twitter Card -->
    <meta name="twitter:card" content="summary">
    <meta name="twitter:title" content="Studio Console | Optlyx Prisma">
    <meta name="twitter:description" content="La console AI per studi professionali italiani.">
    <meta name="twitter:image"
        content="https://firebasestorage.googleapis.com/v0/b/playground-optlyx.firebasestorage.app/o/optlyxAssets%2Flogo%20grad.png?alt=media&token=151c2e9c-8e41-4829-864d-8163239180bd">

    <!-- Structured Data -->
    <script type="application/ld+json">
    {
      "@context": "https://schema.org",
      "@type": "SoftwareApplication",
      "name": "Optlyx Prisma",
      "applicationCategory": "BusinessApplication",
      "operatingSystem": "Web",
      "description": "Piattaforma AI per studi professionali: gestione clienti, fatturazione elettronica, documenti, inbox e automazione intelligente.",
      "url": "https://prisma-optlyx.web.app",
      "author": {
        "@type": "Organization",
        "name": "Optlyx",
        "url": "https://optlyx.com"
      },
      "offers": {
        "@type": "Offer",
        "price": "0",
        "priceCurrency": "EUR"
      }
    }
    </script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script>window.__tw_warn = console.warn; console.warn = function (...a) { if (typeof a[0] === 'string' && a[0].includes('cdn.tailwindcss.com')) return; window.__tw_warn.apply(console, a) };</script>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/lucide@latest"></script>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;600;700;800&display=swap"
        rel="stylesheet">
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="components/loader.css">
    <link rel="stylesheet" href="pages/tracker.css">
    <link rel="stylesheet" href="pages/team-chat.css?v=20260219b">
    <link rel="stylesheet" href="css/tab-guide.css">


    <script src="https://www.gstatic.com/firebasejs/10.7.1/firebase-app-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/10.7.1/firebase-auth-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/10.7.1/firebase-firestore-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/10.7.1/firebase-functions-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/10.7.1/firebase-storage-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/10.7.1/firebase-database-compat.js"></script>

    <script src="https://cdn.sheetjs.com/xlsx-0.20.1/package/dist/xlsx.full.min.js"></script>
    <script src="firebase-init.js"></script>
    <script src="js/system-monitor.js"></script>
    <script src="js/presence-module.js"></script>
    <script src="js/ateco-codes.js"></script>

    <!-- Collaborative Presence Cursor Styles -->
    <style>
        /* ═══════════════════════════════════════════════
           PRESENCE ENGINE v2.0 — SUPERCHARGED STYLES
           ═══════════════════════════════════════════════ */

        /* ─── Cursors (inside #main-scroll-area, below modals) ─── */
        #main-scroll-area {
            position: relative;
        }

        .presence-cursor {
            position: absolute;
            z-index: 40;
            pointer-events: none;
            transition: left 150ms cubic-bezier(.4, 0, .2, 1), top 150ms cubic-bezier(.4, 0, .2, 1), opacity 300ms ease;
            will-change: left, top;
            opacity: 0;
        }

        .presence-cursor-arrow {
            display: block;
            filter: drop-shadow(0 1px 2px rgba(0, 0, 0, .25));
            transition: filter 200ms ease;
        }

        .presence-cursor-arrow.spotlight {
            filter: drop-shadow(0 0 8px rgba(255, 220, 50, .7)) drop-shadow(0 0 16px rgba(255, 220, 50, .3));
        }

        .presence-cursor-label {
            display: inline-block;
            margin-left: 12px;
            margin-top: -4px;
            padding: 2px 8px;
            border-radius: 6px;
            font-size: 11px;
            font-weight: 600;
            color: #fff;
            white-space: nowrap;
            line-height: 1.4;
            box-shadow: 0 1px 4px rgba(0, 0, 0, .2);
            font-family: 'Plus Jakarta Sans', -apple-system, sans-serif;
        }

        .typing-dots {
            letter-spacing: 1px;
            animation: typingPulse 1s infinite;
        }

        @keyframes typingPulse {

            0%,
            100% {
                opacity: 1;
            }

            50% {
                opacity: .3;
            }
        }

        /* ─── Avatar Stack — Rich Cards ─── */
        .presence-avatar-stack {
            display: flex;
            align-items: center;
            gap: 6px;
            margin-right: 12px;
            max-width: 480px;
            overflow-x: auto;
            overflow-y: visible;
            scrollbar-width: none;
        }

        .presence-avatar-stack::-webkit-scrollbar {
            display: none;
        }

        .presence-avatar-card {
            display: flex;
            align-items: center;
            gap: 7px;
            padding: 3px 10px 3px 3px;
            border-radius: 20px;
            background: rgba(255, 255, 255, .06);
            border: 1px solid rgba(255, 255, 255, .08);
            cursor: pointer;
            white-space: nowrap;
            transition: all 200ms ease;
            flex-shrink: 0;
        }

        .presence-avatar-card:hover {
            background: rgba(255, 255, 255, .12);
            border-color: rgba(255, 255, 255, .18);
            transform: translateY(-1px);
        }

        .presence-avatar-card.same-page {
            border-color: var(--avatar-color, #7c3aed);
            box-shadow: 0 0 8px color-mix(in srgb, var(--avatar-color) 30%, transparent);
        }

        .presence-avatar-card.following {
            animation: followPulse 2s infinite;
        }

        @keyframes followPulse {

            0%,
            100% {
                box-shadow: 0 0 0 0 rgba(124, 58, 237, .4);
            }

            50% {
                box-shadow: 0 0 0 4px rgba(124, 58, 237, 0);
            }
        }

        .presence-avatar-circle {
            width: 26px;
            height: 26px;
            border-radius: 50%;
            background: var(--avatar-color, #7c3aed);
            color: #fff;
            font-size: 10px;
            font-weight: 700;
            display: flex;
            align-items: center;
            justify-content: center;
            position: relative;
            flex-shrink: 0;
            font-family: 'Plus Jakarta Sans', sans-serif;
        }

        /* Status dots */
        .presence-status-dot {
            position: absolute;
            bottom: -1px;
            right: -1px;
            width: 8px;
            height: 8px;
            border-radius: 50%;
            border: 2px solid #0a0a0a;
        }

        .presence-status-active {
            background: #22c55e;
        }

        .presence-status-idle {
            background: #eab308;
        }

        .presence-status-away {
            background: #ef4444;
        }

        .presence-status-busy {
            background: #ef4444;
        }

        .presence-status-dnd {
            background: #6b7280;
        }

        /* Typing / spotlight badges */
        .presence-typing-badge,
        .presence-spotlight-badge {
            position: absolute;
            top: -4px;
            right: -4px;
            font-size: 9px;
            line-height: 1;
        }

        .presence-avatar-info {
            display: flex;
            flex-direction: column;
            line-height: 1.2;
        }

        .presence-avatar-name {
            font-size: 11px;
            font-weight: 600;
            color: #ededed;
            font-family: 'Plus Jakarta Sans', sans-serif;
        }

        .presence-avatar-tab {
            font-size: 10px;
            color: #888;
            font-family: 'Plus Jakarta Sans', sans-serif;
            max-width: 160px;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        /* ─── Focus Rings (remote user editing a field) ─── */
        .presence-focus-ring {
            position: absolute;
            z-index: 39;
            border: 2px solid var(--ring-color, #7c3aed);
            border-radius: 6px;
            pointer-events: none;
            box-shadow: 0 0 8px color-mix(in srgb, var(--ring-color) 30%, transparent);
            animation: focusRingPulse 2s infinite;
        }

        .presence-focus-ring::after {
            content: attr(data-user);
            position: absolute;
            top: -18px;
            left: 4px;
            font-size: 9px;
            font-weight: 600;
            color: var(--ring-color);
            font-family: 'Plus Jakarta Sans', sans-serif;
            white-space: nowrap;
        }

        @keyframes focusRingPulse {

            0%,
            100% {
                opacity: 1;
            }

            50% {
                opacity: .5;
            }
        }

        /* ─── Toast Notifications ─── */
        .presence-toast-container {
            position: fixed;
            bottom: 20px;
            right: 20px;
            z-index: 9990;
            display: flex;
            flex-direction: column;
            gap: 8px;
            max-width: 300px;
            pointer-events: none;
        }

        .presence-toast {
            padding: 11px 18px;
            border-radius: 14px;
            background: rgba(14, 14, 20, .65);
            backdrop-filter: blur(20px) saturate(1.6);
            -webkit-backdrop-filter: blur(20px) saturate(1.6);
            border: 1px solid rgba(255, 255, 255, .07);
            border-left: 3px solid #7c3aed;
            color: rgba(255, 255, 255, .88);
            font-size: 12px;
            font-weight: 500;
            font-family: 'Plus Jakarta Sans', sans-serif;
            box-shadow: 0 8px 32px rgba(0, 0, 0, .35), inset 0 1px 0 rgba(255, 255, 255, .04);
            transform: translateX(120%);
            opacity: 0;
            transition: all 350ms cubic-bezier(.34, 1.56, .64, 1);
        }

        .presence-toast.show {
            transform: translateX(0);
            opacity: 1;
        }

        /* ─── Rich User Card — GLASSY ─── */
        .presence-user-card {
            position: fixed;
            top: 56px;
            right: 16px;
            z-index: 9991;
            width: 310px;
            background: rgba(10, 10, 16, .62);
            backdrop-filter: blur(28px) saturate(1.8);
            -webkit-backdrop-filter: blur(28px) saturate(1.8);
            border: 1px solid rgba(255, 255, 255, .08);
            border-radius: 20px;
            padding: 20px;
            box-shadow: 0 20px 56px rgba(0, 0, 0, .45), 0 0 0 1px rgba(255, 255, 255, .04), inset 0 1px 0 rgba(255, 255, 255, .06);
            font-family: 'Plus Jakarta Sans', sans-serif;
            color: rgba(255, 255, 255, .88);
            animation: cardGlassIn 300ms cubic-bezier(.34, 1.56, .64, 1);
        }

        @keyframes cardGlassIn {
            from {
                opacity: 0;
                transform: translateY(-12px) scale(.92);
                backdrop-filter: blur(0px);
            }

            to {
                opacity: 1;
                transform: translateY(0) scale(1);
                backdrop-filter: blur(24px) saturate(1.8);
            }
        }

        @keyframes cardSlideIn {
            from {
                opacity: 0;
                transform: translateY(-8px) scale(.96);
            }

            to {
                opacity: 1;
                transform: translateY(0) scale(1);
            }
        }

        .puc-header {
            display: flex;
            align-items: center;
            gap: 12px;
            padding-bottom: 12px;
            margin-bottom: 12px;
            border-bottom: 1px solid rgba(255, 255, 255, .08);
        }

        .puc-avatar {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            color: #fff;
            font-weight: 700;
            font-size: 14px;
            display: flex;
            align-items: center;
            justify-content: center;
            flex-shrink: 0;
        }

        .puc-name {
            font-size: 14px;
            font-weight: 700;
            color: #fff;
        }

        .puc-status {
            font-size: 11px;
            color: #999;
            margin-top: 2px;
        }

        .puc-msg {
            font-size: 10px;
            color: #7c3aed;
            font-style: italic;
            margin-top: 2px;
        }

        .puc-location {
            font-size: 12px;
            color: #ccc;
            margin-bottom: 8px;
        }

        .puc-ctx {
            color: #888;
        }

        .puc-detail {
            font-size: 11px;
            color: #888;
            margin-bottom: 4px;
        }

        .puc-actions {
            display: flex;
            gap: 8px;
            margin-top: 12px;
        }

        .puc-btn {
            flex: 1;
            padding: 7px 10px;
            border-radius: 10px;
            border: 1px solid rgba(255, 255, 255, .06);
            background: rgba(255, 255, 255, .04);
            color: rgba(255, 255, 255, .75);
            font-size: 11px;
            font-weight: 500;
            cursor: pointer;
            transition: background 150ms ease, color 150ms ease;
            font-family: 'Plus Jakarta Sans', sans-serif;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 6px;
        }

        .puc-btn:hover {
            background: rgba(255, 255, 255, .08);
            color: rgba(255, 255, 255, .95);
        }

        .puc-btn-nudge:hover {
            color: #fbbf24;
        }

        .puc-btn-follow:hover {
            color: #a78bfa;
        }

        /* ─── Nudge Shake ─── */
        .presence-nudge-shake {
            animation: nudgeShake 500ms ease;
        }

        @keyframes nudgeShake {

            0%,
            100% {
                transform: translateX(0);
            }

            10%,
            50%,
            90% {
                transform: translateX(-4px);
            }

            30%,
            70% {
                transform: translateX(4px);
            }
        }

        /* ─── User Count Badge ─── */
        .presence-count-badge {
            position: absolute;
            top: -4px;
            right: -4px;
            min-width: 16px;
            height: 16px;
            border-radius: 8px;
            background: #7c3aed;
            color: #fff;
            font-size: 9px;
            font-weight: 700;
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 0 4px;
            font-family: 'Plus Jakarta Sans', sans-serif;
            border: 2px solid #0a0a0a;
        }

        /* ─── User Card Section Labels ─── */
        .puc-section-label {
            font-size: 9px;
            font-weight: 700;
            text-transform: uppercase;
            letter-spacing: 1px;
            color: #555;
            margin-top: 12px;
            margin-bottom: 6px;
        }

        .puc-actions {
            margin-top: 6px;
        }

        /* ─── Reactions Bar (in user card) ─── */
        .puc-reactions {
            display: flex;
            gap: 4px;
            flex-wrap: wrap;
            margin-top: 6px;
        }

        .puc-reaction {
            width: 32px;
            height: 32px;
            border-radius: 8px;
            border: 1px solid rgba(255, 255, 255, .08);
            background: rgba(255, 255, 255, .04);
            font-size: 16px;
            cursor: pointer;
            transition: all 150ms ease;
            display: flex;
            align-items: center;
            justify-content: center;
        }

        .puc-reaction:hover {
            background: rgba(255, 255, 255, .1);
        }

        /* ─── CTA Button hover ─── */
        .puc-btn-cta:hover {
            color: #4ade80;
        }

        /* ─── Quick Message Popup — GLASSY ─── */
        .presence-quick-msg-popup {
            position: fixed;
            top: 56px;
            right: 16px;
            z-index: 9992;
            width: 320px;
            background: rgba(10, 10, 16, .62);
            backdrop-filter: blur(28px) saturate(1.8);
            -webkit-backdrop-filter: blur(28px) saturate(1.8);
            border: 1px solid rgba(255, 255, 255, .08);
            border-radius: 20px;
            padding: 16px;
            box-shadow: 0 20px 56px rgba(0, 0, 0, .45), inset 0 1px 0 rgba(255, 255, 255, .06);
            font-family: 'Plus Jakarta Sans', sans-serif;
            animation: cardGlassIn 300ms cubic-bezier(.34, 1.56, .64, 1);
        }

        .pqm-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding-bottom: 10px;
            margin-bottom: 10px;
            border-bottom: 1px solid rgba(255, 255, 255, .08);
            font-size: 12px;
            color: #ccc;
        }

        .pqm-close {
            background: none;
            border: none;
            color: #666;
            cursor: pointer;
            font-size: 14px;
            padding: 4px;
        }

        .pqm-close:hover {
            color: #fff;
        }

        .pqm-presets {
            display: flex;
            flex-direction: column;
            gap: 4px;
            margin-bottom: 10px;
        }

        .pqm-preset {
            padding: 7px 10px;
            border-radius: 8px;
            border: 1px solid rgba(255, 255, 255, .06);
            background: rgba(255, 255, 255, .04);
            color: #ccc;
            font-size: 11px;
            font-weight: 500;
            cursor: pointer;
            text-align: left;
            transition: all 150ms ease;
            font-family: 'Plus Jakarta Sans', sans-serif;
        }

        .pqm-preset:hover {
            background: rgba(124, 58, 237, .15);
            border-color: rgba(124, 58, 237, .3);
            color: #e5e5e5;
        }

        .pqm-custom {
            display: flex;
            gap: 6px;
        }

        .pqm-input {
            flex: 1;
            padding: 8px 12px;
            border-radius: 8px;
            border: 1px solid rgba(255, 255, 255, .1);
            background: rgba(255, 255, 255, .06);
            color: #e5e5e5;
            font-size: 12px;
            font-family: 'Plus Jakarta Sans', sans-serif;
            outline: none;
            transition: border-color 150ms ease;
        }

        .pqm-input:focus {
            border-color: #7c3aed;
        }

        .pqm-input::placeholder {
            color: #555;
        }

        .pqm-send {
            padding: 8px 12px;
            border-radius: 8px;
            border: 1px solid rgba(124, 58, 237, .3);
            background: rgba(124, 58, 237, .15);
            color: #a78bfa;
            font-size: 14px;
            cursor: pointer;
            transition: all 150ms ease;
        }

        .pqm-send:hover {
            background: rgba(124, 58, 237, .3);
            color: #fff;
        }

        /* ─── Chat Bubbles (incoming messages) ─── */
        .presence-chat-container {
            position: fixed;
            bottom: 80px;
            left: 20px;
            z-index: 9993;
            display: flex;
            flex-direction: column;
            gap: 8px;
            max-width: 340px;
        }

        .presence-chat-bubble {
            background: rgba(14, 14, 20, .68);
            backdrop-filter: blur(24px) saturate(1.6);
            -webkit-backdrop-filter: blur(24px) saturate(1.6);
            border: 1px solid rgba(255, 255, 255, .07);
            border-left: 3px solid var(--bubble-color, #7c3aed);
            border-radius: 16px;
            padding: 14px;
            font-family: 'Plus Jakarta Sans', sans-serif;
            box-shadow: 0 12px 40px rgba(0, 0, 0, .4), inset 0 1px 0 rgba(255, 255, 255, .04);
            transform: translateX(-120%);
            opacity: 0;
            transition: all 350ms cubic-bezier(.34, 1.56, .64, 1);
        }

        .presence-chat-bubble.show {
            transform: translateX(0);
            opacity: 1;
        }

        .pcb-header {
            display: flex;
            align-items: center;
            gap: 8px;
            margin-bottom: 6px;
        }

        .pcb-name {
            font-size: 11px;
            font-weight: 700;
        }

        .pcb-time {
            font-size: 9px;
            color: #666;
            margin-left: auto;
        }

        .pcb-close {
            background: none;
            border: none;
            color: #555;
            cursor: pointer;
            font-size: 12px;
            padding: 2px 4px;
        }

        .pcb-close:hover {
            color: #fff;
        }

        .pcb-text {
            font-size: 13px;
            color: #e5e5e5;
            line-height: 1.5;
            margin-bottom: 8px;
        }

        .pcb-reply {
            display: flex;
            gap: 6px;
        }

        .pcb-reply-input {
            flex: 1;
            padding: 6px 10px;
            border-radius: 6px;
            border: 1px solid rgba(255, 255, 255, .1);
            background: rgba(255, 255, 255, .06);
            color: #e5e5e5;
            font-size: 11px;
            font-family: 'Plus Jakarta Sans', sans-serif;
            outline: none;
        }

        .pcb-reply-input:focus {
            border-color: var(--bubble-color, #7c3aed);
        }

        .pcb-reply-input::placeholder {
            color: #555;
        }

        .pcb-reply-btn {
            padding: 6px 10px;
            border-radius: 6px;
            border: 1px solid rgba(255, 255, 255, .08);
            background: rgba(255, 255, 255, .06);
            color: #a78bfa;
            cursor: pointer;
            font-size: 12px;
            transition: all 150ms ease;
        }

        .pcb-reply-btn:hover {
            background: rgba(124, 58, 237, .2);
            color: #fff;
        }

        /* ─── Floating Reactions ─── */
        .presence-floating-reaction {
            position: fixed;
            bottom: 40%;
            z-index: 9994;
            display: flex;
            flex-direction: column;
            align-items: center;
            pointer-events: none;
            opacity: 0;
            transition: all 2s cubic-bezier(.4, 0, .2, 1);
        }

        .presence-floating-reaction.animate {
            opacity: 1;
            transform: translateY(-200px) scale(1.2);
        }

        .pfr-emoji {
            font-size: 48px;
        }

        .pfr-from {
            font-size: 10px;
            font-weight: 600;
            font-family: 'Plus Jakarta Sans', sans-serif;
            margin-top: 4px;
        }

        /* ─── Action Toast (with button) ─── */
        .presence-toast.action {
            pointer-events: auto;
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .pat-text {
            font-size: 12px;
            color: #eee;
        }

        .pat-btn {
            padding: 5px 12px;
            border-radius: 6px;
            border: 1px solid rgba(255, 255, 255, .15);
            background: rgba(255, 255, 255, .08);
            color: #fff;
            font-size: 11px;
            font-weight: 600;
            cursor: pointer;
            font-family: 'Plus Jakarta Sans', sans-serif;
            transition: all 150ms ease;
            align-self: flex-end;
        }

        .pat-btn:hover {
            background: rgba(255, 255, 255, .15);
            transform: translateY(-1px);
        }

        /* ═══════ v3 TEAM COLLABORATION CSS ═══════ */

        /* ─── Task Assign Form ─── */
        .ptask-form {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .ptask-row {
            display: flex;
            gap: 6px;
        }

        .ptask-select {
            flex: 1;
            padding: 7px 10px;
            border-radius: 8px;
            border: 1px solid rgba(255, 255, 255, .1);
            background: rgba(255, 255, 255, .06);
            color: #ccc;
            font-size: 11px;
            cursor: pointer;
            font-family: 'Plus Jakarta Sans', sans-serif;
            appearance: none;
            outline: none;
        }

        .ptask-select:focus {
            border-color: #7c3aed;
        }

        .ptask-select option {
            background: #1a1a1a;
            color: #ccc;
        }

        .ptask-submit {
            padding: 8px 14px;
            border-radius: 8px;
            border: 1px solid rgba(124, 58, 237, .3);
            background: rgba(124, 58, 237, .15);
            color: #a78bfa;
            font-size: 12px;
            font-weight: 600;
            cursor: pointer;
            font-family: 'Plus Jakarta Sans', sans-serif;
            transition: all 150ms ease;
        }

        .ptask-submit:hover {
            background: rgba(124, 58, 237, .3);
            color: #fff;
        }

        /* ─── Kudos Celebration ─── */
        .presence-kudos-celebration {
            position: fixed;
            inset: 0;
            z-index: 99999;
            display: flex;
            align-items: center;
            justify-content: center;
            background: rgba(0, 0, 0, .6);
            backdrop-filter: blur(8px);
            opacity: 0;
            transition: opacity 400ms ease;
            pointer-events: none;
        }

        .presence-kudos-celebration.show {
            opacity: 1;
        }

        .pkc-content {
            text-align: center;
            animation: kudosBounceIn 600ms cubic-bezier(.68, -.55, .265, 1.55);
        }

        .pkc-emoji {
            font-size: 80px;
            margin-bottom: 12px;
        }

        .pkc-text {
            font-size: 24px;
            font-weight: 800;
            color: #fff;
            font-family: 'Plus Jakarta Sans', sans-serif;
            margin-bottom: 6px;
        }

        .pkc-from {
            font-size: 14px;
            font-weight: 600;
            font-family: 'Plus Jakarta Sans', sans-serif;
        }

        @keyframes kudosBounceIn {
            0% {
                transform: scale(0.3);
                opacity: 0;
            }

            50% {
                transform: scale(1.1);
            }

            100% {
                transform: scale(1);
                opacity: 1;
            }
        }

        /* Confetti */
        .pkc-confetti {
            position: fixed;
            inset: 0;
            pointer-events: none;
            overflow: hidden;
        }

        .pkc-particle {
            position: absolute;
            width: 8px;
            height: 8px;
            background: var(--color);
            left: var(--x);
            top: -10px;
            border-radius: 2px;
            animation: confettiFall 2s var(--delay) ease forwards;
        }

        @keyframes confettiFall {
            0% {
                transform: translateY(0) rotate(0deg);
                opacity: 1;
            }

            100% {
                transform: translateY(100vh) rotate(720deg);
                opacity: 0;
            }
        }

        /* ─── Kudos Grid ─── */
        .pkudos-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 6px;
        }

        .pkudos-btn {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 8px 10px;
            border-radius: 8px;
            border: 1px solid rgba(255, 255, 255, .06);
            background: rgba(255, 255, 255, .04);
            color: #ccc;
            cursor: pointer;
            transition: all 150ms ease;
            font-family: 'Plus Jakarta Sans', sans-serif;
        }

        .pkudos-btn:hover {
            background: rgba(124, 58, 237, .12);
            border-color: rgba(124, 58, 237, .3);
            transform: scale(1.02);
        }

        .pkudos-emoji {
            font-size: 20px;
        }

        .pkudos-label {
            font-size: 11px;
            font-weight: 600;
        }

        /* ─── Kudos button hover ─── */
        .puc-btn-kudos:hover {
            border-color: #eab308;
            color: #fde047;
        }

        /* ─── Pomodoro Widget ─── */
        .presence-pomodoro-widget {
            position: fixed;
            bottom: 20px;
            left: 50%;
            transform: translateX(-50%);
            z-index: 9990;
            display: flex;
            align-items: center;
            gap: 10px;
            padding: 10px 18px;
            background: rgba(20, 20, 20, .95);
            backdrop-filter: blur(12px);
            border: 1px solid rgba(239, 68, 68, .3);
            border-radius: 50px;
            box-shadow: 0 8px 30px rgba(239, 68, 68, .2);
            font-family: 'Plus Jakarta Sans', sans-serif;
            animation: cardSlideIn 200ms ease;
        }

        .ppw-time {
            font-size: 18px;
            font-weight: 800;
            color: #ef4444;
            font-variant-numeric: tabular-nums;
        }

        .ppw-stop {
            width: 28px;
            height: 28px;
            border-radius: 50%;
            border: 1px solid rgba(255, 255, 255, .15);
            background: rgba(255, 255, 255, .08);
            color: #fff;
            font-size: 14px;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            transition: all 150ms ease;
        }

        .ppw-stop:hover {
            background: rgba(239, 68, 68, .3);
            border-color: rgba(239, 68, 68, .5);
        }

        /* ─── Handoff Context ─── */
        .phandoff-context {
            padding: 8px 10px;
            background: rgba(255, 255, 255, .04);
            border: 1px solid rgba(255, 255, 255, .06);
            border-radius: 8px;
            margin-bottom: 4px;
        }

        .phandoff-label {
            font-size: 9px;
            color: #666;
            text-transform: uppercase;
            letter-spacing: 1px;
            margin-bottom: 4px;
        }

        .phandoff-page {
            font-size: 12px;
            color: #ccc;
        }

        /* ─── Sticky Notes ─── */
        .presence-sticky-note {
            position: absolute;
            z-index: 38;
            width: 180px;
            min-height: 80px;
            padding: 12px;
            border-radius: 4px;
            box-shadow: 2px 4px 12px rgba(0, 0, 0, .15);
            cursor: grab;
            transition: box-shadow 200ms ease, transform 200ms ease;
            font-family: 'Plus Jakarta Sans', sans-serif;
        }

        .presence-sticky-note:hover {
            box-shadow: 4px 8px 20px rgba(0, 0, 0, .25);
            transform: rotate(-1deg);
        }

        .presence-sticky-note:active {
            cursor: grabbing;
        }

        .psn-text {
            font-size: 12px;
            color: #333;
            line-height: 1.5;
            word-break: break-word;
        }

        .psn-footer {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 6px;
            padding-top: 6px;
            border-top: 1px solid rgba(0, 0, 0, .1);
        }

        .psn-author {
            font-size: 9px;
            font-weight: 700;
        }

        .psn-delete {
            background: none;
            border: none;
            color: rgba(0, 0, 0, .3);
            cursor: pointer;
            font-size: 14px;
            padding: 2px;
            transition: color 150ms ease;
        }

        .psn-delete:hover {
            color: #ef4444;
        }

        /* Sticky note color picker */
        .psticky-colors {
            display: flex;
            gap: 6px;
            margin: 8px 0;
        }

        .psticky-color {
            width: 24px;
            height: 24px;
            border-radius: 50%;
            border: 2px solid transparent;
            cursor: pointer;
            transition: all 150ms ease;
        }

        .psticky-color:hover {
            transform: scale(1.2);
        }

        .psticky-color.active {
            border-color: #fff;
            box-shadow: 0 0 8px rgba(255, 255, 255, .3);
        }

        /* ─── Mood Check-in ─── */
        .pmood-grid {
            display: flex;
            gap: 6px;
            justify-content: center;
            margin-bottom: 12px;
        }

        .pmood-btn {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 4px;
            padding: 10px 8px;
            border-radius: 10px;
            border: 1px solid rgba(255, 255, 255, .06);
            background: rgba(255, 255, 255, .04);
            cursor: pointer;
            transition: all 150ms ease;
            flex: 1;
            font-family: 'Plus Jakarta Sans', sans-serif;
        }

        .pmood-btn:hover {
            background: rgba(124, 58, 237, .12);
            border-color: rgba(124, 58, 237, .3);
            transform: translateY(-2px);
        }

        .pmood-emoji {
            font-size: 24px;
        }

        .pmood-label {
            font-size: 9px;
            color: #999;
            font-weight: 600;
        }

        .pmood-team {
            padding: 10px;
            background: rgba(255, 255, 255, .04);
            border: 1px solid rgba(255, 255, 255, .06);
            border-radius: 8px;
            font-size: 12px;
            color: #ccc;
        }

        .pmood-summary {
            display: flex;
            gap: 8px;
            align-items: center;
            margin-bottom: 4px;
        }

        .pmood-avatars {
            font-size: 16px;
        }

        /* ─── Availability Schedule ─── */
        .pavail-grid {
            display: grid;
            grid-template-columns: 1fr 1fr 1fr;
            gap: 6px;
            margin-bottom: 10px;
        }

        .pavail-btn {
            padding: 8px 6px;
            border-radius: 8px;
            border: 1px solid rgba(255, 255, 255, .06);
            background: rgba(255, 255, 255, .04);
            color: #ccc;
            font-size: 11px;
            cursor: pointer;
            text-align: center;
            transition: all 150ms ease;
            font-family: 'Plus Jakarta Sans', sans-serif;
        }

        .pavail-btn:hover {
            background: rgba(34, 197, 94, .12);
            border-color: rgba(34, 197, 94, .3);
            color: #e5e5e5;
        }

        .pavail-custom {
            margin-top: 6px;
        }

        /* ─── Screen Annotation Marker ─── */
        .presence-annotation-marker {
            position: absolute;
            z-index: 50;
            pointer-events: none;
            opacity: 0;
            transition: opacity 500ms ease;
        }

        .presence-annotation-marker.show {
            opacity: 1;
        }

        .pam-ring {
            width: 40px;
            height: 40px;
            border: 3px solid var(--anno-color, #7c3aed);
            border-radius: 50%;
            animation: annotationPulse 1.2s infinite;
            margin: -20px 0 0 -20px;
        }

        .pam-label {
            position: absolute;
            top: 24px;
            left: 4px;
            padding: 2px 8px;
            border-radius: 4px;
            color: #fff;
            font-size: 10px;
            font-weight: 700;
            font-family: 'Plus Jakarta Sans', sans-serif;
            white-space: nowrap;
        }

        @keyframes annotationPulse {

            0%,
            100% {
                transform: scale(1);
                opacity: 1;
            }

            50% {
                transform: scale(1.4);
                opacity: .5;
            }
        }
    </style>
</head>

<body class="flex h-screen overflow-hidden bg-slate-50" style="display:none">

    <div id="voice-overlay"
        class="fixed inset-0 z-[9999] opacity-0 invisible transition-all duration-500 flex flex-col items-center justify-center overflow-hidden">
        <div class="absolute inset-0 bg-slate-950/90 backdrop-blur-3xl z-0"></div>
        <div class="relative z-10 flex flex-col items-center justify-center w-full max-w-4xl">
            <div class="relative w-64 h-64 flex items-center justify-center mb-12">
                <div id="voice-orb" class="voice-orb-liquid listening">
                    <div class="liquid-core"></div>
                    <div class="liquid-glow"></div>
                </div>
            </div>
            <div id="voice-transcript" class="min-h-[120px] px-8 text-center">
                <p class="text-3xl text-white font-display">In ascolto...</p>
            </div>
            <button onclick="window.stopVoiceMode()"
                class="mt-8 px-6 py-2 bg-white/10 rounded-full text-white text-sm hover:bg-white/20 transition-all">Chiudi</button>
        </div>
    </div>

    <!-- Archivio Detail Flyout — portaled to body to escape any stacking context -->
    <div id="archivio-detail-overlay" class="cx-flyout-overlay"
        onclick="if(event.target===event.currentTarget) ConservazioneModule.closeDetailPanel()"></div>
    <div id="archivio-detail-panel" class="cx-flyout-panel" style="width:min(520px,calc(100vw - 40px))">
        <div class="cx-flyout-header">
            <div class="cx-flyout-header-content">
                <div class="cx-flyout-tagline" id="detail-tagline">DOCUMENTO</div>
                <h3 class="cx-flyout-title" id="detail-title" style="white-space:normal;overflow:visible">—</h3>
                <div class="cx-flyout-desc" id="detail-description"></div>
            </div>
            <button class="cx-flyout-dismiss" onclick="ConservazioneModule.closeDetailPanel()">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <line x1="18" y1="6" x2="6" y2="18" />
                    <line x1="6" y1="6" x2="18" y2="18" />
                </svg>
            </button>
        </div>
        <div class="cx-flyout-body" id="archivio-detail-content"
            style="flex:1 1 auto;overflow-y:auto;overscroll-behavior:contain;padding:24px"></div>
        <div class="cx-flyout-footer" id="detail-footer"
            style="flex:none;border-top:1px solid #e5e5e5;padding:16px 24px;background:#fafafa;display:flex;align-items:center;gap:8px">
        </div>
    </div>

    <aside id="main-sidebar"
        class="sidebar-solid flex flex-col justify-between h-full relative z-20 hidden md:flex shrink-0">

        <!-- Logo Icon -->
        <div class="flex-1 min-h-0 overflow-hidden flex flex-col">
            <div class="h-16 flex items-center justify-center overflow-hidden"
                style="border-bottom: 1px solid rgba(255,255,255,0.08)">
                <img src="https://firebasestorage.googleapis.com/v0/b/playground-optlyx.firebasestorage.app/o/optlyxAssets%2Flogo%20grad.png?alt=media&token=151c2e9c-8e41-4829-864d-8163239180bd"
                    alt="Optlyx" class="h-8 w-8 object-contain">
            </div>

            <!-- Navigation -->
            <nav class="py-3 overflow-y-auto flex-1" id="main-nav" style="scrollbar-width:none;-ms-overflow-style:none">

                <a href="#" onclick="event.preventDefault(); router.load('dashboard')" class="nav-item active"
                    id="nav-dashboard">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"
                        stroke-linecap="round" stroke-linejoin="round">
                        <rect x="3" y="3" width="7" height="7" rx="1" />
                        <rect x="14" y="3" width="7" height="7" rx="1" />
                        <rect x="3" y="14" width="7" height="7" rx="1" />
                        <rect x="14" y="14" width="7" height="7" rx="1" />
                    </svg>
                    <span class="nav-text">Home</span>
                </a>

                <a href="#" onclick="event.preventDefault(); router.load('inbox')" class="nav-item" id="nav-inbox">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"
                        stroke-linecap="round" stroke-linejoin="round">
                        <path d="M22 12h-6l-2 3H10l-2-3H2" />
                        <path
                            d="M5.45 5.11L2 12v6a2 2 0 002 2h16a2 2 0 002-2v-6l-3.45-6.89A2 2 0 0016.76 4H7.24a2 2 0 00-1.79 1.11z" />
                    </svg>
                    <span class="nav-text">Inbox</span>
                </a>

                <a href="#" onclick="event.preventDefault(); router.load('clients')" class="nav-item" id="nav-clients">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"
                        stroke-linecap="round" stroke-linejoin="round">
                        <path d="M6 22V4a2 2 0 012-2h8a2 2 0 012 2v18Z" />
                        <path d="M6 12H4a2 2 0 00-2 2v6a2 2 0 002 2h2" />
                        <path d="M18 9h2a2 2 0 012 2v9a2 2 0 01-2 2h-2" />
                        <path d="M10 6h4" />
                        <path d="M10 10h4" />
                        <path d="M10 14h4" />
                        <path d="M10 18h4" />
                    </svg>
                    <span class="nav-text">Clienti</span>
                </a>

                <a href="#" onclick="event.preventDefault(); router.load('cortex')" class="nav-item" id="nav-cortex">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"
                        stroke-linecap="round" stroke-linejoin="round">
                        <path d="M14 2H6a2 2 0 00-2 2v16a2 2 0 002 2h12a2 2 0 002-2V8z" />
                        <polyline points="14 2 14 8 20 8" />
                        <line x1="16" y1="13" x2="8" y2="13" />
                        <line x1="16" y1="17" x2="8" y2="17" />
                        <polyline points="10 9 9 9 8 9" />
                    </svg>
                    <span class="nav-text">Documenti</span>
                </a>

                <a href="#" onclick="event.preventDefault(); router.load('fatturazione')" class="nav-item"
                    id="nav-fatturazione">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"
                        stroke-linecap="round" stroke-linejoin="round">
                        <path d="M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1-2-1z" />
                        <path d="M16 8h-6a2 2 0 100 4h4a2 2 0 110 4H8" />
                        <path d="M12 17.5v.5" />
                        <path d="M12 6v.5" />
                    </svg>
                    <span class="nav-text">Autofatture</span>
                </a>


                <!-- Calendar group — hover opens sub-sidebar -->
                <button type="button" class="nav-item" id="nav-flows">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"
                        stroke-linecap="round" stroke-linejoin="round">
                        <rect x="3" y="4" width="18" height="18" rx="2" ry="2" />
                        <line x1="16" y1="2" x2="16" y2="6" />
                        <line x1="8" y1="2" x2="8" y2="6" />
                        <line x1="3" y1="10" x2="21" y2="10" />
                        <circle cx="12" cy="16" r="1" />
                    </svg>
                    <span class="nav-text">Scadenze</span>
                </button>
                <div id="nav-appointments" style="display:none;height:0;margin:0;padding:0;overflow:hidden"
                    aria-hidden="true"></div>

                <div id="nav-presenze" style="display:none;height:0;margin:0;padding:0;overflow:hidden"
                    aria-hidden="true"></div>

                <a href="#" onclick="event.preventDefault(); router.load('team-chat')" class="nav-item"
                    id="nav-team-chat">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"
                        stroke-linecap="round" stroke-linejoin="round">
                        <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z" />
                    </svg>
                    <span class="nav-text">Team Chat</span>
                </a>

                <a href="#" onclick="event.preventDefault(); router.load('console')" class="nav-item" id="nav-console">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"
                        stroke-linecap="round" stroke-linejoin="round">
                        <path d="M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z" />
                        <path d="M19 3v4" />
                        <path d="M21 5h-4" />
                    </svg>
                    <span class="nav-text">Console AI</span>
                </a>

                <a href="#" onclick="event.preventDefault(); router.load('cortex'); setTimeout(() => window.CortexCore && CortexCore.switchTab('integrita'), 200);" class="nav-item"
                    id="nav-integrity">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"
                        stroke-linecap="round" stroke-linejoin="round">
                        <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />
                        <path d="M9 12l2 2 4-4" />
                    </svg>
                    <span class="nav-text">Integrità</span>
                </a>

                <a href="#" onclick="event.preventDefault(); router.load('academy')" class="nav-item" id="nav-academy">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"
                        stroke-linecap="round" stroke-linejoin="round">
                        <path d="M22 10v6M2 10l10-5 10 5-10 5z" />
                        <path d="M6 12v5c3 3 9 3 12 0v-5" />
                    </svg>
                    <span class="nav-text">Academy</span>
                </a>

                <a href="#" onclick="event.preventDefault(); router.load('settings')" class="nav-item"
                    id="nav-settings">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"
                        stroke-linecap="round" stroke-linejoin="round">
                        <circle cx="12" cy="12" r="3" />
                        <path
                            d="M19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 010 2.83 2 2 0 01-2.83 0l-.06-.06a1.65 1.65 0 00-1.82-.33 1.65 1.65 0 00-1 1.51V21a2 2 0 01-2 2 2 2 0 01-2-2v-.09A1.65 1.65 0 009 19.4a1.65 1.65 0 00-1.82.33l-.06.06a2 2 0 01-2.83 0 2 2 0 010-2.83l.06-.06A1.65 1.65 0 004.68 15a1.65 1.65 0 00-1.51-1H3a2 2 0 01-2-2 2 2 0 012-2h.09A1.65 1.65 0 004.6 9a1.65 1.65 0 00-.33-1.82l-.06-.06a2 2 0 010-2.83 2 2 0 012.83 0l.06.06A1.65 1.65 0 009 4.68a1.65 1.65 0 001-1.51V3a2 2 0 012-2 2 2 0 012 2v.09a1.65 1.65 0 001 1.51 1.65 1.65 0 001.82-.33l.06-.06a2 2 0 012.83 0 2 2 0 010 2.83l-.06.06A1.65 1.65 0 0019.4 9a1.65 1.65 0 001.51 1H21a2 2 0 012 2 2 2 0 01-2 2h-.09a1.65 1.65 0 00-1.51 1z" />
                    </svg>
                    <span class="nav-text">Settings</span>
                </a>

                <a href="#" onclick="event.preventDefault(); router.load('team-permissions')" class="nav-item"
                    id="nav-team-permissions">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"
                        stroke-linecap="round" stroke-linejoin="round">
                        <path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z" />
                    </svg>
                    <span class="nav-text">Permessi</span>
                </a>

                <!-- Platform Admin — solo superAdmin, nascosto di default -->
                <a href="#" onclick="event.preventDefault(); router.load('admin-panel')" class="nav-item"
                    id="nav-admin-panel" style="display:none;">
                    <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"
                        stroke-linecap="round" stroke-linejoin="round">
                        <circle cx="12" cy="12" r="3" />
                        <path
                            d="M12 1v4M12 19v4M4.22 4.22l2.83 2.83M16.95 16.95l2.83 2.83M1 12h4M19 12h4M4.22 19.78l2.83-2.83M16.95 7.05l2.83-2.83" />
                    </svg>
                    <span class="nav-text">Admin</span>
                </a>

            </nav>
        </div>

        <!-- Bottom: Help + User Avatar -->
        <div class="py-3 flex flex-col items-center shrink-0" style="border-top: 1px solid rgba(255,255,255,0.08);">
            <button onclick="if(window.router)window.router.load('onboarding')" title="Mostra setup guidato"
                class="w-8 h-8 rounded-lg flex items-center justify-center transition-colors mb-2"
                style="background: rgba(255,255,255,0.08); color: rgba(255,255,255,0.4);"
                onmouseover="this.style.background='rgba(255,255,255,0.15)';this.style.color='rgba(255,255,255,0.7)'"
                onmouseout="this.style.background='rgba(255,255,255,0.08)';this.style.color='rgba(255,255,255,0.4)'">
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"
                    stroke-linecap="round" stroke-linejoin="round">
                    <circle cx="12" cy="12" r="10" />
                    <path d="M9.09 9a3 3 0 015.83 1c0 2-3 3-3 3" />
                    <line x1="12" y1="17" x2="12.01" y2="17" />
                </svg>
            </button>
            <div class="relative cursor-pointer" onclick="toggleUserMenu()">
                <div class="w-9 h-9 rounded-full bg-white/15 text-white flex items-center justify-center font-bold text-xs"
                    id="sidebar-user-avatar">...</div>
                <div
                    class="absolute -bottom-0.5 -right-0.5 w-2.5 h-2.5 bg-emerald-500 rounded-full border-2 border-black">
                </div>
            </div>

            <!-- User Dropdown Menu (opens ABOVE) -->
            <div id="user-dropdown-menu"
                class="hidden fixed w-48 bg-white rounded-xl border border-gray-200 shadow-lg overflow-hidden z-[9999]">
                <button onclick="router.load('settings')"
                    class="w-full flex items-center gap-3 px-4 py-2.5 text-left hover:bg-gray-50 transition-colors">
                    <i data-lucide="user" class="w-4 h-4 text-gray-400"></i>
                    <span class="text-sm font-medium text-gray-700">Profilo</span>
                </button>
                <button onclick="setUserStatus('away')"
                    class="w-full flex items-center gap-3 px-4 py-2.5 text-left hover:bg-gray-50 transition-colors border-t border-gray-100">
                    <i data-lucide="moon" class="w-4 h-4 text-gray-400"></i>
                    <span class="text-sm font-medium text-gray-700">Assente</span>
                </button>
                <button onclick="window._secureLogout()"
                    class="w-full flex items-center gap-3 px-4 py-2.5 text-left hover:bg-red-50 transition-colors border-t border-gray-100 text-red-500">
                    <i data-lucide="log-out" class="w-4 h-4"></i>
                    <span class="text-sm font-medium">Esci</span>
                </button>
            </div>
        </div>
    </aside>


    <div id="cal-subnav" class="cal-subnav-panel" aria-hidden="true" role="navigation"
        aria-label="Scadenziario e Prenotazioni">

        <!-- Header -->
        <div class="cal-subnav-header">
            <svg class="cal-subnav-header-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5"
                stroke-linecap="round" stroke-linejoin="round">
                <rect x="3" y="4" width="18" height="18" rx="2" />
                <line x1="16" y1="2" x2="16" y2="6" />
                <line x1="8" y1="2" x2="8" y2="6" />
                <line x1="3" y1="10" x2="21" y2="10" />
            </svg>
            <span class="cal-subnav-header-title">Scadenze</span>
        </div>

        <!-- Section: Scadenziario -->
        <div class="cal-subnav-section">
            <div class="cal-subnav-section-title">Scadenziario</div>
            <button type="button" class="cal-subnav-item" data-view="timeline"
                onclick="CalSubnav.navigateView('flows','timeline')">Timeline</button>
            <button type="button" class="cal-subnav-item" data-view="calendar"
                onclick="CalSubnav.navigateView('flows','calendar')">Calendario</button>
            <button type="button" class="cal-subnav-item" data-view="kanban"
                onclick="CalSubnav.navigateView('flows','kanban')">Kanban</button>
            <button type="button" class="cal-subnav-item" data-view="table"
                onclick="CalSubnav.navigateView('flows','table')">Tabella</button>
            <button type="button" class="cal-subnav-item" data-view="team"
                onclick="CalSubnav.navigateView('flows','team')">Team</button>
        </div>

        <!-- Section: Prenotazioni -->
        <div class="cal-subnav-section">
            <div class="cal-subnav-section-title">Prenotazioni</div>
            <button type="button" class="cal-subnav-item" data-target="calendar"
                onclick="CalSubnav.navigate('appointments')">Calendario</button>
            <button type="button" class="cal-subnav-item" data-target="links"
                onclick="CalSubnav.navigate('appointments')">Link prenotazione</button>
        </div>

    </div>
    <div id="cal-subnav-backdrop" class="cal-subnav-backdrop" onclick="CalSubnav.close()"></div>

    <main class="flex-1 min-w-0 flex flex-col h-screen relative bg-slate-50/50 overflow-hidden">
        <div id="main-scroll-area" class="flex-1 overflow-y-auto h-full scroll-smooth">

            <header class="sticky top-0 z-50 w-full h-16 px-4 flex items-center justify-between
                        bg-[#0a0a0a] transition-all duration-200"
                style="font-family: 'Plus Jakarta Sans', -apple-system, BlinkMacSystemFont, 'Segoe UI', system-ui, sans-serif; border-bottom: 1px solid rgba(255,255,255,0.08);">

                <!-- LEFT: Sidebar Toggle + Breadcrumb -->
                <div class="flex items-center gap-2.5 shrink-0 min-w-0">
                    <button id="sidebar-toggle-btn" type="button"
                        class="w-8 h-8 flex items-center justify-center text-[#666] hover:text-[#ededed] rounded-md hover:bg-[#1a1a1a] transition-all duration-150">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                            stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
                            <rect x="3" y="3" width="18" height="18" rx="2" />
                            <line x1="9" y1="3" x2="9" y2="21" />
                        </svg>
                    </button>
                    <div class="flex items-center gap-2 min-w-0">
                        <span class="text-[13px] text-[#555] font-medium hidden sm:inline">Prisma</span>
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#333" stroke-width="1.5"
                            class="shrink-0 hidden sm:block">
                            <path d="m9 18 6-6-6-6" />
                        </svg>
                        <h2 id="header-title" class="text-[13px] text-[#ededed] font-medium truncate">Dashboard</h2>
                    </div>
                </div>

                <!-- CENTER: Search -->
                <div class="hidden md:flex flex-1 max-w-[480px] mx-6">
                    <button onclick="GlobalSearch.open()" type="button"
                        class="w-full h-8 pl-3 pr-3 bg-[#111] border border-[#2a2a2a] hover:border-[#444] rounded-md text-[13px] text-[#555] text-left outline-none transition-all duration-150 cursor-pointer flex items-center gap-2.5">
                        <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="#555" stroke-width="2"
                            stroke-linecap="round" stroke-linejoin="round">
                            <circle cx="11" cy="11" r="8" />
                            <path d="m21 21-4.3-4.3" />
                        </svg>
                        <span>Cerca clienti, documenti, fatture...</span>
                        <span
                            class="ml-auto text-[11px] text-[#444] bg-[#1a1a1a] border border-[#2a2a2a] px-1.5 py-px rounded font-mono">⌘K</span>
                    </button>
                </div>

                <!-- GLOBAL STICKY NOTES - Inline in header -->
                <div id="global-sticky-notes" class="flex items-center gap-2">
                    <div id="pinned-sticky-notes" class="flex items-start gap-2"></div>
                    <button onclick="toggleMoreStickyNotes()" id="more-sticky-btn"
                        class="hidden relative flex items-center gap-1.5 px-2.5 py-1.5 bg-white/6 hover:bg-white/10 border border-white/8 rounded-lg text-white/50 hover:text-white/80 font-bold text-[10px] transition-all"
                        title="Altri promemoria">
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                            stroke-width="1.5">
                            <path d="M12 2L2 7l10 5 10-5-10-5z" />
                            <path d="M2 17l10 5 10-5" />
                            <path d="M2 12l10 5 10-5" />
                        </svg>
                        <span>Altri</span>
                        <span id="more-sticky-count" class="px-1.5 py-0.5 bg-white/10 rounded-full text-[9px]">+0</span>
                        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                            stroke-width="2" id="more-sticky-chevron" class="transition-transform">
                            <path d="m6 9 6 6 6-6" />
                        </svg>
                    </button>
                    <div id="hidden-sticky-notes-panel" class="absolute top-full right-0 mt-2 w-72 max-h-[300px] overflow-hidden rounded-lg 
                               bg-[#0a0a0a] border border-[#333] shadow-2xl shadow-black/50
                               hidden opacity-0 transform -translate-y-2 transition-all duration-300 z-[100]">
                        <div class="px-3 py-2 border-b border-[#1a1a1a]">
                            <span class="text-[11px] font-medium text-[#666]">📌 Promemoria</span>
                        </div>
                        <div id="hidden-sticky-notes-list"
                            class="max-h-[240px] overflow-y-auto p-2 space-y-2 custom-scrollbar"></div>
                    </div>
                </div>

                <style>
                    /* Glassy Static Post-it Notes */
                    #global-sticky-notes {
                        pointer-events: auto;
                    }

                    .pinned-note {
                        position: relative;
                        min-width: 140px;
                        max-width: 180px;
                        padding: 10px 12px;
                        border-radius: 8px;
                        font-size: 11px;
                        font-weight: 500;
                        line-height: 1.4;
                        cursor: pointer;
                        /* Glassy effect */
                        background: rgba(255, 255, 255, 0.85);
                        backdrop-filter: blur(12px);
                        -webkit-backdrop-filter: blur(12px);
                        border: 1px solid rgba(255, 255, 255, 0.5);
                        box-shadow:
                            0 4px 16px rgba(0, 0, 0, 0.08),
                            0 1px 4px rgba(0, 0, 0, 0.05),
                            inset 0 1px 0 rgba(255, 255, 255, 0.8);
                        /* Parchment fold animation */
                        transform-origin: top center;
                        transition: all 0.35s cubic-bezier(0.4, 0, 0.2, 1);
                    }

                    /* Folded state (default) - rolled up like parchment */
                    .pinned-note.folded {
                        max-height: 28px;
                        padding: 6px 12px;
                        overflow: hidden;
                        transform: perspective(500px) rotateX(-15deg);
                        box-shadow:
                            0 2px 8px rgba(0, 0, 0, 0.06),
                            0 1px 2px rgba(0, 0, 0, 0.04);
                    }

                    .pinned-note.folded .note-text {
                        white-space: nowrap;
                        overflow: hidden;
                        text-overflow: ellipsis;
                    }

                    /* Unfolded state - full parchment */
                    .pinned-note:not(.folded) {
                        transform: perspective(500px) rotateX(0deg);
                    }

                    .pinned-note:not(.folded) .note-text {
                        white-space: normal;
                        word-wrap: break-word;
                    }

                    .pinned-note:hover {
                        box-shadow:
                            0 8px 24px rgba(0, 0, 0, 0.12),
                            0 2px 8px rgba(0, 0, 0, 0.06),
                            inset 0 1px 0 rgba(255, 255, 255, 0.9);
                    }

                    .pinned-note .note-close {
                        position: absolute;
                        top: 4px;
                        right: 4px;
                        width: 16px;
                        height: 16px;
                        background: rgba(0, 0, 0, 0.08);
                        border: none;
                        border-radius: 50%;
                        color: rgba(0, 0, 0, 0.4);
                        font-size: 11px;
                        cursor: pointer;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        opacity: 0;
                        transition: all 0.2s;
                    }

                    .pinned-note:hover .note-close {
                        opacity: 1;
                    }

                    .pinned-note .note-close:hover {
                        background: #ef4444;
                        color: white;
                    }

                    /* Color accents - subtle left border */
                    .pinned-note.yellow {
                        border-left: 3px solid #fbbf24;
                        background: rgba(254, 249, 195, 0.9);
                    }

                    .pinned-note.pink {
                        border-left: 3px solid #f472b6;
                        background: rgba(252, 231, 243, 0.9);
                    }

                    .pinned-note.blue {
                        border-left: 3px solid #60a5fa;
                        background: rgba(219, 234, 254, 0.9);
                    }

                    .pinned-note.green {
                        border-left: 3px solid #4ade80;
                        background: rgba(220, 252, 231, 0.9);
                    }

                    .pinned-note.orange {
                        border-left: 3px solid #fb923c;
                        background: rgba(255, 237, 213, 0.9);
                    }

                    /* Fold indicator shadow at bottom */
                    .pinned-note::after {
                        content: '';
                        position: absolute;
                        bottom: 0;
                        left: 0;
                        right: 0;
                        height: 12px;
                        background: linear-gradient(to top, rgba(0, 0, 0, 0.03), transparent);
                        opacity: 0;
                        transition: opacity 0.2s;
                        pointer-events: none;
                    }

                    .pinned-note.folded::after {
                        opacity: 1;
                    }

                    /* Urgent indicator */
                    .pinned-note.urgent {
                        border-left: 3px solid #ef4444;
                        animation: urgent-glow 2s ease-in-out infinite;
                    }

                    @keyframes urgent-glow {

                        0%,
                        100% {
                            box-shadow: 0 4px 16px rgba(239, 68, 68, 0.15);
                        }

                        50% {
                            box-shadow: 0 4px 20px rgba(239, 68, 68, 0.3);
                        }
                    }
                </style>

                <!-- RIGHT: Actions -->
                <div class="flex items-center gap-1.5 shrink-0">

                    <!-- New Button — labeled, prominent -->
                    <div class="relative" id="quick-actions-wrapper">
                        <button onclick="toggleQuickActions()" id="btn-quick-actions"
                            class="h-8 px-3 flex items-center gap-1.5 rounded-md bg-[#ededed] hover:bg-white text-[#0a0a0a] text-[13px] font-medium transition-all duration-150"
                            title="Crea nuovo (⌘N)">
                            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                                stroke-width="2.5" stroke-linecap="round">
                                <line x1="12" y1="5" x2="12" y2="19" />
                                <line x1="5" y1="12" x2="19" y2="12" />
                            </svg>
                            <span class="hidden sm:inline">Nuovo</span>
                        </button>

                        <!-- Quick Actions Dropdown -->
                        <div id="quick-actions-dropdown"
                            class="absolute top-full right-0 mt-2 w-[240px] bg-[#0a0a0a] border border-[#333] rounded-lg shadow-2xl shadow-black/50 hidden opacity-0 transform -translate-y-2 transition-all duration-200 z-50 overflow-hidden">
                            <div class="px-3 py-2 border-b border-[#1a1a1a]">
                                <span class="text-[11px] font-medium text-[#666]">Crea nuovo</span>
                            </div>
                            <div class="py-1">
                                <button onclick="router.load('clients'); toggleQuickActions();"
                                    class="w-full flex items-center gap-3 px-3 py-2 text-left hover:bg-[#1a1a1a] transition-colors group">
                                    <div
                                        class="w-7 h-7 rounded-md bg-[#1a1a1a] border border-[#333] flex items-center justify-center group-hover:border-[#0ea5e9]/40">
                                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#0ea5e9"
                                            stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
                                            <path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2" />
                                            <circle cx="9" cy="7" r="4" />
                                            <line x1="19" y1="8" x2="19" y2="14" />
                                            <line x1="22" y1="11" x2="16" y2="11" />
                                        </svg>
                                    </div>
                                    <div class="flex flex-col">
                                        <span class="text-[13px] font-medium text-[#ededed]">Nuovo Cliente</span>
                                        <span class="text-[11px] text-[#555]">Aggiungi anagrafica</span>
                                    </div>
                                </button>
                                <button onclick="router.load('fatturazione'); toggleQuickActions();"
                                    class="w-full flex items-center gap-3 px-3 py-2 text-left hover:bg-[#1a1a1a] transition-colors group">
                                    <div
                                        class="w-7 h-7 rounded-md bg-[#1a1a1a] border border-[#333] flex items-center justify-center group-hover:border-[#10b981]/40">
                                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#10b981"
                                            stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
                                            <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8Z" />
                                            <path d="M14 2v6h6" />
                                            <path d="M16 13H8" />
                                            <path d="M16 17H8" />
                                            <path d="M10 9H8" />
                                        </svg>
                                    </div>
                                    <div class="flex flex-col">
                                        <span class="text-[13px] font-medium text-[#ededed]">Nuova Autofattura</span>
                                        <span class="text-[11px] text-[#555]">Avvia workflow TD17/18/19</span>
                                    </div>
                                </button>
                                <button onclick="router.load('inbox'); toggleQuickActions();"
                                    class="w-full flex items-center gap-3 px-3 py-2 text-left hover:bg-[#1a1a1a] transition-colors group">
                                    <div
                                        class="w-7 h-7 rounded-md bg-[#1a1a1a] border border-[#333] flex items-center justify-center group-hover:border-[#8b5cf6]/40">
                                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#8b5cf6"
                                            stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
                                            <rect width="20" height="16" x="2" y="4" rx="2" />
                                            <path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7" />
                                        </svg>
                                    </div>
                                    <div class="flex flex-col">
                                        <span class="text-[13px] font-medium text-[#ededed]">Scrivi Email</span>
                                        <span class="text-[11px] text-[#555]">Componi messaggio</span>
                                    </div>
                                </button>
                                <button
                                    onclick="window.open('scan.html', 'ScannerAI', 'width=500,height=900'); toggleQuickActions();"
                                    class="w-full flex items-center gap-3 px-3 py-2 text-left hover:bg-[#1a1a1a] transition-colors group">
                                    <div
                                        class="w-7 h-7 rounded-md bg-[#1a1a1a] border border-[#333] flex items-center justify-center group-hover:border-[#f59e0b]/40">
                                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="#f59e0b"
                                            stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
                                            <path d="M3 7V5a2 2 0 0 1 2-2h2" />
                                            <path d="M17 3h2a2 2 0 0 1 2 2v2" />
                                            <path d="M21 17v2a2 2 0 0 1-2 2h-2" />
                                            <path d="M7 21H5a2 2 0 0 1-2-2v-2" />
                                            <line x1="7" y1="12" x2="17" y2="12" />
                                        </svg>
                                    </div>
                                    <div class="flex flex-col">
                                        <span class="text-[13px] font-medium text-[#ededed]">Scanner AI</span>
                                        <span class="text-[11px] text-[#555]">Analizza documento</span>
                                    </div>
                                </button>
                            </div>
                        </div>
                    </div>

                    <div class="w-px h-4 bg-[#222]"></div>

                    <!-- Inbox — shows unread count -->
                    <button onclick="router.load('inbox')"
                        class="h-8 px-2.5 flex items-center gap-2 rounded-md text-[#888] hover:text-[#ededed] hover:bg-[#1a1a1a] transition-all duration-150"
                        title="Vai alla Inbox">
                        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                            stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
                            <rect width="20" height="16" x="2" y="4" rx="2" />
                            <path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7" />
                        </svg>
                        <span id="header-inbox-count" class="text-[11px] font-medium tabular-nums hidden">0</span>
                    </button>

                    <!-- Calendar -->
                    <div class="relative" id="calendar-wrapper">
                        <button onclick="toggleCalendarDropdown()" id="btn-calendar"
                            class="w-8 h-8 flex items-center justify-center rounded-md text-[#888] hover:text-[#ededed] hover:bg-[#1a1a1a] transition-all duration-150"
                            title="Scadenzario">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                                stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
                                <rect width="18" height="18" x="3" y="4" rx="2" />
                                <line x1="16" x2="16" y1="2" y2="6" />
                                <line x1="8" x2="8" y1="2" y2="6" />
                                <line x1="3" x2="21" y1="10" y2="10" />
                            </svg>
                        </button>

                        <!-- Calendar Dropdown Panel -->
                        <div id="calendar-dropdown"
                            class="absolute top-full right-0 mt-2 w-[340px] bg-[#0a0a0a] border border-[#333] rounded-lg shadow-2xl shadow-black/50 hidden opacity-0 transform -translate-y-2 transition-all duration-200 z-50 overflow-hidden">
                            <div class="px-4 py-3 border-b border-[#1a1a1a] flex items-center justify-between">
                                <button onclick="calendarNav(-1)"
                                    class="w-7 h-7 flex items-center justify-center rounded-md hover:bg-[#1a1a1a] text-[#666] hover:text-[#ededed] transition-all">
                                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                                        stroke-width="2">
                                        <path d="m15 18-6-6 6-6" />
                                    </svg>
                                </button>
                                <span id="calendar-month-label"
                                    class="text-[13px] font-semibold text-[#ededed]">--</span>
                                <button onclick="calendarNav(1)"
                                    class="w-7 h-7 flex items-center justify-center rounded-md hover:bg-[#1a1a1a] text-[#666] hover:text-[#ededed] transition-all">
                                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                                        stroke-width="2">
                                        <path d="m9 18 6-6-6-6" />
                                    </svg>
                                </button>
                            </div>
                            <div class="px-3 pt-2 pb-1">
                                <div class="grid grid-cols-7 gap-0 text-center mb-1">
                                    <span class="text-[10px] font-medium text-[#555] py-1">Lu</span>
                                    <span class="text-[10px] font-medium text-[#555] py-1">Ma</span>
                                    <span class="text-[10px] font-medium text-[#555] py-1">Me</span>
                                    <span class="text-[10px] font-medium text-[#555] py-1">Gi</span>
                                    <span class="text-[10px] font-medium text-[#555] py-1">Ve</span>
                                    <span class="text-[10px] font-medium text-[#555] py-1">Sa</span>
                                    <span class="text-[10px] font-medium text-[#555] py-1">Do</span>
                                </div>
                                <div id="calendar-grid" class="grid grid-cols-7 gap-0 text-center"></div>
                            </div>
                            <div class="border-t border-[#1a1a1a] px-3 py-2">
                                <div class="flex items-center justify-between mb-2">
                                    <span class="text-[11px] font-medium text-[#666]">Attività del giorno</span>
                                    <span id="calendar-selected-date"
                                        class="text-[11px] font-mono text-[#555]">--</span>
                                </div>
                                <div id="calendar-tasks-list"
                                    class="space-y-1.5 max-h-[180px] overflow-y-auto custom-scrollbar">
                                    <div class="text-center py-3">
                                        <span class="text-[11px] text-[#444]">Seleziona un giorno</span>
                                    </div>
                                </div>
                            </div>
                            <div class="px-3 py-2 border-t border-[#1a1a1a]">
                                <button onclick="router.load('flows'); toggleCalendarDropdown();"
                                    class="w-full flex items-center gap-2 justify-center text-[11px] font-medium text-[#888] hover:text-[#ededed] transition-colors py-0.5">
                                    Apri Scadenzario →
                                </button>
                            </div>
                        </div>
                    </div>

                    <div class="w-px h-4 bg-[#222]"></div>

                    <!-- Notifications -->
                    <div class="relative" id="notification-wrapper">
                        <button id="btn-notifications"
                            class="relative w-8 h-8 flex items-center justify-center rounded-md text-[#888] hover:text-[#ededed] hover:bg-[#1a1a1a] transition-all duration-150">
                            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                                stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
                                <path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9" />
                                <path d="M10.3 21a1.94 1.94 0 0 0 3.4 0" />
                            </svg>
                            <span id="notification-badge"
                                class="absolute top-0.5 right-0.5 min-w-[14px] h-3.5 px-1 bg-red-500 text-[8px] font-bold text-white rounded-full hidden flex items-center justify-center">0</span>
                        </button>

                        <!-- Notification Dropdown -->
                        <div id="notification-dropdown"
                            class="absolute top-full right-0 mt-2 w-80 bg-[#0a0a0a] border border-[#333] rounded-lg shadow-2xl shadow-black/50 hidden opacity-0 transform -translate-y-2 transition-all duration-200 z-50 overflow-hidden">
                            <div class="px-4 py-3 border-b border-[#1a1a1a]">
                                <div class="flex items-center justify-between">
                                    <h3 class="font-semibold text-[#ededed] text-[13px]">Notifiche</h3>
                                    <button onclick="StudioNotificationManager.markAllAsRead()"
                                        class="text-[10px] font-medium text-[#888] hover:text-[#ededed] bg-[#1a1a1a] border border-[#333] hover:border-[#555] px-2 py-0.5 rounded-md transition-all duration-150">
                                        Segna tutte lette
                                    </button>
                                </div>
                            </div>
                            <div class="max-h-72 overflow-y-auto custom-scrollbar" id="notifications-list">
                                <div class="p-6 text-center">
                                    <div
                                        class="w-10 h-10 mx-auto mb-2 bg-[#1a1a1a] border border-[#333] rounded-full flex items-center justify-center">
                                        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#555"
                                            stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
                                            <path d="M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9" />
                                            <path d="M10.3 21a1.94 1.94 0 0 0 3.4 0" />
                                        </svg>
                                    </div>
                                    <p class="text-[13px] font-medium text-[#888]">Nessuna notifica</p>
                                    <p class="text-[11px] text-[#555] mt-0.5">Le notifiche appariranno qui</p>
                                </div>
                            </div>
                            <div class="px-4 py-2 border-t border-[#1a1a1a] text-center">
                                <button onclick="router.load('settings')"
                                    class="text-[11px] font-medium text-[#888] hover:text-[#ededed] transition-colors">
                                    Impostazioni notifiche →
                                </button>
                            </div>
                        </div>
                    </div>

                </div>
            </header>

            <div id="app-content" class="flex-1 p-6 pb-0 max-w-[1920px] mx-auto flex flex-col relative overflow-hidden">
                <div class="jarvis-loader-wrapper animate-fade-in h-full flex-1 min-h-[60vh]">
                    <div class="optlyx-loader-container">
                        <div class="optlyx-loader-ring"></div>
                        <div class="optlyx-loader-particles orbit-inner">
                            <span></span><span></span><span></span><span></span></div>
                        <div class="optlyx-loader-particles orbit-mid">
                            <span></span><span></span><span></span><span></span><span></span><span></span></div>
                        <div class="optlyx-loader-particles orbit-outer">
                            <span></span><span></span><span></span><span></span><span></span><span></span><span></span><span></span>
                        </div>
                        <div class="optlyx-loader-logo">
                            <img src="https://firebasestorage.googleapis.com/v0/b/playground-optlyx.firebasestorage.app/o/optlyxAssets%2Flogo%20grad.png?alt=media&token=151c2e9c-8e41-4829-864d-8163239180bd"
                                alt="Optlyx">
                        </div>
                    </div>
                    <!-- Icon carousel — accountant icons cycling below the logo -->
                    <div class="loader-icon-carousel">
                        <!-- Fattura elettronica -->
                        <div class="loader-icon-item" style="animation-delay:0s">
                            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24"
                                fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"
                                stroke-linejoin="round">
                                <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" />
                                <polyline points="14 2 14 8 20 8" />
                                <line x1="16" y1="13" x2="8" y2="13" />
                                <line x1="16" y1="17" x2="8" y2="17" />
                                <polyline points="10 9 9 9 8 9" />
                            </svg>
                            <span>Fattura elettronica</span>
                        </div>
                        <!-- Bilancio -->
                        <div class="loader-icon-item" style="animation-delay:1.5s">
                            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24"
                                fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"
                                stroke-linejoin="round">
                                <line x1="18" y1="20" x2="18" y2="10" />
                                <line x1="12" y1="20" x2="12" y2="4" />
                                <line x1="6" y1="20" x2="6" y2="14" />
                                <line x1="2" y1="20" x2="22" y2="20" />
                            </svg>
                            <span>Bilancio</span>
                        </div>
                        <!-- Scadenzario -->
                        <div class="loader-icon-item" style="animation-delay:3s">
                            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24"
                                fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"
                                stroke-linejoin="round">
                                <rect x="3" y="4" width="18" height="18" rx="2" ry="2" />
                                <line x1="16" y1="2" x2="16" y2="6" />
                                <line x1="8" y1="2" x2="8" y2="6" />
                                <line x1="3" y1="10" x2="21" y2="10" />
                            </svg>
                            <span>Scadenzario</span>
                        </div>
                        <!-- Calcolo IVA -->
                        <div class="loader-icon-item" style="animation-delay:4.5s">
                            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24"
                                fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"
                                stroke-linejoin="round">
                                <rect x="4" y="2" width="16" height="20" rx="2" />
                                <line x1="8" y1="6" x2="16" y2="6" />
                                <line x1="16" y1="10" x2="16" y2="10" />
                                <line x1="12" y1="10" x2="12" y2="10" />
                                <line x1="8" y1="10" x2="8" y2="10" />
                                <line x1="16" y1="14" x2="16" y2="14" />
                                <line x1="12" y1="14" x2="12" y2="14" />
                                <line x1="8" y1="14" x2="8" y2="14" />
                                <line x1="16" y1="18" x2="12" y2="18" />
                                <line x1="8" y1="18" x2="8" y2="18" />
                            </svg>
                            <span>Calcolo IVA</span>
                        </div>
                        <!-- Clienti -->
                        <div class="loader-icon-item" style="animation-delay:6s">
                            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24"
                                fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"
                                stroke-linejoin="round">
                                <rect x="2" y="7" width="20" height="14" rx="2" ry="2" />
                                <path d="M16 21V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16" />
                            </svg>
                            <span>Gestione clienti</span>
                        </div>
                        <!-- Revisione contabile -->
                        <div class="loader-icon-item" style="animation-delay:7.5s">
                            <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24"
                                fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"
                                stroke-linejoin="round">
                                <line x1="12" y1="3" x2="12" y2="21" />
                                <path d="M3 9l3-6 3 6" />
                                <path d="M15 9l3-6 3 6" />
                                <path d="M3 9c0 2.2 1.3 4 3 4s3-1.8 3-4" />
                                <path d="M15 9c0 2.2 1.3 4 3 4s3-1.8 3-4" />
                                <line x1="7" y1="21" x2="17" y2="21" />
                            </svg>
                            <span>Revisione contabile</span>
                        </div>
                    </div>
                    <div class="jarvis-text">
                        <span class="loader-title">Inizializzazione Sistema</span>
                        <span class="loader-sub">Avvio servizi neurali...</span>
                    </div>
                </div>
            </div>

        </div>

        <!-- Tab Switch Loading Overlay -->
        <div id="page-loader-overlay" class="google-spinner-overlay">
            <div class="prisma-launch-screen">
                <img class="prisma-launch-logo"
                    src="https://firebasestorage.googleapis.com/v0/b/playground-optlyx.firebasestorage.app/o/optlyxAssets%2FLOGO%20B%201.png?alt=media&token=1195fe2a-d4b5-4eef-ad82-fb164e78c94e"
                    alt="Optlyx">
                <div class="prisma-launch-scanner"></div>
                <div class="prisma-launch-ticker">
                    <span class="prisma-tick-item" style="animation-delay:0s">Caricamento moduli</span>
                    <span class="prisma-tick-item" style="animation-delay:1.8s">Sincronizzazione clienti</span>
                    <span class="prisma-tick-item" style="animation-delay:3.6s">Recupero scadenze</span>
                    <span class="prisma-tick-item" style="animation-delay:5.4s">Analisi bilancio</span>
                    <span class="prisma-tick-item" style="animation-delay:7.2s">Verifica dichiarazioni</span>
                </div>
            </div>
        </div>


    </main>

    <div id="clientModal"
        class="fixed inset-0 bg-slate-900/60 backdrop-blur-md z-[100] hidden flex items-center justify-center p-4 transition-opacity duration-300 opacity-0">
    </div>

    <div id="account-picker-overlay"
        class="fixed inset-0 z-[110] bg-slate-900/60 backdrop-blur-md flex items-center justify-center p-4 transition-opacity duration-300 opacity-0 hidden">
        <div class="bg-white rounded-2xl shadow-2xl w-[400px] overflow-hidden transform scale-95 transition-all duration-300"
            id="account-picker-content">
            <div class="p-6 text-center border-b border-slate-100">
                <h3 class="text-xl font-bold text-slate-800">Collega Inbox</h3>
                <p class="text-xs text-slate-500 mt-1">Scegli il provider da connettere allo studio.</p>
            </div>
            <div class="p-6 space-y-3 bg-slate-50/50">
                <button onclick="InboxModule.connectAccount('gmail')"
                    class="w-full flex items-center gap-4 p-4 bg-white border border-slate-200 rounded-xl hover:border-blue-300 hover:shadow-md transition-all group">
                    <div
                        class="w-10 h-10 bg-white border border-slate-100 rounded-full flex items-center justify-center shadow-sm">
                        <img src="https://cdn.brandfetch.io/id5o3EIREg/w/400/h/400/theme/dark/icon.jpeg"
                            class="w-6 h-6 object-contain">
                    </div>
                    <div class="text-left">
                        <h4 class="font-bold text-slate-700 group-hover:text-blue-600">Google Gmail</h4>
                        <p class="text-[10px] text-slate-400">Workspace / Personal</p>
                    </div>
                    <i data-lucide="chevron-right" class="w-4 h-4 ml-auto text-slate-300 group-hover:text-blue-500"></i>
                </button>

                <button onclick="InboxModule.connectAccount('microsoft')"
                    class="w-full flex items-center gap-4 p-4 bg-white border border-slate-200 rounded-xl hover:border-sky-300 hover:shadow-md transition-all group">
                    <div
                        class="w-10 h-10 bg-white border border-slate-100 rounded-full flex items-center justify-center shadow-sm">
                        <img src="https://cdn.brandfetch.io/idgdw68PEO/w/400/h/400/theme/dark/icon.png"
                            class="w-6 h-6 object-contain">
                    </div>
                    <div class="text-left">
                        <h4 class="font-bold text-slate-700 group-hover:text-sky-600">Outlook 365</h4>
                        <p class="text-[10px] text-slate-400">Exchange / Office</p>
                    </div>
                    <i data-lucide="chevron-right" class="w-4 h-4 ml-auto text-slate-300 group-hover:text-sky-500"></i>
                </button>
            </div>
            <div class="p-4 bg-slate-50 border-t border-slate-100 text-center">
                <button onclick="InboxModule.closeAccountPicker()"
                    class="text-xs font-bold text-slate-500 hover:text-slate-700 uppercase tracking-wider">Annulla</button>
            </div>
        </div>
    </div>

    <!-- GLOBAL EMAIL COMPOSE DRAWER - Available from any page -->
    <div id="compose-overlay" class="cx-flyout-overlay"
        onclick="if(event.target===event.currentTarget) ComposeManager.close()"></div>
    <div id="compose-drawer" class="cx-flyout-panel compose-drawer">

        <!-- HEADER -->
        <div class="cx-flyout-header">
            <div class="cx-flyout-header-content">
                <div class="cx-flyout-tagline">COMPOSIZIONE</div>
                <h3 class="cx-flyout-title">Nuovo Messaggio</h3>
                <div class="cx-flyout-desc flex items-center gap-2 mt-1">
                    <span class="w-2 h-2 bg-emerald-400 rounded-full"></span>
                    <span style="font-size:11px; color:#9ca3af;">Connesso a Gmail & Outlook</span>
                </div>
            </div>
            <button class="cx-flyout-dismiss" onclick="ComposeManager.close()">
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
                    <line x1="18" y1="6" x2="6" y2="18" />
                    <line x1="6" y1="6" x2="18" y2="18" />
                </svg>
            </button>
        </div>

        <!-- BODY -->
        <div class="cx-flyout-body" style="padding:0; display:flex; flex-direction:column;">
            <div class="px-6 py-4 space-y-3 shrink-0 bg-white z-30 relative border-b border-slate-50">
                <div class="flex items-center gap-3 group">
                    <label
                        class="text-[11px] font-bold text-slate-400 uppercase tracking-widest w-16 text-right">Da</label>
                    <div class="relative flex-1">
                        <select id="compose-from-select"
                            class="w-full bg-slate-50/80 border border-slate-200 text-slate-800 text-sm font-medium rounded-lg px-3.5 py-2.5 outline-none focus:border-slate-400 focus:bg-white focus:ring-2 focus:ring-slate-200 appearance-none transition-all cursor-pointer">
                            <option value="" disabled selected>Seleziona mittente...</option>
                        </select>
                        <i data-lucide="chevron-down"
                            class="absolute right-3 top-1/2 -translate-y-1/2 w-4 h-4 text-slate-400 pointer-events-none"></i>
                    </div>
                </div>
                <div class="flex items-start gap-3 group relative z-[100]">
                    <label
                        class="text-[11px] font-bold text-slate-400 uppercase tracking-widest w-16 text-right pt-2.5">A</label>
                    <div
                        class="flex-1 relative bg-slate-50/80 border border-slate-200 rounded-lg p-2.5 focus-within:border-slate-400 focus-within:bg-white focus-within:ring-2 focus-within:ring-slate-200 transition-all">
                        <div id="recipient-chips" class="flex flex-wrap gap-2 mb-1 empty:hidden"></div>
                        <input type="text" id="compose-to-search"
                            class="w-full bg-transparent outline-none text-sm text-slate-800 placeholder-slate-400 py-1 font-medium border-none focus:ring-0"
                            placeholder="Cerca cliente o scrivi email..." autocomplete="off"
                            onkeyup="ComposeManager.handleClientSearch(this.value)"
                            onfocus="ComposeManager.showRecentClients(this.value)"
                            onkeydown="if(event.key === 'Enter') { event.preventDefault(); ComposeManager.handleRecipientKeydown(event); }">
                        <div id="client-autocomplete"
                            class="absolute top-full left-0 w-full bg-white border border-slate-200 shadow-xl rounded-lg z-[999] hidden max-h-60 overflow-y-auto mt-1.5 p-1.5 custom-scrollbar">
                        </div>
                    </div>
                </div>
                <div class="flex items-center gap-3 group">
                    <label
                        class="text-[11px] font-bold text-slate-400 uppercase tracking-widest w-16 text-right">Ogg.</label>
                    <input type="text" id="compose-subject"
                        class="flex-1 bg-slate-50/80 border border-slate-200 outline-none text-sm font-semibold text-slate-800 placeholder-slate-400 px-3.5 py-2.5 rounded-lg transition-all focus:border-slate-400 focus:bg-white focus:ring-2 focus:ring-slate-200"
                        placeholder="Inserisci l'oggetto...">
                </div>
            </div>

            <!-- AI TOOLBAR -->
            <div class="px-6 py-2.5 flex items-center gap-2.5 border-b border-slate-100 bg-slate-50/50">
                <div class="flex items-center gap-1.5 px-2.5 py-1 bg-[#0d0d0d] rounded-md shadow-sm">
                    <i data-lucide="sparkles" class="w-3 h-3 text-white"></i>
                    <span class="text-[10px] font-bold text-white tracking-wide">AI</span>
                </div>
                <div class="relative flex-1">
                    <input type="text" id="ai-prompt"
                        class="w-full h-9 pl-3 pr-10 bg-white border border-slate-200 text-sm text-slate-700 placeholder-slate-400 rounded-lg outline-none transition-all focus:border-violet-400 focus:ring-2 focus:ring-violet-100"
                        placeholder="Chiedi a Cortex di scrivere per te..."
                        onkeydown="if(event.key === 'Enter') ComposeManager.generateAI()">
                    <button onclick="ComposeManager.generateAI()"
                        class="absolute right-1 top-1/2 -translate-y-1/2 w-7 h-7 flex items-center justify-center rounded-md bg-[#0d0d0d] text-white transition-all">
                        <i data-lucide="arrow-up" class="w-3.5 h-3.5"></i>
                    </button>
                </div>
            </div>

            <!-- RICH EDITOR -->
            <div class="relative flex-1 px-6 py-3 bg-white">
                <div id="compose-body" contenteditable="true"
                    class="w-full h-full outline-none resize-none text-[15px] text-slate-700 leading-relaxed bg-transparent rounded-lg focus:bg-transparent transition-all custom-scrollbar p-3 overflow-y-auto"
                    style="min-height: 200px; white-space: pre-wrap;" data-placeholder="Scrivi qui il tuo messaggio...">
                </div>
                <div id="ai-skeleton-loader"
                    class="absolute inset-0 bg-white/95 backdrop-blur-sm z-20 hidden flex flex-col justify-center items-center rounded-lg transition-all duration-300">
                    <div class="flex items-center gap-2 mb-3">
                        <div class="w-2.5 h-2.5 bg-violet-500 rounded-full animate-[bounce_1s_infinite_100ms]"></div>
                        <div class="w-2.5 h-2.5 bg-indigo-500 rounded-full animate-[bounce_1s_infinite_200ms]"></div>
                        <div class="w-2.5 h-2.5 bg-purple-500 rounded-full animate-[bounce_1s_infinite_300ms]"></div>
                    </div>
                    <p class="text-xs font-bold text-slate-500">Cortex sta scrivendo...</p>
                </div>
            </div>

            <!-- SIGNATURE PREVIEW -->
            <div id="compose-signature-preview" class="hidden shrink-0 border-t border-slate-100">
                <button type="button" onclick="ComposeManager.toggleSignaturePreview()"
                    class="w-full flex items-center gap-2 px-6 py-2 text-[10px] font-bold text-slate-400 hover:text-indigo-500 hover:bg-indigo-50/50 transition-all uppercase tracking-wider">
                    <i data-lucide="pen-tool" class="w-3 h-3"></i>
                    <span>Firma</span>
                    <i data-lucide="chevron-down" id="sig-preview-chevron"
                        class="w-3 h-3 ml-auto transition-transform duration-200"></i>
                </button>
                <div id="compose-signature-content"
                    class="px-6 py-3 bg-slate-50/80 border-t border-slate-100/60 text-sm text-slate-600 leading-relaxed"
                    style="max-height: 160px; overflow-y: auto; display: none;">
                </div>
            </div>

            <div id="compose-attachments"
                class="px-6 py-2.5 flex flex-wrap gap-2.5 hidden border-t border-slate-100 bg-slate-50/30 min-h-[44px]">
            </div>
        </div>

        <!-- FOOTER -->
        <div class="cx-flyout-footer" style="flex-direction:column; gap:0;">
            <div class="w-full flex items-center gap-2 pb-2.5 mb-2.5" style="border-bottom:1px solid #ebebeb;">
                <button onclick="document.getElementById('local-upload-input').click()"
                    class="compose-toolbar-btn flex items-center gap-1.5 px-3 py-1.5 text-slate-500 rounded-lg hover:bg-slate-200/80 transition-all text-xs font-medium"
                    title="Allega file">
                    <i data-lucide="paperclip" class="w-3.5 h-3.5"></i>
                    <span>Allega</span>
                </button>
                <input type="file" id="local-upload-input" class="hidden" multiple
                    onchange="ComposeManager.handleLocalUpload(event)">
                <div class="h-5 w-px bg-slate-200"></div>
                <button onclick="InboxSignatureEditor.open()"
                    class="compose-toolbar-btn flex items-center gap-1.5 px-3 py-1.5 text-slate-500 rounded-lg hover:bg-slate-200/80 transition-all text-xs font-medium"
                    title="Configura Firma Email">
                    <i data-lucide="pen-tool" class="w-3.5 h-3.5"></i>
                    <span>Firma</span>
                </button>
                <div class="flex-1"></div>
                <button onclick="ComposeManager.saveDraft()"
                    class="compose-toolbar-btn flex items-center gap-1.5 px-3 py-1.5 text-slate-500 rounded-lg hover:bg-slate-200/80 transition-all text-xs font-medium">
                    <i data-lucide="file-edit" class="w-3.5 h-3.5"></i>
                    <span>Bozza</span>
                </button>
            </div>
            <div class="w-full flex justify-end items-center">
                <button onclick="ComposeManager.send()" id="btn-send-real"
                    class="px-6 py-2.5 bg-slate-900 hover:bg-slate-800 text-white rounded-lg text-sm font-bold shadow-lg shadow-slate-900/20 transition-all duration-200 flex items-center gap-2.5 hover:shadow-slate-900/30">
                    <span>Invia</span>
                    <i data-lucide="send" class="w-4 h-4"></i>
                </button>
            </div>
        </div>
    </div>

    <!-- Console Protection (must be first) -->
    <script src="js/console-protection.js"></script>

    <script src="js/secure-sanitize.js"></script>
    <script src="js/db-helper.js"></script>
    <script src="js/cloud-connector.js"></script>

    <script src="script.js"></script>
    <script src="js/global-notifications.js"></script>
    <!-- [REMOVED] studio-config-modal.js — replaced by unified OnboardingWizard -->
    <script src="components/oauth-disclaimer.js"></script>
    <script src="components/add-client-modal.js"></script>
    <script src="components/auto-file-modal.js"></script>
    <script src="js/tab-guide-definitions.js"></script>
    <script src="js/tab-guide.js"></script>
    <script src="router.js?v=20260218f"></script>
    <script src="js/custom-tabs-loader.js"></script>
    <script src="cortex-logic.js"></script>
    <script src="components/loader.js"></script>
    <script src="components/smartMentions.js"></script>
    <script src="js/document-integrity.js"></script>
    <script src="js/integrity-logic.js"></script>
    <script src="js/firma-dashboard.js"></script>
    <script src="js/cortex-actions.js"></script>
    <script src="js/agentic-console.js"></script>
    <script src="js/archive-testament.js"></script>
    <script src="js/archive-router.js"></script>
    <script src="js/cortex-views.js"></script>
    <script src="js/cortex-core.js"></script>
    <script src="js/audit-logger.js"></script>
    <script src="components/CloudMapViewer.js"></script>
    <script src="js/inbox-logic.js"></script>
    <script src="js/attachment-viewer.js"></script>
    <script src="js/notifications.js"></script>
    <script src="js/studio-notifications.js"></script>
    <script src="js/calendar-integration.js"></script>
    <script src="js/clients-logic.js"></script>

    <script src="js/import-clients-modal.js"></script>
    <script src="js/voice-ai-engine.js"></script>
    <script src="js/team-chat.js"></script>
    <script src="js/team-tasks.js"></script>
    <script src="js/team-permissions.js"></script>
    <script src="js/f24-module.js"></script>
    <script src="js/global-search.js"></script>

    <!-- Global Sticky Notes Functions -->
    <script>
        // Global Sticky Notes - Available in all tabs
        let globalStickyNotes = [];
        let stickyNotesUnsubscribe = null;

        // Toggle sticky notes panel
        function toggleGlobalStickyNotes() {
            const panel = document.getElementById('sticky-notes-panel');
            const chevron = document.getElementById('sticky-chevron');
            if (!panel) return;

            const isHidden = panel.classList.contains('hidden');

            if (isHidden) {
                panel.classList.remove('hidden');
                setTimeout(() => {
                    panel.classList.remove('opacity-0', '-translate-y-2');
                    panel.classList.add('opacity-100', 'translate-y-0');
                }, 10);
                chevron?.classList.add('rotate-180');
                loadGlobalStickyNotes();
                document.addEventListener('click', closeStickiesOnOutsideClick);
            } else {
                panel.classList.add('opacity-0', '-translate-y-2');
                panel.classList.remove('opacity-100', 'translate-y-0');
                chevron?.classList.remove('rotate-180');
                setTimeout(() => panel.classList.add('hidden'), 200);
                document.removeEventListener('click', closeStickiesOnOutsideClick);
            }
        }

        function closeStickiesOnOutsideClick(e) {
            const wrapper = document.getElementById('global-sticky-notes');
            if (wrapper && !wrapper.contains(e.target)) {
                const panel = document.getElementById('sticky-notes-panel');
                const chevron = document.getElementById('sticky-chevron');
                if (panel && !panel.classList.contains('hidden')) {
                    panel.classList.add('opacity-0', '-translate-y-2');
                    panel.classList.remove('opacity-100', 'translate-y-0');
                    chevron?.classList.remove('rotate-180');
                    setTimeout(() => panel.classList.add('hidden'), 200);
                }
                document.removeEventListener('click', closeStickiesOnOutsideClick);
            }
        }

        // Load sticky notes from Firestore
        async function loadGlobalStickyNotes() {
            const studioId = window.DbHelper?.getStudioId();
            if (!studioId) {
                console.warn('⚠️ No studioId for sticky notes');
                return;
            }

            try {
                const snap = await window.db.collection('studios').doc(studioId)
                    .collection('sticky_notes')
                    .orderBy('createdAt', 'desc')
                    .limit(20)
                    .get();

                globalStickyNotes = snap.docs.map(doc => ({ id: doc.id, ...doc.data() }));
                renderGlobalStickyNotes();
            } catch (err) {
                console.error('Error loading sticky notes:', err);
            }
        }

        // Render sticky notes - first 3 pinned, rest in dropdown
        function renderGlobalStickyNotes() {
            const pinnedContainer = document.getElementById('pinned-sticky-notes');
            const moreBtn = document.getElementById('more-sticky-btn');
            const moreCount = document.getElementById('more-sticky-count');
            const hiddenList = document.getElementById('hidden-sticky-notes-list');

            if (!pinnedContainer) return;

            // Split into pinned (first 3) and hidden (rest)
            const pinnedNotes = globalStickyNotes.slice(0, 3);
            const hiddenNotes = globalStickyNotes.slice(3);

            // Render pinned notes with pushpin
            if (pinnedNotes.length === 0) {
                pinnedContainer.innerHTML = '';
            } else {
                pinnedContainer.innerHTML = pinnedNotes.map(note => {
                    const truncatedText = note.text.length > 30 ? note.text.slice(0, 30) + '...' : note.text;
                    return `
                        <div class="pinned-note folded ${note.color || 'yellow'}" 
                             title="${escapeHtml(note.text)}"
                             onclick="togglePinnedNoteFold(this)"
                             data-full-text="${escapeHtml(note.text)}"
                             data-truncated-text="${escapeHtml(truncatedText)}">
                            <button class="note-close" onclick="deleteGlobalStickyNote('${note.id}', event)">×</button>
                            <div class="note-text text-[11px] leading-tight text-slate-700">${escapeHtml(truncatedText)}</div>
                            ${note.client ? `<div class="text-[9px] mt-1 opacity-70">📎 ${escapeHtml(note.client)}</div>` : ''}
                        </div>`;
                }).join('');
            }

            // Show/hide more button
            if (hiddenNotes.length > 0) {
                moreBtn?.classList.remove('hidden');
                if (moreCount) moreCount.textContent = `+${hiddenNotes.length}`;

                // Render hidden notes list
                if (hiddenList) {
                    hiddenList.innerHTML = hiddenNotes.map(note => `
                        <div class="relative p-2.5 rounded-lg border bg-${note.color || 'yellow'}-100 border-${note.color || 'yellow'}-200 group hover:shadow-sm transition-all">
                            <button onclick="deleteGlobalStickyNote('${note.id}', event)" 
                                class="absolute top-1 right-1 w-4 h-4 rounded-full bg-red-500/0 hover:bg-red-500 text-slate-400 hover:text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition-all text-[10px]">×</button>
                            <p class="text-xs font-medium text-slate-700 pr-4">${escapeHtml(note.text)}</p>
                            ${note.client ? `<div class="text-[10px] text-slate-400 mt-1">📎 ${escapeHtml(note.client)}</div>` : ''}
                        </div>`).join('');
                }
            } else {
                moreBtn?.classList.add('hidden');
            }

            lucide?.createIcons?.();
        }

        // Toggle more sticky notes dropdown
        function toggleMoreStickyNotes() {
            const panel = document.getElementById('hidden-sticky-notes-panel');
            const chevron = document.getElementById('more-sticky-chevron');
            if (!panel) return;

            const isHidden = panel.classList.contains('hidden');

            if (isHidden) {
                panel.classList.remove('hidden');
                setTimeout(() => {
                    panel.classList.remove('opacity-0', '-translate-y-2');
                    panel.classList.add('opacity-100', 'translate-y-0');
                }, 10);
                chevron?.classList.add('rotate-180');
                document.addEventListener('click', closeMoreStickiesOnOutsideClick);
            } else {
                panel.classList.add('opacity-0', '-translate-y-2');
                panel.classList.remove('opacity-100', 'translate-y-0');
                chevron?.classList.remove('rotate-180');
                setTimeout(() => panel.classList.add('hidden'), 200);
                document.removeEventListener('click', closeMoreStickiesOnOutsideClick);
            }
        }

        function closeMoreStickiesOnOutsideClick(e) {
            const wrapper = document.getElementById('global-sticky-notes');
            const moreBtn = document.getElementById('more-sticky-btn');
            if (wrapper && !wrapper.contains(e.target)) {
                const panel = document.getElementById('hidden-sticky-notes-panel');
                const chevron = document.getElementById('more-sticky-chevron');
                if (panel && !panel.classList.contains('hidden')) {
                    panel.classList.add('opacity-0', '-translate-y-2');
                    panel.classList.remove('opacity-100', 'translate-y-0');
                    chevron?.classList.remove('rotate-180');
                    setTimeout(() => panel.classList.add('hidden'), 200);
                }
                document.removeEventListener('click', closeMoreStickiesOnOutsideClick);
            }
        }


        // Delete a sticky note
        async function deleteGlobalStickyNote(noteId, event) {
            event.stopPropagation();
            const studioId = window.DbHelper?.getStudioId();
            if (!studioId || !noteId) return;

            try {
                await window.db.collection('studios').doc(studioId)
                    .collection('sticky_notes').doc(noteId).delete();
                globalStickyNotes = globalStickyNotes.filter(n => n.id !== noteId);
                renderGlobalStickyNotes();
            } catch (err) {
                console.error('Error deleting sticky note:', err);
            }
        }

        // Toggle pinned note between folded (small) and unfolded (full text) - parchment style
        function togglePinnedNoteFold(noteElement) {
            // Don't toggle if clicking the close button
            if (event.target.classList.contains('note-close')) return;

            const isFolded = noteElement.classList.contains('folded');
            const textElement = noteElement.querySelector('.note-text');

            // Fold any other unfolded notes first
            document.querySelectorAll('.pinned-note:not(.folded)').forEach(note => {
                if (note !== noteElement) {
                    note.classList.add('folded');
                    const txt = note.querySelector('.note-text');
                    if (txt) txt.textContent = note.dataset.truncatedText;
                }
            });

            if (isFolded) {
                // Unfold it - show full text
                noteElement.classList.remove('folded');
                if (textElement) textElement.textContent = noteElement.dataset.fullText;
            } else {
                // Fold it back
                noteElement.classList.add('folded');
                if (textElement) textElement.textContent = noteElement.dataset.truncatedText;
            }
        }

        // Open add sticky note modal
        async function openAddStickyModal() {
            const studioId = window.DbHelper?.getStudioId();
            if (!studioId) {
                Swal.fire('Errore', 'Studio non trovato. Ricarica la pagina.', 'error');
                return;
            }

            // Get team members for assignment
            let teamMembers = [];
            try {
                const membersSnap = await window.db.collection('studios').doc(studioId)
                    .collection('team_members').get();
                teamMembers = membersSnap.docs.map(doc => ({ id: doc.id, ...doc.data() }));
            } catch (err) {
                console.warn('Could not load team members:', err);
            }

            const colorOptions = [
                { value: 'yellow', label: '🟡 Giallo' },
                { value: 'pink', label: '🩷 Rosa' },
                { value: 'blue', label: '🔵 Blu' },
                { value: 'green', label: '🟢 Verde' },
                { value: 'orange', label: '🟠 Arancio' }
            ].map((c, i) => `<option value="${c.value}" ${i === 0 ? 'selected' : ''}>${c.label}</option>`).join('');

            const memberOptions = teamMembers.length > 0
                ? `<option value="">Nessuno (visibile a tutti)</option>` + teamMembers.map(m =>
                    `<option value="${m.id}">${escapeHtml(m.displayName || m.email)}</option>`).join('')
                : `<option value="">Nessun membro</option>`;

            const { value: formData } = await Swal.fire({
                title: '📌 Nuovo Promemoria',
                html: `
                    <div class="space-y-4 text-left">
                        <div>
                            <label class="block text-sm font-semibold text-slate-600 mb-1">Testo</label>
                            <textarea id="sticky-text" class="swal2-textarea" placeholder="Scrivi il promemoria..." rows="3" style="margin:0;width:100%"></textarea>
                        </div>
                        <div class="flex gap-3">
                            <div class="flex-1">
                                <label class="block text-sm font-semibold text-slate-600 mb-1">Colore</label>
                                <select id="sticky-color" class="swal2-select" style="margin:0;width:100%">${colorOptions}</select>
                            </div>
                            <div class="flex-1">
                                <label class="block text-sm font-semibold text-slate-600 mb-1">Cliente (opz)</label>
                                <input id="sticky-client" class="swal2-input" placeholder="Nome cliente" style="margin:0;width:100%">
                            </div>
                        </div>
                        <div>
                            <label class="block text-sm font-semibold text-slate-600 mb-1">Assegna a (opz)</label>
                            <select id="sticky-assignee" class="swal2-select" style="margin:0;width:100%">${memberOptions}</select>
                        </div>
                    </div>
                `,
                showCancelButton: true,
                confirmButtonText: 'Aggiungi',
                cancelButtonText: 'Annulla',
                confirmButtonColor: '#6366f1',
                preConfirm: () => {
                    const text = document.getElementById('sticky-text').value.trim();
                    if (!text) {
                        Swal.showValidationMessage('Inserisci un testo');
                        return null;
                    }
                    return {
                        text,
                        color: document.getElementById('sticky-color').value,
                        client: document.getElementById('sticky-client').value.trim(),
                        assignee: document.getElementById('sticky-assignee').value
                    };
                }
            });

            if (!formData) return;

            try {
                const user = firebase.auth().currentUser;
                const assignedMember = teamMembers.find(m => m.id === formData.assignee);

                await window.db.collection('studios').doc(studioId)
                    .collection('sticky_notes').add({
                        text: formData.text,
                        color: formData.color,
                        client: formData.client || null,
                        assignedTo: formData.assignee || null,
                        assignedToName: assignedMember?.displayName || assignedMember?.email || null,
                        createdBy: user?.uid || null,
                        createdByName: user?.displayName || user?.email || null,
                        createdAt: firebase.firestore.FieldValue.serverTimestamp()
                    });

                await loadGlobalStickyNotes();
                Swal.fire({ icon: 'success', title: 'Aggiunto!', timer: 1200, showConfirmButton: false });
            } catch (err) {
                console.error('Error adding sticky note:', err);
                Swal.fire('Errore', 'Impossibile aggiungere il promemoria', 'error');
            }
        }

        // Escape HTML helper
        function escapeHtml(str) {
            if (!str) return '';
            const div = document.createElement('div');
            div.textContent = str;
            return div.innerHTML;
        }

        // Load sticky notes on auth state change
        firebase.auth().onAuthStateChanged(user => {
            if (user) {
                setTimeout(() => loadGlobalStickyNotes(), 1500);
                // 2FA enforcement: load twofa-logic.js and check if 2FA is required
                setTimeout(() => {
                    if (window.TwoFAModule) {
                        window.TwoFAModule.check2FAStatus();
                    } else {
                        const s = document.createElement('script');
                        s.src = 'js/twofa-logic.js';
                        s.onload = () => window.TwoFAModule.check2FAStatus();
                        document.body.appendChild(s);
                    }
                }, 2500);
                // DPA check: show blocker if DPA not signed
                setTimeout(() => {
                    if (window.DPAModule) {
                        window.DPAModule.checkAndShowDPA();
                    } else {
                        const s = document.createElement('script');
                        s.src = 'js/dpa-module.js';
                        s.onload = () => window.DPAModule && window.DPAModule.checkAndShowDPA();
                        document.body.appendChild(s);
                    }
                }, 3000);
            }
        });
    </script>

    <script src="js/dpa-module.js"></script>

    <!-- Sidebar Helpers -->
    <script>
        // =====================================================
        // NOTIFICATIONS DROPDOWN
        // =====================================================

        // Toggle notifications dropdown
        function toggleNotifications(event) {
            if (event) event.stopPropagation();

            // Delegate to StudioNotificationManager if available
            if (window.StudioNotificationManager && typeof StudioNotificationManager.toggleDropdown === 'function') {
                StudioNotificationManager.toggleDropdown();
                return;
            }

            const dropdown = document.getElementById('notification-dropdown');
            if (!dropdown) return;

            const isHidden = dropdown.classList.contains('hidden');

            if (isHidden) {
                dropdown.classList.remove('hidden');
                setTimeout(() => {
                    dropdown.classList.remove('opacity-0', '-translate-y-2');
                    dropdown.classList.add('opacity-100', 'translate-y-0');
                }, 10);
                // Delay adding outside click listener to prevent immediate close
                setTimeout(() => document.addEventListener('click', closeNotificationsOnOutsideClick), 100);
                loadNotifications();
            } else {
                closeNotificationDropdown();
            }
        }

        function closeNotificationDropdown() {
            const dropdown = document.getElementById('notification-dropdown');
            if (dropdown) {
                dropdown.classList.add('opacity-0', '-translate-y-2');
                dropdown.classList.remove('opacity-100', 'translate-y-0');
                setTimeout(() => dropdown.classList.add('hidden'), 200);
            }
            document.removeEventListener('click', closeNotificationsOnOutsideClick);
        }

        function closeNotificationsOnOutsideClick(e) {
            const wrapper = document.getElementById('notification-wrapper');
            if (wrapper && !wrapper.contains(e.target)) {
                const dropdown = document.getElementById('notification-dropdown');
                if (dropdown) {
                    dropdown.classList.add('opacity-0', '-translate-y-2');
                    dropdown.classList.remove('opacity-100', 'translate-y-0');
                    setTimeout(() => dropdown.classList.add('hidden'), 200);
                }
                document.removeEventListener('click', closeNotificationsOnOutsideClick);
            }
        }

        // Expose globally so StudioNotificationManager can call it
        window.loadNotifications = loadNotifications;

        async function loadNotifications() {
            const studioId = window.DbHelper?.getStudioId();
            if (!studioId) return;

            const notifications = [];

            try {
                // 1. Email non lette (ultime 5)
                const emailSnap = await window.db.collection('studios').doc(studioId)
                    .collection('inbox').where('status', '==', 'unread')
                    .orderBy('receivedAt', 'desc').limit(5).get();

                emailSnap.docs.forEach(doc => {
                    const d = doc.data();
                    notifications.push({
                        id: doc.id,
                        type: 'email',
                        title: d.from?.split('<')[0]?.trim() || 'Nuova email',
                        message: d.subject || 'Senza oggetto',
                        createdAt: d.receivedAt,
                        read: false
                    });
                });

                // 2. Scadenze imminenti (prossimi 7 giorni)
                const now = new Date();
                const in7days = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);

                const deadlinesSnap = await window.db.collection('studios').doc(studioId)
                    .collection('deadlines').where('dueDate', '>=', firebase.firestore.Timestamp.fromDate(now))
                    .where('dueDate', '<=', firebase.firestore.Timestamp.fromDate(in7days))
                    .orderBy('dueDate', 'asc').limit(5).get();

                deadlinesSnap.docs.forEach(doc => {
                    const d = doc.data();
                    notifications.push({
                        id: doc.id,
                        type: 'deadline',
                        title: d.title || 'Scadenza',
                        message: d.description || d.clientName || '',
                        createdAt: d.dueDate,
                        read: d.completed || false
                    });
                });

                // 3. Documenti recenti non processati
                const docsSnap = await window.db.collection('studios').doc(studioId)
                    .collection('documents').where('status', '==', 'pending')
                    .orderBy('createdAt', 'desc').limit(3).get();

                docsSnap.docs.forEach(doc => {
                    const d = doc.data();
                    notifications.push({
                        id: doc.id,
                        type: 'document',
                        title: 'Documento da processare',
                        message: d.fileName || d.name || '',
                        createdAt: d.createdAt,
                        read: false
                    });
                });

                // Ordina per data più recente
                notifications.sort((a, b) => {
                    const dateA = a.createdAt?.toDate?.() || a.createdAt || new Date(0);
                    const dateB = b.createdAt?.toDate?.() || b.createdAt || new Date(0);
                    return dateB - dateA;
                });

                renderNotifications(notifications.slice(0, 10));
            } catch (err) {
                console.warn('Failed to load notifications:', err);
                renderNotifications([]);
            }
        }

        function renderNotifications(notifications) {
            const list = document.getElementById('notifications-list');
            const dropdownHeaderBadge = document.querySelector('#notification-dropdown .bg-indigo-100.text-indigo-600');
            if (!list) return;

            if (!notifications || notifications.length === 0) {
                list.innerHTML = `<div class="p-8 text-center"><div class="w-12 h-12 bg-slate-100 rounded-full flex items-center justify-center mx-auto mb-3"><i data-lucide="bell-off" class="w-6 h-6 text-slate-400"></i></div><p class="text-sm text-slate-500">Nessuna notifica</p></div>`;
                lucide.createIcons();
                // Hide header badge
                const headerBadge = document.getElementById('notification-badge');
                if (headerBadge) headerBadge.classList.add('hidden');
                if (dropdownHeaderBadge) dropdownHeaderBadge.textContent = '0 nuove';
                return;
            }

            const unreadCount = notifications.filter(n => !n.read).length;

            // Update header badge
            const headerBadge = document.getElementById('notification-badge');
            if (headerBadge) {
                headerBadge.textContent = unreadCount;
                if (unreadCount > 0) {
                    headerBadge.classList.remove('hidden');
                } else {
                    headerBadge.classList.add('hidden');
                }
            }

            // Update dropdown badge
            const dropdownBadge = document.querySelector('#notification-dropdown .bg-indigo-100.text-indigo-600');
            if (dropdownBadge) dropdownBadge.textContent = `${unreadCount} nuove`;

            const icons = { document: 'file-check', email: 'mail', deadline: 'clock', client: 'user', system: 'info' };
            const colors = { document: 'bg-emerald-100 text-emerald-600', email: 'bg-blue-100 text-blue-600', deadline: 'bg-amber-100 text-amber-600', client: 'bg-teal-100 text-teal-600', system: 'bg-slate-100 text-slate-600' };

            list.innerHTML = `<div class="p-2 space-y-1">${notifications.map(n => {
                const icon = icons[n.type] || 'bell';
                const color = colors[n.type] || 'bg-slate-100 text-slate-600';
                const time = n.createdAt?.toDate ? formatTimeAgo(n.createdAt.toDate()) : '';
                const bg = !n.read ? 'bg-indigo-50/50' : '';
                return `<div class="flex gap-3 p-3 rounded-xl hover:bg-slate-50 cursor-pointer transition-colors ${bg}" onclick="handleNotificationClick('${n.type}', '${n.id}')"><div class="w-9 h-9 rounded-lg ${color} flex items-center justify-center shrink-0"><i data-lucide="${icon}" class="w-4 h-4"></i></div><div class="flex-1 min-w-0"><p class="text-sm font-medium text-slate-700 truncate">${n.title || 'Notifica'}</p><p class="text-xs text-slate-400">${n.message || ''} • ${time}</p></div></div>`;
            }).join('')}</div>`;
            lucide.createIcons();
        }

        function handleNotificationClick(type, id) {
            // Chiudi dropdown
            toggleNotifications();

            // Naviga alla sezione appropriata
            if (type === 'email') {
                router.load('inbox');
            } else if (type === 'deadline') {
                router.load('dashboard');
            } else if (type === 'document') {
                router.load('cortex');
            }
        }

        function formatTimeAgo(date) {
            if (!date) return '';
            const diff = Math.floor((new Date() - date) / 1000);
            if (diff < 60) return 'ora';
            if (diff < 3600) return `${Math.floor(diff / 60)} min fa`;
            if (diff < 86400) return `${Math.floor(diff / 3600)} ore fa`;
            if (diff < 604800) return `${Math.floor(diff / 86400)} giorni fa`;
            return date.toLocaleDateString('it-IT');
        }

        // =====================================================
        // USER MENU DROPDOWN
        // =====================================================

        // Toggle user menu dropdown in sidebar (opens ABOVE)
        function toggleUserMenu() {
            const menu = document.getElementById('user-dropdown-menu');
            if (menu) {
                const isHidden = menu.classList.contains('hidden');
                menu.classList.toggle('hidden');

                // Position the fixed dropdown relative to the avatar
                if (isHidden) {
                    const avatar = document.getElementById('sidebar-user-avatar');
                    if (avatar) {
                        const rect = avatar.getBoundingClientRect();
                        menu.style.left = rect.left + 'px';
                        menu.style.bottom = (window.innerHeight - rect.top + 8) + 'px';
                    }
                    setTimeout(() => {
                        document.addEventListener('click', closeUserMenuOnOutsideClick);
                    }, 10);
                }

                // Update chevron direction
                const chevron = document.getElementById('user-menu-chevron');
                if (chevron) {
                    chevron.style.transform = isHidden ? 'rotate(180deg)' : '';
                }
            }
        }

        // Set user status (online/away)
        function setUserStatus(status) {
            const statusDot = document.querySelector('#main-sidebar .relative .absolute');
            if (statusDot) {
                statusDot.classList.remove('bg-emerald-500', 'bg-amber-500');
                if (status === 'away') {
                    statusDot.classList.add('bg-amber-500');
                } else {
                    statusDot.classList.add('bg-emerald-500');
                }
            }
            toggleUserMenu();

            // Save status to Firestore - use 'team' collection (not 'operators')
            const studioId = window.DbHelper?.getStudioId();
            const user = firebase.auth().currentUser;
            if (studioId && user && window.db) {
                window.db.collection('studios').doc(studioId)
                    .collection('team').doc(user.uid)
                    .set({
                        status: status,
                        online: status !== 'away',
                        statusUpdatedAt: firebase.firestore.FieldValue.serverTimestamp()
                    }, { merge: true })
                    .then(() => console.log('User status updated to:', status))
                    .catch(err => console.log('Status update:', err));
            }
        }

        // Open Team Chat - navigates to tracker and opens team chat tab
        function openTeamChat() {
            router.load('team-chat');
        }

        // Close user menu when clicking outside
        function closeUserMenuOnOutsideClick(e) {
            const menu = document.getElementById('user-dropdown-menu');
            const userCard = document.querySelector('#main-sidebar .p-3.relative > .flex');

            if (menu && userCard && !menu.contains(e.target) && !userCard.contains(e.target)) {
                menu.classList.add('hidden');
                const chevron = document.getElementById('user-menu-chevron');
                if (chevron) chevron.style.transform = '';
                document.removeEventListener('click', closeUserMenuOnOutsideClick);
            }
        }

        // =====================================================
        // UNIFIED INBOX WIDGET
        // =====================================================

        // Toggle the Unified Inbox widget expand/collapse
        function toggleUnifiedInboxWidget() {
            const widget = document.getElementById('unified-inbox-widget');
            if (widget) {
                widget.classList.toggle('collapsed');
            }
        }

        // Load Inbox widget data (called when page loads)
        async function loadInboxWidgetData() {
            const studioId = window.DbHelper?.getStudioId();
            if (!studioId) return;

            try {
                // Call Cloud Function to get stats
                const getStats = firebase.app().functions('europe-west1').httpsCallable('getEmailCategorizationStats');
                const result = await getStats({ studioId });
                const stats = result.data;

                if (!stats) return;

                // Update widget stats (null-safe for pages without widgets)
                const elUnread = document.getElementById('widget-stat-unread');
                const elUrgent = document.getElementById('widget-stat-urgent');
                const elAi = document.getElementById('widget-stat-ai');
                if (elUnread) elUnread.textContent = stats.unread || 0;
                if (elUrgent) elUrgent.textContent = stats.urgent || 0;
                if (elAi) elAi.textContent = stats.aiCategorized || 0;

                // Update badge on Inbox nav item
                const badge = document.getElementById('inbox-unread-badge');
                if (badge && stats.unread > 0) {
                    badge.textContent = stats.unread;
                    badge.classList.remove('hidden');
                }

                // Populate categories list
                const categoriesList = document.getElementById('ai-categories-list');
                if (categoriesList && stats.byCategory) {
                    const categoryColors = {
                        'urgente': 'bg-red-100 text-red-700',
                        'fatture': 'bg-amber-100 text-amber-700',
                        'f24': 'bg-orange-100 text-orange-700',
                        'pagamenti': 'bg-emerald-100 text-emerald-700',
                        'scadenze': 'bg-rose-100 text-rose-700',
                        'iva': 'bg-blue-100 text-blue-700',
                        'bilancio': 'bg-purple-100 text-purple-700',
                        'contratti': 'bg-indigo-100 text-indigo-700',
                        'buste_paga': 'bg-cyan-100 text-cyan-700',
                        'clienti': 'bg-teal-100 text-teal-700',
                        'generale': 'bg-slate-100 text-slate-700'
                    };

                    const entries = Object.entries(stats.byCategory)
                        .filter(([_, count]) => count > 0)
                        .sort((a, b) => b[1] - a[1])
                        .slice(0, 5);

                    if (entries.length === 0) {
                        // Fallback: trigger local categorization or show categorize button
                        categoriesList.innerHTML = `
                            <button onclick="triggerAICategorization()" 
                                    class="w-full px-3 py-2 bg-gradient-to-r from-indigo-500 to-purple-500 text-white text-xs font-bold rounded-lg hover:opacity-90 transition-all flex items-center justify-center gap-2">
                                <i data-lucide="sparkles" class="w-3 h-3"></i>
                                Categorizza email con AI
                            </button>
                        `;
                        if (typeof lucide !== 'undefined') lucide.createIcons();
                    } else {
                        categoriesList.innerHTML = entries.map(([cat, count]) => {
                            const colorClass = categoryColors[cat] || 'bg-slate-100 text-slate-700';
                            const displayName = cat.replace('_', ' ').charAt(0).toUpperCase() + cat.replace('_', ' ').slice(1);
                            return `
                                <div class="ai-category-pill ${colorClass}" onclick="router.load('inbox'); setTimeout(() => InboxModule.filterBySmartCategory?.('${cat}'), 500)">
                                    <span>${displayName}</span>
                                    <span class="count">${count}</span>
                                </div>`;
                        }).join('');
                    }
                }
            } catch (error) {
                console.warn('Inbox widget data load failed:', error);
                const categoriesList = document.getElementById('ai-categories-list');
                if (categoriesList) {
                    categoriesList.innerHTML = `
                        <button onclick="triggerAICategorization()" 
                                class="w-full px-3 py-2 bg-gradient-to-r from-indigo-500 to-purple-500 text-white text-xs font-bold rounded-lg hover:opacity-90 transition-all flex items-center justify-center gap-2">
                            <i data-lucide="sparkles" class="w-3 h-3"></i>
                            Categorizza email
                        </button>
                    `;
                    if (typeof lucide !== 'undefined') lucide.createIcons();
                }
            }
        }

        // Trigger AI categorization of emails
        async function triggerAICategorization() {
            const studioId = window.DbHelper?.getStudioId();
            if (!studioId) return;

            const categoriesList = document.getElementById('ai-categories-list');
            if (categoriesList) {
                categoriesList.innerHTML = '<p class="text-[10px] text-indigo-500 animate-pulse flex items-center gap-1"><i data-lucide="loader" class="w-3 h-3 animate-spin"></i> Categorizzazione in corso...</p>';
                if (typeof lucide !== 'undefined') lucide.createIcons();
            }

            try {
                const categorizeEmails = firebase.app().functions('europe-west1').httpsCallable('aiBatchCategorizeEmails');
                await categorizeEmails({ studioId, limit: 50 });

                // Reload widget data
                await loadInboxWidgetData();
            } catch (error) {
                console.error('AI Categorization failed:', error);
                if (categoriesList) {
                    categoriesList.innerHTML = '<p class="text-[10px] text-red-500">Errore categorizzazione</p>';
                }
            }
        }

        // Load widget data when auth state changes
        firebase.auth().onAuthStateChanged(user => {
            if (user) {
                setTimeout(() => loadInboxWidgetData(), 1500);
                setTimeout(() => loadNotifications(), 2000); // Load notification badge
                setTimeout(() => { if (window.CustomTabsLoader) CustomTabsLoader.init(); }, 1200); // Load custom tabs
            }
        });

        // ===== HEADER WIDGETS JS =====

        // --- Live Clock ---
        function updateHeaderClock() {
            const now = new Date();
            const clockEl = document.getElementById('header-clock');
            const dateEl = document.getElementById('header-date');
            if (clockEl) clockEl.textContent = now.toLocaleTimeString('it-IT', { hour: '2-digit', minute: '2-digit', second: '2-digit' });
            if (dateEl) dateEl.textContent = now.toLocaleDateString('it-IT', { weekday: 'short', day: 'numeric', month: 'short' });
        }
        updateHeaderClock();
        setInterval(updateHeaderClock, 1000);

        // --- Quick Actions Dropdown ---
        function toggleQuickActions() {
            const dd = document.getElementById('quick-actions-dropdown');
            if (!dd) return;
            const isOpen = !dd.classList.contains('hidden');
            if (isOpen) {
                dd.classList.add('opacity-0', '-translate-y-2');
                setTimeout(() => dd.classList.add('hidden'), 150);
            } else {
                dd.classList.remove('hidden');
                requestAnimationFrame(() => {
                    dd.classList.remove('opacity-0', '-translate-y-2');
                });
                if (typeof lucide !== 'undefined') lucide.createIcons();
            }
        }
        // Close quick actions on outside click
        document.addEventListener('click', e => {
            const wrapper = document.getElementById('quick-actions-wrapper');
            const dd = document.getElementById('quick-actions-dropdown');
            if (wrapper && dd && !wrapper.contains(e.target) && !dd.classList.contains('hidden')) {
                toggleQuickActions();
            }
        });

        // --- Keyboard Shortcuts Modal ---
        function showKeyboardShortcuts() {
            // Remove existing if any
            document.getElementById('keyboard-shortcuts-modal')?.remove();

            const shortcuts = [
                { keys: '⌘ K', desc: 'Ricerca globale' },
                { keys: '⌘ N', desc: 'Nuovo elemento' },
                { keys: '⌘ /', desc: 'Scorciatoie tastiera' },
                { keys: '⌘ B', desc: 'Toggle sidebar' },
                { keys: '⌘ F', desc: 'Cerca nella pagina' },
                { keys: 'F11', desc: 'Schermo intero' },
                { keys: 'Esc', desc: 'Chiudi modale / overlay' },
                { keys: '1', desc: 'Home / Dashboard' },
                { keys: '2', desc: 'Inbox' },
                { keys: '3', desc: 'Clienti' },
                { keys: '4', desc: 'Documenti' },
                { keys: '5', desc: 'Fatture' },
            ];

            const modal = document.createElement('div');
            modal.id = 'keyboard-shortcuts-modal';
            modal.style.cssText = 'position:fixed;inset:0;z-index:99999;display:flex;align-items:center;justify-content:center;background:rgba(0,0,0,0.7);backdrop-filter:blur(8px);animation:fadeIn 0.2s ease;';
            modal.onclick = e => { if (e.target === modal) modal.remove(); };

            modal.innerHTML = `
                <div style="background:#111;border:1px solid rgba(255,255,255,0.1);border-radius:16px;width:380px;max-height:80vh;overflow:hidden;box-shadow:0 25px 60px rgba(0,0,0,0.5);">
                    <div style="padding:16px 20px;border-bottom:1px solid rgba(255,255,255,0.06);display:flex;align-items:center;justify-content:space-between;">
                        <div style="display:flex;align-items:center;gap:8px;">
                            <span style="font-size:14px;">⌨️</span>
                            <span style="font-size:13px;font-weight:700;color:white;font-family:'Space Grotesk',sans-serif;">Scorciatoie da Tastiera</span>
                        </div>
                        <button onclick="document.getElementById('keyboard-shortcuts-modal').remove()" style="width:24px;height:24px;border-radius:6px;border:1px solid rgba(255,255,255,0.1);background:rgba(255,255,255,0.05);color:rgba(255,255,255,0.4);cursor:pointer;font-size:12px;display:flex;align-items:center;justify-content:center;">&times;</button>
                    </div>
                    <div style="padding:8px 12px;max-height:400px;overflow-y:auto;">
                        ${shortcuts.map(s => `
                            <div style="display:flex;align-items:center;justify-content:space-between;padding:8px 8px;border-radius:8px;transition:background 0.15s;" onmouseenter="this.style.background='rgba(255,255,255,0.04)'" onmouseleave="this.style.background='transparent'">
                                <span style="font-size:12px;color:rgba(255,255,255,0.6);font-weight:500;">${s.desc}</span>
                                <kbd style="font-size:10px;font-weight:700;color:rgba(255,255,255,0.5);background:rgba(255,255,255,0.08);border:1px solid rgba(255,255,255,0.1);padding:3px 8px;border-radius:6px;font-family:'Space Grotesk',monospace;letter-spacing:0.5px;">${s.keys}</kbd>
                            </div>
                        `).join('')}
                    </div>
                    <div style="padding:12px 20px;border-top:1px solid rgba(255,255,255,0.06);text-align:center;">
                        <span style="font-size:10px;color:rgba(255,255,255,0.25);font-weight:500;">Premi <kbd style="background:rgba(255,255,255,0.08);padding:2px 6px;border-radius:4px;font-size:9px;border:1px solid rgba(255,255,255,0.1);">Esc</kbd> per chiudere</span>
                    </div>
                </div>
            `;
            document.body.appendChild(modal);
        }
        // ===== GLOBAL KEYBOARD SHORTCUTS =====
        document.addEventListener('keydown', e => {
            // Don't fire shortcuts when typing in inputs
            const tag = document.activeElement?.tagName?.toLowerCase();
            const isEditable = tag === 'input' || tag === 'textarea' || tag === 'select' || document.activeElement?.isContentEditable;

            // ⌘/ — Show keyboard shortcuts
            if ((e.metaKey || e.ctrlKey) && e.key === '/') {
                e.preventDefault();
                showKeyboardShortcuts();
                return;
            }

            // Escape — Close modals/overlays
            if (e.key === 'Escape') {
                document.getElementById('keyboard-shortcuts-modal')?.remove();
                // Close quick actions dropdown
                const qadd = document.getElementById('quick-actions-dropdown');
                if (qadd && !qadd.classList.contains('hidden')) {
                    qadd.classList.add('hidden', 'opacity-0', '-translate-y-2');
                }
                // Close calendar dropdown
                const caldd = document.getElementById('calendar-dropdown');
                if (caldd && !caldd.classList.contains('hidden')) {
                    caldd.classList.add('opacity-0', '-translate-y-2');
                    setTimeout(() => caldd.classList.add('hidden'), 150);
                }
                return;
            }

            // ⌘B — Toggle sidebar
            if ((e.metaKey || e.ctrlKey) && e.key === 'b') {
                e.preventDefault();
                const sidebarBtn = document.getElementById('sidebar-toggle-btn');
                if (sidebarBtn) sidebarBtn.click();
                return;
            }

            // ⌘N — New element (open quick actions)
            if ((e.metaKey || e.ctrlKey) && e.key === 'n') {
                e.preventDefault();
                toggleQuickActions();
                return;
            }

            // F11 — Fullscreen toggle
            if (e.key === 'F11') {
                e.preventDefault();
                toggleFullscreen();
                return;
            }

            // Skip number navigation if typing
            if (isEditable) return;

            // 1-5 — Page navigation
            const navMap = { '1': 'dashboard', '2': 'inbox', '3': 'clients', '4': 'documents', '5': 'invoices' };
            if (navMap[e.key] && !e.metaKey && !e.ctrlKey && !e.altKey) {
                e.preventDefault();
                if (window.router) router.load(navMap[e.key]);
                return;
            }
        });

        // --- Fullscreen Toggle ---
        function toggleFullscreen() {
            if (!document.fullscreenElement) {
                document.documentElement.requestFullscreen().catch(() => { });
            } else {
                document.exitFullscreen().catch(() => { });
            }
        }
        document.addEventListener('fullscreenchange', () => {
            const icon = document.getElementById('fullscreen-icon');
            if (icon) {
                icon.setAttribute('data-lucide', document.fullscreenElement ? 'minimize' : 'maximize');
                if (typeof lucide !== 'undefined') lucide.createIcons();
            }
        });

        // ===== MINI CALENDAR DROPDOWN =====
        let calendarCurrentMonth = new Date().getMonth();
        let calendarCurrentYear = new Date().getFullYear();
        let calendarSelectedDay = null;
        let calendarTasksCache = {};

        function toggleCalendarDropdown() {
            const dd = document.getElementById('calendar-dropdown');
            if (!dd) return;
            const isOpen = !dd.classList.contains('hidden');
            if (isOpen) {
                dd.classList.add('opacity-0', '-translate-y-2');
                setTimeout(() => dd.classList.add('hidden'), 150);
            } else {
                dd.classList.remove('hidden');
                requestAnimationFrame(() => dd.classList.remove('opacity-0', '-translate-y-2'));
                renderCalendar();
                loadCalendarTasks();
                if (typeof lucide !== 'undefined') lucide.createIcons();
            }
        }
        document.addEventListener('click', e => {
            const w = document.getElementById('calendar-wrapper');
            const dd = document.getElementById('calendar-dropdown');
            if (w && dd && !w.contains(e.target) && !dd.classList.contains('hidden')) {
                dd.classList.add('opacity-0', '-translate-y-2');
                setTimeout(() => dd.classList.add('hidden'), 150);
            }
        });

        function calendarNav(dir) {
            calendarCurrentMonth += dir;
            if (calendarCurrentMonth > 11) { calendarCurrentMonth = 0; calendarCurrentYear++; }
            if (calendarCurrentMonth < 0) { calendarCurrentMonth = 11; calendarCurrentYear--; }
            renderCalendar();
            loadCalendarTasks();
        }

        function renderCalendar() {
            const months = ['Gennaio', 'Febbraio', 'Marzo', 'Aprile', 'Maggio', 'Giugno', 'Luglio', 'Agosto', 'Settembre', 'Ottobre', 'Novembre', 'Dicembre'];
            const label = document.getElementById('calendar-month-label');
            if (label) label.textContent = `${months[calendarCurrentMonth]} ${calendarCurrentYear}`;

            const grid = document.getElementById('calendar-grid');
            if (!grid) return;
            grid.innerHTML = '';

            const firstDay = new Date(calendarCurrentYear, calendarCurrentMonth, 1);
            let startDay = firstDay.getDay() - 1; // Monday = 0
            if (startDay < 0) startDay = 6;

            const daysInMonth = new Date(calendarCurrentYear, calendarCurrentMonth + 1, 0).getDate();
            const today = new Date();
            const isCurrentMonth = today.getMonth() === calendarCurrentMonth && today.getFullYear() === calendarCurrentYear;

            // Empty cells before first day
            for (let i = 0; i < startDay; i++) {
                grid.innerHTML += `<span class="w-8 h-8"></span>`;
            }

            for (let d = 1; d <= daysInMonth; d++) {
                const isToday = isCurrentMonth && d === today.getDate();
                const isSelected = calendarSelectedDay === d;
                const dateKey = `${calendarCurrentYear}-${String(calendarCurrentMonth + 1).padStart(2, '0')}-${String(d).padStart(2, '0')}`;
                const hasTasks = calendarTasksCache[dateKey] && calendarTasksCache[dateKey].length > 0;

                let cls = 'w-8 h-8 rounded-lg text-[11px] font-medium cursor-pointer transition-all flex items-center justify-center relative ';
                if (isSelected) cls += 'bg-cyan-500 text-white font-bold ';
                else if (isToday) cls += 'bg-white/10 text-cyan-400 font-bold ring-1 ring-cyan-500/40 ';
                else cls += 'text-white/50 hover:bg-white/8 hover:text-white/80 ';

                const dot = hasTasks ? `<span class="absolute bottom-0.5 w-1 h-1 rounded-full bg-cyan-400"></span>` : '';
                grid.innerHTML += `<button class="${cls}" onclick="selectCalendarDay(${d})">${d}${dot}</button>`;
            }
        }

        function selectCalendarDay(day) {
            calendarSelectedDay = day;
            renderCalendar();
            const dateKey = `${calendarCurrentYear}-${String(calendarCurrentMonth + 1).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
            const dateLabel = document.getElementById('calendar-selected-date');
            if (dateLabel) dateLabel.textContent = `${day}/${calendarCurrentMonth + 1}/${calendarCurrentYear}`;
            renderCalendarTasks(dateKey);
        }

        async function loadCalendarTasks() {
            try {
                const studioId = window.DbHelper?.getStudioId();
                if (!studioId) return;
                const db = firebase.firestore();
                const start = new Date(calendarCurrentYear, calendarCurrentMonth, 1);
                const end = new Date(calendarCurrentYear, calendarCurrentMonth + 1, 0, 23, 59, 59);

                const snap = await db.collection('studi').doc(studioId).collection('scadenze')
                    .where('dataScadenza', '>=', firebase.firestore.Timestamp.fromDate(start))
                    .where('dataScadenza', '<=', firebase.firestore.Timestamp.fromDate(end))
                    .get();

                calendarTasksCache = {};
                snap.forEach(doc => {
                    const d = doc.data();
                    const ts = d.dataScadenza?.toDate?.() || new Date(d.dataScadenza);
                    const key = `${ts.getFullYear()}-${String(ts.getMonth() + 1).padStart(2, '0')}-${String(ts.getDate()).padStart(2, '0')}`;
                    if (!calendarTasksCache[key]) calendarTasksCache[key] = [];
                    calendarTasksCache[key].push({ id: doc.id, ...d });
                });
                renderCalendar(); // Re-render to show task dots

                // Auto-select today
                const today = new Date();
                if (today.getMonth() === calendarCurrentMonth && today.getFullYear() === calendarCurrentYear) {
                    selectCalendarDay(today.getDate());
                }
            } catch (err) {
                console.warn('Calendar tasks load:', err);
            }
        }

        const collaboratorColors = ['bg-blue-500', 'bg-emerald-500', 'bg-violet-500', 'bg-amber-500', 'bg-rose-500', 'bg-cyan-500', 'bg-pink-500', 'bg-indigo-500'];

        function renderCalendarTasks(dateKey) {
            const list = document.getElementById('calendar-tasks-list');
            if (!list) return;
            const tasks = calendarTasksCache[dateKey] || [];

            if (tasks.length === 0) {
                list.innerHTML = `<div class="text-center py-4">
                    <i data-lucide="calendar-check" class="w-5 h-5 text-white/15 mx-auto mb-1"></i>
                    <span class="text-[10px] text-white/25 block">Nessuna scadenza</span>
                </div>`;
                if (typeof lucide !== 'undefined') lucide.createIcons();
                return;
            }

            // Group by collaborator
            const byCollab = {};
            tasks.forEach(t => {
                const name = t.assegnatoA || t.collaboratore || 'Non assegnato';
                if (!byCollab[name]) byCollab[name] = [];
                byCollab[name].push(t);
            });

            let html = '';
            let colorIdx = 0;
            for (const [name, collabTasks] of Object.entries(byCollab)) {
                const color = collaboratorColors[colorIdx % collaboratorColors.length];
                const initials = name.split(' ').map(w => w[0]).join('').toUpperCase().slice(0, 2);

                html += `<div class="mb-2">
                    <div class="flex items-center gap-2 mb-1">
                        <div class="w-5 h-5 rounded-full ${color} flex items-center justify-center">
                            <span class="text-[7px] font-bold text-white">${initials}</span>
                        </div>
                        <span class="text-[10px] font-bold text-white/60">${name}</span>
                        <span class="text-[8px] text-white/25 ml-auto">${collabTasks.length}</span>
                    </div>`;

                collabTasks.forEach(t => {
                    const statusColor = t.stato === 'completato' ? 'bg-emerald-500' : t.stato === 'in_corso' ? 'bg-amber-500' : 'bg-white/20';
                    html += `<div class="flex items-center gap-2 pl-7 py-0.5">
                        <span class="w-1.5 h-1.5 rounded-full ${statusColor} shrink-0"></span>
                        <span class="text-[10px] text-white/50 truncate">${t.descrizione || t.titolo || t.tipo || 'Attività'}</span>
                    </div>`;
                });
                html += `</div>`;
                colorIdx++;
            }

            list.innerHTML = html;
        }

        // ===== SKELETON LOADING SYSTEM =====
        window.SkeletonLoader = {
            inject: function (containerId) {
                const container = document.getElementById(containerId);
                if (!container) return;
                container.innerHTML = `
                <div class="animate-pulse p-6 space-y-6">
                    <!-- Top Stats Row -->
                    <div class="grid grid-cols-4 gap-4">
                        <div class="h-24 rounded-xl bg-slate-200/60"></div>
                        <div class="h-24 rounded-xl bg-slate-200/60"></div>
                        <div class="h-24 rounded-xl bg-slate-200/60"></div>
                        <div class="h-24 rounded-xl bg-slate-200/60"></div>
                    </div>
                    <!-- Toolbar -->
                    <div class="flex items-center gap-3">
                        <div class="h-9 w-48 rounded-lg bg-slate-200/60"></div>
                        <div class="h-9 w-24 rounded-lg bg-slate-200/60"></div>
                        <div class="ml-auto h-9 w-32 rounded-lg bg-slate-200/60"></div>
                    </div>
                    <!-- Table Header -->
                    <div class="flex items-center gap-4 px-4 py-3 bg-slate-100/80 rounded-t-xl">
                        <div class="h-3 w-6 rounded bg-slate-200/80"></div>
                        <div class="h-3 w-32 rounded bg-slate-200/80"></div>
                        <div class="h-3 w-24 rounded bg-slate-200/80 ml-auto"></div>
                        <div class="h-3 w-20 rounded bg-slate-200/80"></div>
                        <div class="h-3 w-16 rounded bg-slate-200/80"></div>
                    </div>
                    <!-- Table Rows -->
                    ${Array(6).fill('').map(() => `
                    <div class="flex items-center gap-4 px-4 py-4 border-b border-slate-100/60">
                        <div class="h-4 w-4 rounded bg-slate-200/50"></div>
                        <div class="h-8 w-8 rounded-full bg-slate-200/60"></div>
                        <div class="flex-1 space-y-2">
                            <div class="h-3 w-3/5 rounded bg-slate-200/60"></div>
                            <div class="h-2 w-2/5 rounded bg-slate-200/40"></div>
                        </div>
                        <div class="h-5 w-16 rounded-full bg-slate-200/50"></div>
                        <div class="h-3 w-20 rounded bg-slate-200/40"></div>
                        <div class="h-7 w-7 rounded bg-slate-200/40"></div>
                    </div>`).join('')}
                </div>
                <style>
                    @keyframes skeletonShimmer {
                        0% { background-position: -200% 0; }
                        100% { background-position: 200% 0; }
                    }
                    .animate-pulse > div > div,
                    .animate-pulse > div {
                        background-image: linear-gradient(90deg, transparent 25%, rgba(255,255,255,0.4) 50%, transparent 75%);
                        background-size: 200% 100%;
                        animation: skeletonShimmer 1.5s ease-in-out infinite;
                    }
                </style>`;
            }
        };

    </script>


    <!-- ===== GLOBAL SEARCH — Command Palette Overlay ===== -->
    <div id="gs-overlay" class="gs-overlay hidden">
        <div id="gs-palette" class="gs-palette">
            <!-- Search Input -->
            <div class="gs-input-wrap">
                <svg class="gs-input-icon" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor"
                    stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                    <circle cx="11" cy="11" r="8" />
                    <line x1="21" y1="21" x2="16.65" y2="16.65" />
                </svg>
                <input type="text" id="gs-input" placeholder="Cerca clienti, email, documenti, scadenze, fatture..."
                    oninput="GlobalSearch.handleInput(this.value)" autocomplete="off" spellcheck="false">
                <kbd class="gs-input-kbd">ESC</kbd>
            </div>
            <!-- Results -->
            <div id="gs-results" class="gs-results"></div>
        </div>
    </div>
    <!-- Invisible reCAPTCHA container for Firebase Phone Auth (2FA) -->
    <div id="recaptcha-container-2fa"></div>

    <!-- [REMOVED] Driver.js + Onboarding Engine — replaced by unified OnboardingWizard -->

    <!-- ── Calendar Sub-Sidebar Controller ── -->
    <script>
        const CalSubnav = {
            _open: false,
            _currentSub: null,
            _pendingView: null,
            _closeTimer: null,

            toggle() {
                this._open ? this.close() : this.open();
            },

            open() {
                clearTimeout(this._closeTimer);
                const panel = document.getElementById('cal-subnav');
                const backdrop = document.getElementById('cal-subnav-backdrop');
                const btn = document.getElementById('nav-flows');
                if (!panel || this._open) return;
                this._open = true;
                panel.classList.add('open');
                panel.setAttribute('aria-hidden', 'false');
                if (backdrop) backdrop.classList.add('open');
                if (btn) btn.classList.add('sub-open');
                this._syncActiveOnOpen();
            },

            close() {
                clearTimeout(this._closeTimer);
                const panel = document.getElementById('cal-subnav');
                const backdrop = document.getElementById('cal-subnav-backdrop');
                const btn = document.getElementById('nav-flows');
                if (!panel) return;
                this._open = false;
                panel.classList.remove('open');
                panel.setAttribute('aria-hidden', 'true');
                if (backdrop) backdrop.classList.remove('open');
                if (btn) btn.classList.remove('sub-open');
            },

            scheduleClose() {
                clearTimeout(this._closeTimer);
                this._closeTimer = setTimeout(() => this.close(), 400);
            },

            cancelClose() {
                clearTimeout(this._closeTimer);
            },

            navigate(page) {
                this.close();
                this._highlightActive(page);
                router.load(page);
            },

            navigateView(page, view) {
                this.close();
                this._pendingView = view;
                this._highlightActiveView(view);
                if (this._currentSub === 'flows' && typeof ScadenziarioModule !== 'undefined') {
                    ScadenziarioModule.switchView(view);
                    return;
                }
                router.load(page);
            },

            applyPendingView() {
                if (this._pendingView && typeof ScadenziarioModule !== 'undefined') {
                    ScadenziarioModule.switchView(this._pendingView);
                    this._pendingView = null;
                }
            },

            _syncActiveOnOpen() {
                document.querySelectorAll('.cal-subnav-item').forEach(el => el.classList.remove('active'));
                if (this._currentSub === 'flows' && typeof ScadenziarioModule !== 'undefined') {
                    const view = ScadenziarioModule.currentView || 'timeline';
                    const match = document.querySelector(`.cal-subnav-item[data-view="${view}"]`);
                    if (match) match.classList.add('active');
                }
            },

            _highlightActive(page) {
                setTimeout(() => {
                    document.querySelectorAll('#main-sidebar .nav-item').forEach(el => el.classList.remove('active'));
                    const navFlows = document.getElementById('nav-flows');
                    if (navFlows) navFlows.classList.add('active');
                    document.querySelectorAll('.cal-subnav-item').forEach(el => el.classList.remove('active'));
                    this._currentSub = page;
                }, 50);
            },

            _highlightActiveView(view) {
                setTimeout(() => {
                    document.querySelectorAll('#main-sidebar .nav-item').forEach(el => el.classList.remove('active'));
                    const navFlows = document.getElementById('nav-flows');
                    if (navFlows) navFlows.classList.add('active');
                    document.querySelectorAll('.cal-subnav-item').forEach(el => el.classList.remove('active'));
                    const match = document.querySelector(`.cal-subnav-item[data-view="${view}"]`);
                    if (match) match.classList.add('active');
                    this._currentSub = 'flows';
                }, 50);
            },

            syncActive(page) {
                const isCalPage = page === 'flows' || page === 'appointments';
                if (!isCalPage) { this._currentSub = null; return; }
                const navFlows = document.getElementById('nav-flows');
                if (navFlows) navFlows.classList.add('active');
                document.querySelectorAll('.cal-subnav-item').forEach(el => el.classList.remove('active'));
                this._currentSub = page;
                if (page === 'flows') this.applyPendingView();
            }
        };

        // ── Hover wiring ──
        (function () {
            const navBtn = document.getElementById('nav-flows');
            const panel = document.getElementById('cal-subnav');
            const backdrop = document.getElementById('cal-subnav-backdrop');
            if (!navBtn || !panel) return;

            navBtn.addEventListener('mouseenter', () => {
                CalSubnav.cancelClose();
                CalSubnav.open();
            });

            navBtn.addEventListener('mouseleave', (e) => {
                // Don't schedule close if mouse is going to the panel (or its ::before bridge)
                const to = e.relatedTarget;
                if (to && (panel === to || panel.contains(to))) return;
                CalSubnav.scheduleClose();
            });

            panel.addEventListener('mouseenter', () => {
                CalSubnav.cancelClose();
            });

            panel.addEventListener('mouseleave', (e) => {
                const to = e.relatedTarget;
                if (to && (navBtn === to || navBtn.contains(to))) return;
                CalSubnav.scheduleClose();
            });

            // Click navigates to scadenziario default view
            navBtn.addEventListener('click', (e) => {
                e.preventDefault();
                CalSubnav.navigateView('flows', 'timeline');
            });

            if (backdrop) {
                backdrop.addEventListener('click', () => CalSubnav.close());
            }
        })();

        // Close on Escape
        document.addEventListener('keydown', e => {
            if (e.key === 'Escape' && CalSubnav._open) CalSubnav.close();
        });
    </script>
</body>

</html>