/**
 * Dashboard Utilities
 * Centralizes common logic for Mobile Menu, Notifications, Theme Switcher, and Modals.
 * 
 * Included in: dashboard-footer.php
 */

// ============================================
// MOBILE MENU (Bottom Sheet)
// ============================================

function toggleMobileMenu() {
    const overlay = document.getElementById('mobileMenuOverlay');
    if (!overlay) return;

    overlay.classList.toggle('active');

    // Prevent body scroll when menu is open
    if (overlay.classList.contains('active')) {
        document.body.style.overflow = 'hidden';
        // Focus search input
        setTimeout(() => {
            const searchInput = document.getElementById('menuSearchInput');
            if (searchInput) searchInput.focus();
        }, 300);
    } else {
        document.body.style.overflow = '';
        // Clear search input on close
        const searchInput = document.getElementById('menuSearchInput');
        if (searchInput) {
            searchInput.value = '';
            filterMenuItems('');
        }
    }
}

function filterMenuItems(searchValue) {
    const search = searchValue.toLowerCase().trim();
    const cards = document.querySelectorAll('.nubank-card');
    const listItems = document.querySelectorAll('.nubank-list-item');
    const sections = document.querySelectorAll('.nubank-section');

    // Filter cards
    cards.forEach(card => {
        const text = card.getAttribute('data-search') || '';
        if (!search) {
            card.classList.remove('hidden');
        } else {
            card.classList.toggle('hidden', !text.includes(search));
        }
    });

    // Filter list items
    listItems.forEach(item => {
        const text = item.getAttribute('data-search') || '';
        if (!search) {
            item.classList.remove('hidden');
        } else {
            item.classList.toggle('hidden', !text.includes(search));
        }
    });

    // Hide empty sections
    sections.forEach(section => {
        const visibleItems = section.querySelectorAll('.nubank-card:not(.hidden), .nubank-list-item:not(.hidden)');
        section.classList.toggle('hidden', visibleItems.length === 0);
    });
}

// Close menu when clicking on overlay
document.addEventListener('DOMContentLoaded', function() {
    const overlay = document.getElementById('mobileMenuOverlay');
    if (overlay) {
        overlay.addEventListener('click', function(e) {
            if (e.target === overlay) {
                toggleMobileMenu();
            }
        });
    }
});

// ============================================
// NOTIFICATIONS
// ============================================

function toggleNotifications() {
    const dropdown = document.getElementById('notificationsDropdown');
    if (!dropdown) return;

    dropdown.classList.toggle('open');
    
    // Close on click outside
    if (dropdown.classList.contains('open')) {
        setTimeout(() => {
            document.addEventListener('click', closeNotificationsOnClickOutside);
        }, 10);
    }
}

function closeNotificationsOnClickOutside(e) {
    const wrapper = document.querySelector('.notifications-wrapper');
    const dropdown = document.getElementById('notificationsDropdown');
    
    if (wrapper && !wrapper.contains(e.target)) {
        if (dropdown) dropdown.classList.remove('open');
        document.removeEventListener('click', closeNotificationsOnClickOutside);
    }
}

function markAsRead(id) {
    fetch('/api/notifications.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'mark_read', id: id })
    });
}

function markAllAsRead() {
    fetch('/api/notifications.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'mark_all_read' })
    }).then(() => {
        // Update UI
        document.querySelectorAll('.notification-item.unread').forEach(item => {
            item.classList.remove('unread');
        });
        const badge = document.querySelector('.notification-badge');
        if (badge) badge.remove();
        
        const btn = document.querySelector('.notifications-btn');
        if (btn) btn.classList.remove('has-unread');
        
        const markAllBtn = document.querySelector('.mark-all-read');
        if (markAllBtn) markAllBtn.remove();
    });
}

function clearAllNotifications() {
    if (!confirm('Tem certeza que deseja limpar TODAS as notificações? Esta ação não pode ser desfeita.')) return;
    
    fetch('/api/notifications.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ action: 'clear_all' })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            // Clear list
            const list = document.querySelector('.notifications-list');
            if (list) {
                list.innerHTML = '<div class="notifications-empty"><iconify-icon icon="solar:bell-off-bold"></iconify-icon><p>Nenhuma notificação</p></div>';
            }
            // Remove badge
            const badge = document.querySelector('.notification-badge');
            if (badge) badge.remove();
            
            const btn = document.querySelector('.notifications-btn');
            if (btn) btn.classList.remove('has-unread');
            
            // Hide action buttons
            const markAllBtn = document.querySelector('.mark-all-read');
            if (markAllBtn) markAllBtn.remove();
            
            const clearBtn = document.querySelector('.clear-all-btn');
            if (clearBtn) clearBtn.remove();
        }
    });
}

// ============================================
// THEME SWITCHER
// ============================================

(function() {
    // Apply theme from global variable (DB) or localStorage
    const dbTheme = window.userThemeFromDB || null;
    const localTheme = localStorage.getItem('montaloja-theme');
    const currentTheme = dbTheme || localTheme || 'dark';
    
    if (dbTheme && dbTheme !== localTheme) {
        localStorage.setItem('montaloja-theme', dbTheme);
    }
    
    document.documentElement.setAttribute('data-theme', currentTheme);

    // Update buttons
    setTimeout(() => {
        document.querySelectorAll('.theme-btn').forEach(btn => {
            btn.classList.remove('active');
            if (btn.dataset.theme === currentTheme) {
                btn.classList.add('active');
            }
        });
    }, 100);
})();

function setTheme(theme) {
    document.documentElement.setAttribute('data-theme', theme);
    localStorage.setItem('montaloja-theme', theme);

    document.querySelectorAll('.theme-btn').forEach(btn => {
        btn.classList.remove('active');
        if (btn.dataset.theme === theme) {
            btn.classList.add('active');
        }
    });
    
    // Save to DB
    fetch('/api/theme.php?action=set&theme=' + encodeURIComponent(theme), {
        method: 'GET',
        credentials: 'include'
    }).then(response => response.json())
      .then(data => {
          if (data.success) {
              // console.log('Theme saved');
          }
      }).catch(err => {
          // console.log('Error saving theme');
      });
}

if (window.matchMedia) {
    window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
        const currentTheme = localStorage.getItem('montaloja-theme');
        if (currentTheme === 'auto') {
            document.documentElement.setAttribute('data-theme', 'auto');
        }
    });
}

// ============================================
// MODAL UTILS
// ============================================

function closeModal(modalId = null) {
    // If no ID provided, try to find the open one
    const modal = modalId ? document.getElementById(modalId) : document.querySelector('.modal-overlay[style*="display: flex"]');
    
    if (modal) {
        modal.style.display = 'none';
        document.body.style.overflow = '';
    }
}

// Generic escape key handler for modals
document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') {
        const openModal = document.querySelector('.modal-overlay[style*="display: flex"]');
        if (openModal) {
            openModal.style.display = 'none';
            document.body.style.overflow = '';
        }
    }
});

// Close modal on click outside (needs specific listener per modal or a generic global one)
// We add a global click listener to .modal-overlay
document.addEventListener('click', function(e) {
    if (e.target.classList.contains('modal-overlay')) {
        e.target.style.display = 'none';
        document.body.style.overflow = '';
    }
});
