/**
 * MCL Media Control Center — App principale
 */

document.addEventListener('DOMContentLoaded', function() {

    // ============================================================
    // SIDEBAR MOBILE TOGGLE
    // ============================================================

    const mobileToggle = document.getElementById('mobileToggle');
    const sidebar = document.getElementById('sidebar');

    if (mobileToggle && sidebar) {
        mobileToggle.addEventListener('click', function() {
            sidebar.classList.toggle('open');
        });

        // Chiudi sidebar cliccando fuori
        document.addEventListener('click', function(e) {
            if (sidebar.classList.contains('open') && !sidebar.contains(e.target) && !mobileToggle.contains(e.target)) {
                sidebar.classList.remove('open');
            }
        });
    }

    // ============================================================
    // NOTIFICATION DROPDOWN
    // ============================================================

    const bell = document.getElementById('notificationBell');
    const dropdown = document.getElementById('notificationDropdown');

    if (bell && dropdown) {
        bell.addEventListener('click', function(e) {
            e.stopPropagation();
            dropdown.classList.toggle('open');
        });

        document.addEventListener('click', function(e) {
            if (!bell.contains(e.target)) {
                dropdown.classList.remove('open');
            }
        });

        // Segna tutte lette
        const markAllBtn = document.getElementById('markAllRead');
        if (markAllBtn) {
            markAllBtn.addEventListener('click', function(e) {
                e.preventDefault();
                apiPost('api/notifications.php', { action: 'mark_all_read' }).then(() => {
                    document.querySelectorAll('.notification-item').forEach(el => el.remove());
                    const count = document.querySelector('.notification-count');
                    if (count) count.remove();
                    const body = document.querySelector('.notification-dropdown-body');
                    if (body) body.innerHTML = '<div class="notification-empty">Nessuna notifica</div>';
                });
            });
        }
    }

    // ============================================================
    // TASK CHECKBOXES
    // ============================================================

    document.querySelectorAll('.task-check').forEach(function(el) {
        el.addEventListener('click', function() {
            const taskId = this.dataset.id;
            const isDone = this.classList.toggle('done');
            const title = this.nextElementSibling?.querySelector('.task-title');
            if (title) title.classList.toggle('done', isDone);

            apiPost('api/tasks.php', {
                action: 'toggle_status',
                id: taskId,
                status: isDone ? 'done' : 'todo'
            });
        });
    });

    // ============================================================
    // TABS
    // ============================================================

    document.querySelectorAll('.tabs').forEach(function(tabGroup) {
        tabGroup.querySelectorAll('.tab').forEach(function(tab) {
            tab.addEventListener('click', function() {
                tabGroup.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
                this.classList.add('active');

                // Se ha data-target, mostra/nascondi pannello
                const target = this.dataset.target;
                if (target) {
                    const parent = tabGroup.closest('.card') || tabGroup.parentElement;
                    parent.querySelectorAll('[data-tab-panel]').forEach(p => p.style.display = 'none');
                    const panel = parent.querySelector(`[data-tab-panel="${target}"]`);
                    if (panel) panel.style.display = '';
                }
            });
        });
    });

    // ============================================================
    // GLOBAL SEARCH (basico)
    // ============================================================

    const searchInput = document.getElementById('globalSearch');
    if (searchInput) {
        let searchTimeout;
        searchInput.addEventListener('input', function() {
            clearTimeout(searchTimeout);
            searchTimeout = setTimeout(() => {
                const query = this.value.trim();
                if (query.length >= 2) {
                    // Per ora logga — implementeremo la ricerca completa
                    console.log('Ricerca:', query);
                }
            }, 300);
        });
    }

    // ============================================================
    // MODAL
    // ============================================================

    window.openModal = function(id) {
        const overlay = document.getElementById(id);
        if (overlay) overlay.classList.add('open');
    };

    window.closeModal = function(id) {
        const overlay = document.getElementById(id);
        if (overlay) overlay.classList.remove('open');
    };

    // Chiudi modal cliccando overlay
    document.querySelectorAll('.modal-overlay').forEach(function(overlay) {
        overlay.addEventListener('click', function(e) {
            if (e.target === this) this.classList.remove('open');
        });
    });

    // ESC chiude modal
    document.addEventListener('keydown', function(e) {
        if (e.key === 'Escape') {
            document.querySelectorAll('.modal-overlay.open').forEach(m => m.classList.remove('open'));
        }
    });

    console.log('MCL Media Control Center — Inizializzato');
});

// ============================================================
// API HELPERS
// ============================================================

async function apiPost(url, data = {}) {
    data[window.MCL.csrfToken ? 'mcl_csrf' : '_token'] = window.MCL.csrfToken || '';

    const response = await fetch(window.MCL.baseUrl + url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'X-Requested-With': 'XMLHttpRequest',
            'X-CSRF-TOKEN': window.MCL.csrfToken || '',
        },
        body: JSON.stringify(data),
    });

    const result = await response.json();

    if (!response.ok) {
        if (response.status === 401) {
            window.location.href = window.MCL.baseUrl + '?page=login';
            return;
        }
        showToast(result.error || 'Errore', 'error');
        throw new Error(result.error);
    }

    return result;
}

async function apiGet(url) {
    const response = await fetch(window.MCL.baseUrl + url, {
        headers: { 'X-Requested-With': 'XMLHttpRequest' },
    });

    if (!response.ok) {
        if (response.status === 401) {
            window.location.href = window.MCL.baseUrl + '?page=login';
            return;
        }
        throw new Error('Errore API');
    }

    return response.json();
}

// ============================================================
// TOAST NOTIFICATIONS
// ============================================================

function showToast(message, type = 'info', duration = 4000) {
    let container = document.querySelector('.toast-container');
    if (!container) {
        container = document.createElement('div');
        container.className = 'toast-container';
        document.body.appendChild(container);
    }

    const icons = {
        success: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 11.08V12a10 10 0 11-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg>',
        error: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="15" y1="9" x2="9" y2="15"/><line x1="9" y1="9" x2="15" y2="15"/></svg>',
        warning: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>',
        info: '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"/><line x1="12" y1="16" x2="12" y2="12"/><line x1="12" y1="8" x2="12.01" y2="8"/></svg>',
    };

    const toast = document.createElement('div');
    toast.className = `toast ${type}`;
    toast.innerHTML = `${icons[type] || icons.info}<span>${message}</span><button class="toast-close" onclick="this.parentElement.remove()">✕</button>`;
    container.appendChild(toast);

    setTimeout(() => {
        toast.style.opacity = '0';
        toast.style.transform = 'translateX(100%)';
        toast.style.transition = 'all 0.3s ease';
        setTimeout(() => toast.remove(), 300);
    }, duration);
}

// ============================================================
// CONFIRM DIALOG
// ============================================================

function confirmAction(message, callback) {
    if (confirm(message)) callback();
}