// Swizzle Events - Main JavaScript

document.addEventListener('DOMContentLoaded', async function() {
    // Load includes first
    await loadIncludes();

    // Sidebar Toggle
    initSidebar();

    // Dropdowns
    initDropdowns();

    // Modals
    initModals();

    // Tabs
    initTabs();

    // File Upload Preview
    initFileUpload();

    // Toast Notifications
    window.showToast = showToast;
});

// Load HTML Includes
async function loadIncludes() {
    const includes = document.querySelectorAll('[data-include]');

    for (const el of includes) {
        const file = el.getAttribute('data-include');
        const activePage = el.getAttribute('data-active-page');

        try {
            const response = await fetch(`../assets/includes/${file}`);
            if (response.ok) {
                const html = await response.text();
                el.innerHTML = html;

                // Set active page in sidebar
                if (activePage) {
                    const activeLink = el.querySelector(`[data-page="${activePage}"]`);
                    if (activeLink) {
                        activeLink.classList.add('active');
                    }
                }
            }
        } catch (error) {
            console.error(`Failed to load include: ${file}`, error);
        }
    }
}

// Sidebar Toggle
function initSidebar() {
    const sidebarToggle = document.getElementById('sidebarToggle');
    const sidebar = document.getElementById('sidebar');
    const sidebarOverlay = document.getElementById('sidebarOverlay');

    if (sidebarToggle && sidebar) {
        sidebarToggle.addEventListener('click', () => {
            sidebar.classList.toggle('open');
            if (sidebarOverlay) {
                sidebarOverlay.classList.toggle('hidden');
            }
        });
    }

    if (sidebarOverlay && sidebar) {
        sidebarOverlay.addEventListener('click', () => {
            sidebar.classList.remove('open');
            sidebarOverlay.classList.add('hidden');
        });
    }
}

// Dropdowns
function initDropdowns() {
    const dropdownTriggers = document.querySelectorAll('[data-dropdown]');

    dropdownTriggers.forEach(trigger => {
        const dropdownId = trigger.getAttribute('data-dropdown');
        const dropdown = document.getElementById(dropdownId);

        if (dropdown) {
            trigger.addEventListener('click', (e) => {
                e.stopPropagation();

                // Close other dropdowns
                document.querySelectorAll('.dropdown-menu.active').forEach(menu => {
                    if (menu.id !== dropdownId) {
                        menu.classList.remove('active');
                    }
                });

                dropdown.classList.toggle('active');
            });
        }
    });

    // Close dropdowns when clicking outside
    document.addEventListener('click', () => {
        document.querySelectorAll('.dropdown-menu.active').forEach(menu => {
            menu.classList.remove('active');
        });
    });
}

// Modals
function initModals() {
    // Open modal triggers
    const modalTriggers = document.querySelectorAll('[data-modal]');

    modalTriggers.forEach(trigger => {
        const modalId = trigger.getAttribute('data-modal');
        const modal = document.getElementById(modalId);

        if (modal) {
            trigger.addEventListener('click', () => {
                modal.classList.add('active');
                document.body.style.overflow = 'hidden';
            });
        }
    });

    // Close modal triggers
    const modalCloses = document.querySelectorAll('[data-modal-close]');

    modalCloses.forEach(close => {
        close.addEventListener('click', () => {
            const modal = close.closest('.modal-overlay');
            if (modal) {
                modal.classList.remove('active');
                document.body.style.overflow = '';
            }
        });
    });

    // Close on overlay click
    document.querySelectorAll('.modal-overlay').forEach(overlay => {
        overlay.addEventListener('click', (e) => {
            if (e.target === overlay) {
                overlay.classList.remove('active');
                document.body.style.overflow = '';
            }
        });
    });
}

// Tabs
function initTabs() {
    const tabContainers = document.querySelectorAll('[data-tabs]');

    tabContainers.forEach(container => {
        const tabs = container.querySelectorAll('.tab');
        const tabContents = document.querySelectorAll('[data-tab-content]');

        tabs.forEach(tab => {
            tab.addEventListener('click', () => {
                const target = tab.getAttribute('data-tab');

                // Update active tab
                tabs.forEach(t => t.classList.remove('active'));
                tab.classList.add('active');

                // Show target content
                tabContents.forEach(content => {
                    if (content.getAttribute('data-tab-content') === target) {
                        content.classList.remove('hidden');
                    } else {
                        content.classList.add('hidden');
                    }
                });
            });
        });
    });
}

// File Upload Preview
function initFileUpload() {
    const fileInputs = document.querySelectorAll('input[type="file"][data-preview]');

    fileInputs.forEach(input => {
        const previewId = input.getAttribute('data-preview');
        const preview = document.getElementById(previewId);

        if (preview) {
            input.addEventListener('change', (e) => {
                const file = e.target.files[0];
                if (file) {
                    const reader = new FileReader();
                    reader.onload = (e) => {
                        preview.src = e.target.result;
                        preview.classList.remove('hidden');
                    };
                    reader.readAsDataURL(file);
                }
            });
        }
    });
}

// Copy Registration URL
function copyRegistrationUrl(eventId = null) {
    // Get the base path by going up from current location
    const currentPath = window.location.pathname;
    const basePath = currentPath.substring(0, currentPath.lastIndexOf('/account/'));
    const origin = window.location.origin;

    const registrationUrl = eventId
        ? `${origin}${basePath}/public/register.html?event=${eventId}`
        : `${origin}${basePath}/public/register.html`;

    navigator.clipboard.writeText(registrationUrl).then(() => {
        showToast('Registration URL copied to clipboard!', 'success');
    }).catch(() => {
        // Fallback for older browsers
        const textArea = document.createElement('textarea');
        textArea.value = registrationUrl;
        document.body.appendChild(textArea);
        textArea.select();
        try { document.execCommand('copy'); } catch(e) {}
        document.body.removeChild(textArea);
        showToast('Registration URL copied to clipboard!', 'success');
    });
}

// Make copyRegistrationUrl globally available
window.copyRegistrationUrl = copyRegistrationUrl;

// Toast Notifications
function showToast(message, type = 'success') {
    // Remove existing toasts
    document.querySelectorAll('.toast').forEach(t => t.remove());

    const toast = document.createElement('div');
    toast.className = `toast toast-${type}`;
    toast.textContent = message;

    document.body.appendChild(toast);

    // Trigger animation
    setTimeout(() => toast.classList.add('show'), 10);

    // Auto remove
    setTimeout(() => {
        toast.classList.remove('show');
        setTimeout(() => toast.remove(), 300);
    }, 3000);
}

// Select All Checkbox
function initSelectAll() {
    const selectAllCheckbox = document.getElementById('selectAll');
    const rowCheckboxes = document.querySelectorAll('.row-checkbox');

    if (selectAllCheckbox) {
        selectAllCheckbox.addEventListener('change', () => {
            rowCheckboxes.forEach(checkbox => {
                checkbox.checked = selectAllCheckbox.checked;
            });
            updateBulkActions();
        });
    }

    rowCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', updateBulkActions);
    });
}

function updateBulkActions() {
    const checkedCount = document.querySelectorAll('.row-checkbox:checked').length;
    const bulkActions = document.getElementById('bulkActions');
    const selectedCount = document.getElementById('selectedCount');

    if (bulkActions) {
        if (checkedCount > 0) {
            bulkActions.classList.remove('hidden');
            if (selectedCount) {
                selectedCount.textContent = checkedCount;
            }
        } else {
            bulkActions.classList.add('hidden');
        }
    }
}

// Search Filter
function initSearch() {
    const searchInput = document.getElementById('searchInput');
    const tableRows = document.querySelectorAll('.table tbody tr');

    if (searchInput) {
        searchInput.addEventListener('input', (e) => {
            const query = e.target.value.toLowerCase();

            tableRows.forEach(row => {
                const text = row.textContent.toLowerCase();
                row.style.display = text.includes(query) ? '' : 'none';
            });
        });
    }
}

// Initialize on page load
document.addEventListener('DOMContentLoaded', () => {
    initSelectAll();
    initSearch();
});
