/**
 * Club Management System — Core JavaScript
 */
(function() {
    'use strict';

    // CSRF Token for all AJAX requests
    const csrfToken = document.querySelector('meta[name="csrf-token"]')?.content;
    if (csrfToken) {
        $.ajaxSetup({
            headers: { 'X-CSRF-TOKEN': csrfToken, 'X-Requested-With': 'XMLHttpRequest' }
        });
    }

    // Global AJAX error handler
    $(document).ajaxError(function(event, jqXHR, settings) {
        if (jqXHR.status === 401) {
            Swal.fire({ icon: 'warning', title: 'Session Expired', text: 'Please log in again.', confirmButtonText: 'Login' })
                .then(() => { window.location.href = '/login'; });
        } else if (jqXHR.status === 403) {
            Swal.fire({ icon: 'error', title: 'Access Denied', text: 'You do not have permission for this action.' });
        } else if (jqXHR.status >= 500) {
            Swal.fire({ icon: 'error', title: 'Server Error', text: 'Something went wrong. Please try again later.' });
        }
    });

    // Sidebar Toggle
    const sidebar = document.getElementById('sidebar');
    const mainContent = document.getElementById('mainContent');
    const sidebarToggle = document.getElementById('sidebarToggle');
    const sidebarClose = document.getElementById('sidebarClose');
    const sidebarOverlay = document.getElementById('sidebarOverlay');

    function toggleSidebar() {
        if (window.innerWidth >= 992) {
            sidebar?.classList.toggle('collapsed');
            mainContent?.classList.toggle('expanded');
            localStorage.setItem('sidebar_collapsed', sidebar?.classList.contains('collapsed') ? '1' : '0');
        } else {
            sidebar?.classList.toggle('show');
            sidebarOverlay?.classList.toggle('show');
        }
    }

    sidebarToggle?.addEventListener('click', toggleSidebar);
    sidebarClose?.addEventListener('click', toggleSidebar);
    sidebarOverlay?.addEventListener('click', toggleSidebar);

    // Restore sidebar state
    if (window.innerWidth >= 992 && localStorage.getItem('sidebar_collapsed') === '1') {
        sidebar?.classList.add('collapsed');
        mainContent?.classList.add('expanded');
    }

    // Confirm Delete
    document.addEventListener('click', function(e) {
        const btn = e.target.closest('[data-confirm]');
        if (btn) {
            e.preventDefault();
            const message = btn.getAttribute('data-confirm-message') || 'Are you sure?';
            const form = btn.closest('form');
            Swal.fire({
                title: 'Confirm',
                text: message,
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#e53e3e',
                confirmButtonText: 'Yes, proceed',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed && form) {
                    form.submit();
                }
            });
        }
    });

    // Auto-dismiss alerts after 5 seconds
    document.querySelectorAll('.alert-dismissible').forEach(function(alert) {
        setTimeout(function() {
            const bsAlert = bootstrap.Alert.getOrCreateInstance(alert);
            bsAlert?.close();
        }, 5000);
    });

    // Initialize tooltips
    document.querySelectorAll('[data-bs-toggle="tooltip"]').forEach(function(el) {
        new bootstrap.Tooltip(el);
    });

    // Initialize popovers
    document.querySelectorAll('[data-bs-toggle="popover"]').forEach(function(el) {
        new bootstrap.Popover(el);
    });

    // Initialize Select2
    if ($.fn.select2) {
        $('.select2').select2({ theme: 'bootstrap-5', width: '100%' });
    }

    // Initialize Flatpickr
    if (typeof flatpickr !== 'undefined') {
        document.querySelectorAll('.datepicker').forEach(function(el) {
            flatpickr(el, { dateFormat: 'Y-m-d', allowInput: true });
        });
        document.querySelectorAll('.datetimepicker').forEach(function(el) {
            flatpickr(el, { dateFormat: 'Y-m-d H:i', enableTime: true, allowInput: true });
        });
    }

})();