/**
 * Gmind Institute — Admin Panel JavaScript
 *
 * Vanilla ES2022 — zero dependencies
 * Features: sidebar toggle, delete confirm, toggle active, image preview,
 *           form validation, table search/filter
 */
(function () {
    'use strict';

    // ─── DOM Ready ────────────────────────────────────────────────────────────
    function onReady(fn) {
        if (document.readyState !== 'loading') {
            fn();
        } else {
            document.addEventListener('DOMContentLoaded', fn);
        }
    }

    // ─── Sidebar Toggle (Mobile) ──────────────────────────────────────────────
    function initSidebarToggle() {
        const sidebar = document.getElementById('adminSidebar');
        const overlay = document.getElementById('sidebarOverlay');
        const toggle = document.getElementById('sidebarToggle');
        const close = document.getElementById('sidebarClose');

        if (!sidebar || !toggle) return;

        function openSidebar() {
            sidebar.classList.add('open');
            overlay?.classList.add('active');
            document.body.style.overflow = 'hidden';
        }

        function closeSidebar() {
            sidebar.classList.remove('open');
            overlay?.classList.remove('active');
            document.body.style.overflow = '';
        }

        toggle.addEventListener('click', openSidebar);
        close?.addEventListener('click', closeSidebar);
        overlay?.addEventListener('click', closeSidebar);

        // Close sidebar when a nav link is clicked on mobile
        sidebar.querySelectorAll('.admin-nav-link').forEach((link) => {
            link.addEventListener('click', () => {
                if (window.innerWidth <= 768) {
                    closeSidebar();
                }
            });
        });
    }

    // ─── Delete Confirmation Modal ────────────────────────────────────────────
    function initDeleteConfirmation() {
        const modal = document.getElementById('deleteModal');
        const modalClose = document.getElementById('deleteModalClose');
        const modalCancel = document.getElementById('deleteModalCancel');
        const deleteForm = document.getElementById('deleteForm');

        if (!modal) return;

        function openModal(deleteUrl) {
            modal.classList.add('active');
            if (deleteForm && deleteUrl) {
                deleteForm.action = deleteUrl;
            }
        }

        function closeModal() {
            modal.classList.remove('active');
            if (deleteForm) {
                deleteForm.action = '';
            }
        }

        // Attach to all delete buttons
        document.querySelectorAll('[data-delete-url]').forEach((btn) => {
            btn.addEventListener('click', (e) => {
                e.preventDefault();
                openModal(btn.dataset.deleteUrl);
            });
        });

        // Also handle [data-confirm-delete] buttons (inline forms)
        document.querySelectorAll('[data-confirm-delete]').forEach((btn) => {
            btn.addEventListener('click', (e) => {
                if (!confirm('Are you sure you want to delete this item? This action cannot be undone.')) {
                    e.preventDefault();
                    e.stopImmediatePropagation();
                }
            });
        });

        modalClose?.addEventListener('click', closeModal);
        modalCancel?.addEventListener('click', closeModal);

        // Close on overlay click
        modal.addEventListener('click', (e) => {
            if (e.target === modal) closeModal();
        });

        // Close on Escape
        document.addEventListener('keydown', (e) => {
            if (e.key === 'Escape' && modal.classList.contains('active')) {
                closeModal();
            }
        });
    }

    // ─── Toggle Active Status via AJAX ────────────────────────────────────────
    function initToggleActive() {
        document.querySelectorAll('[data-toggle-url]').forEach((checkbox) => {
            checkbox.addEventListener('change', async () => {
                const url = checkbox.dataset.toggleUrl;
                const field = checkbox.dataset.toggleField || 'active';
                const value = checkbox.checked ? 1 : 0;

                try {
                    const token = document.querySelector('meta[name="csrf-token"]')?.content || '';

                    const formData = new FormData();
                    formData.append('csrf_token', token);
                    formData.append('field', field);
                    formData.append('value', String(value));

                    const response = await fetch(url, {
                        method: 'POST',
                        body: formData,
                        headers: {
                            'X-Requested-With': 'XMLHttpRequest',
                        },
                    });

                    if (!response.ok) {
                        throw new Error('Toggle failed');
                    }

                    // Visual feedback
                    showNotification(value ? 'Item activated' : 'Item deactivated', 'success');
                } catch {
                    // Revert on error
                    checkbox.checked = !checkbox.checked;
                    showNotification('Failed to update status', 'error');
                }
            });
        });
    }

    // ─── Image Preview on Upload ──────────────────────────────────────────────
    function initImagePreview() {
        document.querySelectorAll('input[data-preview]').forEach((input) => {
            input.addEventListener('change', () => {
                const previewId = input.dataset.preview;
                const previewContainer = document.getElementById(previewId);
                if (!previewContainer) return;

                previewContainer.innerHTML = '';

                if (input.files && input.files[0]) {
                    const file = input.files[0];

                    // Validate file type
                    const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
                    if (!allowedTypes.includes(file.type)) {
                        showNotification('Only JPG, PNG, GIF, and WebP images are allowed.', 'error');
                        input.value = '';
                        return;
                    }

                    // Validate file size (5MB)
                    if (file.size > 5 * 1024 * 1024) {
                        showNotification('Image must be less than 5MB.', 'error');
                        input.value = '';
                        return;
                    }

                    const reader = new FileReader();
                    reader.onload = (e) => {
                        const img = document.createElement('img');
                        img.src = e.target?.result ?? '';
                        img.alt = 'Preview';
                        previewContainer.appendChild(img);
                    };
                    reader.readAsDataURL(file);
                }
            });
        });
    }

    // ─── Form Validation ──────────────────────────────────────────────────────
    function initFormValidation() {
        document.querySelectorAll('.admin-form[novalidate]').forEach((form) => {
            form.addEventListener('submit', (e) => {
                let isValid = true;

                // Clear previous errors
                form.querySelectorAll('.admin-form-error').forEach((el) => el.remove());
                form.querySelectorAll('.admin-form-input.is-invalid, .admin-form-select.is-invalid, .admin-form-textarea.is-invalid')
                    .forEach((el) => el.classList.remove('is-invalid'));

                // Check required fields
                form.querySelectorAll('[required]').forEach((field) => {
                    if (!field.value.trim()) {
                        isValid = false;
                        field.classList.add('is-invalid');

                        const error = document.createElement('span');
                        error.className = 'admin-form-error';
                        error.textContent = 'This field is required';
                        error.style.cssText = 'color: #e53e3e; font-size: 12px; margin-top: 4px; display: block;';
                        field.parentNode?.appendChild(error);
                    }
                });

                // Check email fields
                form.querySelectorAll('input[type="email"]').forEach((field) => {
                    if (field.value.trim() && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(field.value)) {
                        isValid = false;
                        field.classList.add('is-invalid');

                        const error = document.createElement('span');
                        error.className = 'admin-form-error';
                        error.textContent = 'Please enter a valid email address';
                        error.style.cssText = 'color: #e53e3e; font-size: 12px; margin-top: 4px; display: block;';
                        field.parentNode?.appendChild(error);
                    }
                });

                if (!isValid) {
                    e.preventDefault();

                    // Focus first invalid field
                    const firstInvalid = form.querySelector('.is-invalid');
                    firstInvalid?.focus();
                    firstInvalid?.scrollIntoView({ behavior: 'smooth', block: 'center' });
                }
            });
        });
    }

    // ─── Table Search/Filter ──────────────────────────────────────────────────
    function initTableSearch() {
        document.querySelectorAll('.admin-table[data-search]').forEach((table) => {
            const wrapper = table.closest('.admin-card-body') || table.closest('.admin-table-responsive');
            if (!wrapper) return;

            // Create search input
            const searchDiv = document.createElement('div');
            searchDiv.className = 'admin-table-filter';
            searchDiv.style.cssText = 'margin-bottom: 16px; display: flex; gap: 12px; align-items: center;';

            const searchInput = document.createElement('input');
            searchInput.type = 'text';
            searchInput.placeholder = 'Search...';
            searchInput.className = 'admin-table-search';
            searchDiv.appendChild(searchInput);

            // Insert before the table
            wrapper.insertBefore(searchDiv, wrapper.firstChild);

            const tbody = table.querySelector('tbody');
            if (!tbody) return;

            const rows = Array.from(tbody.querySelectorAll('tr'));

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

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

    // ─── Category Filter for Courses ──────────────────────────────────────────
    function initCategoryFilter() {
        const filter = document.getElementById('categoryFilter');
        if (!filter) return;

        filter.addEventListener('change', () => {
            const category = filter.value;
            const url = new URL(window.location.href);
            if (category) {
                url.searchParams.set('category', category);
            } else {
                url.searchParams.delete('category');
            }
            window.location.href = url.toString();
        });
    }

    // ─── Flash Alert Auto-Dismiss ─────────────────────────────────────────────
    function initAlertDismiss() {
        // Close buttons
        document.querySelectorAll('.admin-alert-close').forEach((btn) => {
            btn.addEventListener('click', () => {
                const alert = btn.closest('.admin-alert');
                alert?.remove();
            });
        });

        // Auto-dismiss after 5 seconds
        setTimeout(() => {
            document.querySelectorAll('.admin-alert').forEach((alert) => {
                alert.style.transition = 'opacity 0.3s ease';
                alert.style.opacity = '0';
                setTimeout(() => alert.remove(), 300);
            });
        }, 5000);
    }

    // ─── Notification Toast ───────────────────────────────────────────────────
    function showNotification(message, type = 'info') {
        const existing = document.querySelector('.admin-toast');
        existing?.remove();

        const toast = document.createElement('div');
        toast.className = `admin-toast admin-toast-${type}`;
        toast.innerHTML = `
            <span>${message}</span>
            <button class="admin-toast-close" aria-label="Close">&times;</button>
        `;

        // Toast styles
        Object.assign(toast.style, {
            position: 'fixed',
            bottom: '24px',
            right: '24px',
            padding: '12px 20px',
            borderRadius: '8px',
            fontSize: '14px',
            fontWeight: '500',
            display: 'flex',
            alignItems: 'center',
            gap: '12px',
            zIndex: '3000',
            animation: 'adminSlideUp 0.3s ease',
            boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
        });

        if (type === 'success') {
            toast.style.background = '#f0fff4';
            toast.style.color = '#276749';
            toast.style.borderLeft = '4px solid #38a169';
        } else if (type === 'error') {
            toast.style.background = '#fff5f5';
            toast.style.color = '#9b2c2c';
            toast.style.borderLeft = '4px solid #e53e3e';
        } else {
            toast.style.background = '#ebf8ff';
            toast.style.color = '#2b6cb0';
            toast.style.borderLeft = '4px solid #4299e1';
        }

        document.body.appendChild(toast);

        // Close button
        toast.querySelector('.admin-toast-close')?.addEventListener('click', () => {
            toast.remove();
        });

        // Auto-dismiss after 3 seconds
        setTimeout(() => {
            toast.style.transition = 'opacity 0.3s ease';
            toast.style.opacity = '0';
            setTimeout(() => toast.remove(), 300);
        }, 3000);
    }

    // ─── Add toast animation ─────────────────────────────────────────────────
    const toastStyle = document.createElement('style');
    toastStyle.textContent = `
        @keyframes adminSlideUp {
            from { opacity: 0; transform: translateY(20px); }
            to   { opacity: 1; transform: translateY(0); }
        }
        .admin-toast-close {
            background: none;
            border: none;
            font-size: 18px;
            cursor: pointer;
            color: inherit;
            opacity: 0.6;
            padding: 0;
            line-height: 1;
        }
        .admin-toast-close:hover { opacity: 1; }
        .is-invalid {
            border-color: #e53e3e !important;
        }
        .is-invalid:focus {
            box-shadow: 0 0 0 3px rgba(229, 62, 62, 0.1) !important;
        }
    `;
    document.head.appendChild(toastStyle);

    // ─── Initialize All ───────────────────────────────────────────────────────
    onReady(() => {
        initSidebarToggle();
        initDeleteConfirmation();
        initToggleActive();
        initImagePreview();
        initFormValidation();
        initTableSearch();
        initCategoryFilter();
        initAlertDismiss();
    });
})();
