document.addEventListener('alpine:init', () => {
    Alpine.store('theme', {
        mode: localStorage.getItem('theme') || 'light',
        
        toggle() {
            this.mode = this.mode === 'light' ? 'dark' : 'light';
            localStorage.setItem('theme', this.mode);
            this.apply();
        },

        apply() {
            document.documentElement.setAttribute('data-bs-theme', this.mode);
        }
    });

    // Apply theme on init
    Alpine.store('theme').apply();

    Alpine.store('sidebar', {
        open: false,

        toggle() {
            this.open = !this.open;
            const sidebar = document.getElementById('sidebar');
            if (this.open) {
                sidebar.classList.add('show');
            } else {
                sidebar.classList.remove('show');
            }
        },
        
        close() {
            this.open = false;
            document.getElementById('sidebar').classList.remove('show');
        }
    });
});

// HTMX Configuration
document.addEventListener('htmx:configRequest', (event) => {
    // Add CSRF token if available (implementation dependent)
    // event.detail.headers['X-CSRF-Token'] = getCsrfToken(); 
});

document.addEventListener('htmx:beforeSwap', (event) => {
    // Handle 401 Unauthorized by redirecting to login
    if (event.detail.xhr.status === 401) {
        window.location.href = '/login';
    }
});

// Mobile helper: Close sidebar on outside click (simple implementation)
document.addEventListener('click', (e) => {
    const sidebar = document.getElementById('sidebar');
    const toggleBtn = document.querySelector('[data-bs-target="#sidebar"]'); // Adjust selector as needed
    
    // Only on mobile
    if (window.innerWidth < 992 && Alpine.store('sidebar').open) {
        if (!sidebar.contains(e.target) && !toggleBtn.contains(e.target)) {
            Alpine.store('sidebar').close();
        }
    }
});
