// Initialize dark mode from localStorage
document.addEventListener('DOMContentLoaded', () => {
    // Check if dark mode was previously enabled
    const darkMode = localStorage.getItem('darkMode') === 'true';
    if (darkMode) {
        document.documentElement.classList.add('dark');
    }
});

// Handle search form submission
document.addEventListener('submit', (e) => {
    if (e.target.matches('form[action*="search"]')) {
        const searchInput = e.target.querySelector('input[name="q"]');
        if (!searchInput.value.trim()) {
            e.preventDefault();
        }
    }
});

// Close mobile menu when clicking outside
document.addEventListener('click', (e) => {
    const mobileMenu = document.querySelector('[x-show="mobileMenuOpen"]');
    const menuButton = document.querySelector('[x-on\\:click="mobileMenuOpen = !mobileMenuOpen"]');
    
    if (mobileMenu && menuButton && !mobileMenu.contains(e.target) && !menuButton.contains(e.target)) {
        const alpineData = mobileMenu._x_dataStack && mobileMenu._x_dataStack[0];
        if (alpineData && alpineData.mobileMenuOpen) {
            alpineData.mobileMenuOpen = false;
        }
    }
});

// Handle flash messages
document.addEventListener('DOMContentLoaded', () => {
    const alerts = document.querySelectorAll('.alert');
    alerts.forEach(alert => {
        setTimeout(() => {
            alert.style.opacity = '0';
            setTimeout(() => alert.remove(), 300);
        }, 5000);
    });
});

// Initialize tooltips
document.addEventListener('DOMContentLoaded', () => {
    const tooltips = document.querySelectorAll('[data-tooltip]');
    tooltips.forEach(tooltip => {
        tooltip.addEventListener('mouseenter', (e) => {
            const text = e.target.getAttribute('data-tooltip');
            const tooltipEl = document.createElement('div');
            tooltipEl.className = 'tooltip bg-gray-900 text-white px-2 py-1 rounded text-sm absolute z-50';
            tooltipEl.textContent = text;
            document.body.appendChild(tooltipEl);
            
            const rect = e.target.getBoundingClientRect();
            tooltipEl.style.top = rect.bottom + 5 + 'px';
            tooltipEl.style.left = rect.left + (rect.width - tooltipEl.offsetWidth) / 2 + 'px';
        });
        
        tooltip.addEventListener('mouseleave', () => {
            const tooltips = document.querySelectorAll('.tooltip');
            tooltips.forEach(t => t.remove());
        });
    });
});

// Handle dropdown menus
document.addEventListener('click', (e) => {
    const dropdowns = document.querySelectorAll('[x-show]');
    dropdowns.forEach(dropdown => {
        if (!dropdown.contains(e.target) && 
            !e.target.matches('[x-on\\:click*="open = !open"]')) {
            const alpineData = dropdown._x_dataStack && dropdown._x_dataStack[0];
            if (alpineData && alpineData.open) {
                alpineData.open = false;
            }
        }
    });
});
