// Main JavaScript for Recruitment Portal Admin

document.addEventListener('DOMContentLoaded', () => {
    console.log('Recruitment Portal Admin Initialized');

    // Highlight active nav link based on URL
    const currentPath = window.location.pathname.split('/').pop();
    const navLinks = document.querySelectorAll('.nav-link');

    navLinks.forEach(link => {
        const href = link.getAttribute('href');
        if (href === currentPath || (currentPath === '' && href === 'dashboard.html')) {
            link.classList.add('active');
        } else {
            link.classList.remove('active');
        }
    });

    // Notifications
    setupNotifications();

    // Global Search
    setupGlobalSearch();
});

function setupGlobalSearch() {
    const searchInput = document.querySelector('.search-bar input');
    if (searchInput) {
        searchInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                const query = searchInput.value.trim();
                if (query) {
                    window.location.href = `search.html?q=${encodeURIComponent(query)}`;
                }
            }
        });
    }
}

// Notifications Logic
function setupNotifications() {
    const bellBtn = document.querySelector('.btn-bell');
    if (!bellBtn) return;

    // Add badge element if not exists
    let badge = bellBtn.querySelector('.notification-badge');
    if (!badge) {
        badge = document.createElement('span');
        badge.className = 'notification-badge';
        badge.style.cssText = `
            position: absolute;
            top: -2px;
            right: -2px;
            background: #ef4444;
            color: white;
            font-size: 0.6rem;
            width: 16px;
            height: 16px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            display: none;
        `;
        bellBtn.style.position = 'relative';
        bellBtn.appendChild(badge);
    }

    // Add dropdown container if not exists
    let dropdown = document.getElementById('notification-dropdown');
    if (!dropdown) {
        dropdown = document.createElement('div');
        dropdown.id = 'notification-dropdown';
        dropdown.style.cssText = `
            position: absolute;
            top: 120%;
            right: 0;
            width: 350px;
            background: white;
            border: 1px solid #e2e8f0;
            border-radius: 12px;
            box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.1);
            z-index: 1000;
            display: none;
            overflow: hidden;
            transform-origin: top right;
            transition: all 0.2s ease;
        `;
        // Check if header exists to append, else append to body and position absolute
        const header = document.querySelector('header');
        if (header) {
            // Find the parent container of the bell button to append relative to it if possible
            bellBtn.parentElement.style.position = 'relative'; // Ensure parent is relative
            bellBtn.parentElement.appendChild(dropdown);
        }
    }

    // Toggle Dropdown
    bellBtn.addEventListener('click', (e) => {
        e.stopPropagation();
        const isVisible = dropdown.style.display === 'block';
        dropdown.style.display = isVisible ? 'none' : 'block';
        if (!isVisible) {
            markAllRead(); // Mark read when opening
        }
    });

    // Close on click outside
    document.addEventListener('click', () => {
        if (dropdown) dropdown.style.display = 'none';
    });
    dropdown.addEventListener('click', (e) => e.stopPropagation());

    // Initial Fetch & Poll
    fetchNotifications();
    setInterval(fetchNotifications, 30000); // Poll every 30s
}

function fetchNotifications() {
    console.log('Fetching notifications...');
    const dropdown = document.getElementById('notification-dropdown');

    fetch('api/notifications.php')
        .then(res => res.text()) // Get text first to debug if JSON fails
        .then(text => {
            try {
                const data = JSON.parse(text);
                console.log('Notification data:', data);

                const badge = document.querySelector('.notification-badge');
                // Dropdown might be null if not yet created? No, created in setup.

                if (data.unread_count > 0) {
                    badge.textContent = data.unread_count > 9 ? '9+' : data.unread_count;
                    badge.style.display = 'flex';
                } else {
                    badge.style.display = 'none';
                }

                // Render list
                if (dropdown) {
                    let html = `
                        <div style="padding: 16px; border-bottom: 1px solid #f1f5f9; display: flex; justify-content: space-between; align-items: center;">
                            <h6 style="margin: 0; font-weight: 600; color: #0f172a; font-size: 0.95rem;">Notifications</h6>
                        </div>
                        <div style="max-height: 350px; overflow-y: auto;">
                    `;

                    if (data.data && data.data.length > 0) {
                        html += data.data.map(n => `
                            <a href="notifications.html" style="text-decoration: none; display: block;">
                                <div style="padding: 16px; border-bottom: 1px solid #f8fafc; cursor: pointer; transition: background 0.2s;" 
                                     onmouseenter="this.style.background='#f8fafc'" 
                                     onmouseleave="this.style.background='white'">
                                    <div style="display: flex; gap: 12px; align-items: start;">
                                        <div style="min-width: 8px; height: 8px; background: #3b82f6; border-radius: 50%; margin-top: 6px;"></div>
                                        <div>
                                            <div style="font-size: 0.875rem; color: #334155; line-height: 1.4; margin-bottom: 4px;">${n.message}</div>
                                            <div style="font-size: 0.75rem; color: #94a3b8;">${new Date(n.created_at).toLocaleString()}</div>
                                        </div>
                                    </div>
                                </div>
                            </a>
                        `).join('');
                    } else {
                        html += `
                            <div style="padding: 40px 20px; text-align: center;">
                                <div style="font-size: 2rem; color: #cbd5e1; margin-bottom: 12px;"><i class="fa-regular fa-bell-slash"></i></div>
                                <div style="font-size: 0.9rem; color: #64748b; font-weight: 500;">No notifications</div>
                            </div>
                        `;
                    }

                    html += `</div>`; // Close scroll container
                    // Footer
                    html += `
                        <div style="padding: 12px; text-align: center; border-top: 1px solid #f1f5f9; background: #f8fafc;">
                            <a href="notifications.html" style="font-size: 0.8rem; font-weight: 500; color: #3b82f6; text-decoration: none;">View All Notifications</a>
                        </div>
                    `;

                    dropdown.innerHTML = html;
                }
            } catch (e) {
                console.error('Invalid JSON:', text);
            }
        })
        .catch(err => console.error('Error fetching notifications:', err));
}

function markAllRead() {
    fetch('api/notifications.php', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ action: 'mark_read' })
    }).then(() => {
        const badge = document.querySelector('.notification-badge');
        if (badge) badge.style.display = 'none';
    });
}

// Global Logout function
function logoutUser() {
    if (typeof logout === 'function') {
        logout(); // From auth.js
    } else {
        // Fallback if auth.js checkAuth didn't load (unlikely if included)
        fetch('api/auth.php?action=logout', { method: 'POST' })
            .then(() => window.location.href = 'login.html');
    }
}
