    <?php if (isLoggedIn()): ?>
            </div>
        </main>
    </div>
    <?php endif; ?>

    <script>
        // 手機選單切換
        const mobileMenuBtn = document.getElementById('mobile-menu-btn');
        const closeSidebarBtn = document.getElementById('close-sidebar-btn');
        const sidebar = document.getElementById('sidebar');
        let overlay = null;

        function toggleSidebar() {
            if (window.innerWidth >= 768) return;

            if (sidebar.classList.contains('hidden')) {
                sidebar.classList.remove('hidden');
                sidebar.classList.add('flex');
                overlay = document.createElement('div');
                overlay.className = 'fixed inset-0 bg-black/40 z-40 md:hidden';
                overlay.style.backdropFilter = 'blur(4px)';
                overlay.style.WebkitBackdropFilter = 'blur(4px)';
                overlay.addEventListener('click', toggleSidebar);
                document.body.appendChild(overlay);
                document.body.style.overflow = 'hidden';
            } else {
                sidebar.classList.add('hidden');
                sidebar.classList.remove('flex');
                if (overlay) {
                    overlay.remove();
                    overlay = null;
                }
                document.body.style.overflow = '';
            }
        }

        if (mobileMenuBtn) {
            mobileMenuBtn.addEventListener('click', toggleSidebar);
        }

        if (closeSidebarBtn) {
            closeSidebarBtn.addEventListener('click', toggleSidebar);
        }

        // 視窗 resize 時自動處理
        window.addEventListener('resize', function() {
            if (window.innerWidth >= 768 && sidebar.classList.contains('flex')) {
                sidebar.classList.remove('hidden');
                sidebar.classList.add('md:flex');
            }
            if (window.innerWidth >= 768 && overlay) {
                overlay.remove();
                overlay = null;
                document.body.style.overflow = '';
            }
        });

        // sidebar-active class for current page
        document.querySelectorAll('.sidebar a').forEach(function(link) {
            if (link.href === window.location.href || link.href === window.location.href.split('?')[0]) {
                link.classList.add('sidebar-active');
            }
        });

        // PWA Service Worker 註冊
        if ('serviceWorker' in navigator) {
            window.addEventListener('load', function() {
                navigator.serviceWorker.register('sw.js');
            });
        }
    </script>
</body>
</html>
