// ===== ENHANCED UI & UX IMPROVEMENTS =====

// ===== DARK MODE TOGGLE =====
function toggleDarkMode() {
    const isDark = document.body.classList.toggle('dark-mode');
    localStorage.setItem('theme', isDark ? 'dark' : 'light');
    updateThemeBtn(isDark);
}

function updateThemeBtn(isDark) {
    const btn = document.getElementById('themeToggleBtn');
    if (btn) btn.textContent = isDark ? '☀️' : '🌙';
}

// Apply saved theme IMMEDIATELY before DOM renders (prevents flash)
(function () {
    if (localStorage.getItem('theme') === 'dark') {
        document.documentElement.classList.add('dark-mode-pre');
        document.body && document.body.classList.add('dark-mode');
    }
})();

document.addEventListener('DOMContentLoaded', function () {
    const saved = localStorage.getItem('theme');
    if (saved === 'dark') {
        document.body.classList.add('dark-mode');
        updateThemeBtn(true);
    } else {
        updateThemeBtn(false);
    }
    document.documentElement.classList.remove('dark-mode-pre');
});

// ===== SIDEBAR TOGGLE (mobile) =====
function toggleSidebar() {
    const sidebar = document.querySelector('.sidebar');
    const overlay = document.querySelector('.sidebar-overlay');
    const isOpen = sidebar.classList.toggle('open');
    if (overlay) overlay.classList.toggle('show', isOpen);
    if (isOpen) history.pushState({ sidebar: true }, '');
}

function closeSidebar() {
    const sidebar = document.querySelector('.sidebar');
    const overlay = document.querySelector('.sidebar-overlay');
    if (sidebar) sidebar.classList.remove('open');
    if (overlay) overlay.classList.remove('show');
}

window.addEventListener('popstate', function () {
    const sidebar = document.querySelector('.sidebar');
    if (sidebar && sidebar.classList.contains('open')) {
        closeSidebar();
    }
});

// ===== MODAL HELPERS =====
function openModal(id) {
    const modal = document.getElementById(id);
    if (modal) {
        modal.classList.add('open');
        // Focus on first focusable element
        const focusable = modal.querySelector('button, input, textarea, select, a');
        if (focusable) focusable.focus();
    }
}

function closeModal(id) {
    document.getElementById(id).classList.remove('open');
}

// ===== FORM VALIDATION & FEEDBACK =====
function showFormValidation(form) {
    const inputs = form.querySelectorAll('[required]');
    inputs.forEach(input => {
        input.addEventListener('blur', () => {
            if (!input.value.trim()) {
                input.style.borderColor = '#dc2626';
            } else {
                input.style.borderColor = '';
            }
        });
    });
}

// ===== LOADING STATE MANAGEMENT =====
function setButtonLoading(button, isLoading) {
    if (isLoading) {
        button.disabled = true;
        button.style.opacity = '0.7';
        button.innerHTML = '<span style="display:inline-block;animation:spin .8s linear infinite">⟳</span> ' + (button.getAttribute('data-loading-text') || 'Loading...');
    } else {
        button.disabled = false;
        button.style.opacity = '1';
        button.innerHTML = button.getAttribute('data-original-text') || 'Submit';
    }
}

// ===== TOAST NOTIFICATIONS =====
function showToast(message, type = 'info', duration = 3000) {
    const toast = document.createElement('div');
    toast.className = `alert alert-${type}`;
    toast.textContent = message;
    toast.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        min-width: 300px;
        z-index: 9999;
        animation: slideIn 0.3s ease;
    `;

    document.body.appendChild(toast);

    setTimeout(() => {
        toast.style.animation = 'slideOut 0.3s ease';
        setTimeout(() => toast.remove(), 300);
    }, duration);
}

// ===== SMOOTH SCROLLING =====
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        const href = this.getAttribute('href');
        if (href !== '#') {
            e.preventDefault();
            const target = document.querySelector(href);
            if (target) {
                target.scrollIntoView({ behavior: 'smooth', block: 'start' });
            }
        }
    });
});

// ===== KEYBOARD NAVIGATION =====
document.addEventListener('keydown', function (e) {
    // Close modal on Escape
    if (e.key === 'Escape') {
        document.querySelectorAll('.modal-overlay.open').forEach(modal => {
            modal.classList.remove('open');
        });
    }
    // Close sidebar on Escape
    if (e.key === 'Escape') {
        closeSidebar();
    }
});

// ===== DOM READY INITIALIZATION =====
document.addEventListener('DOMContentLoaded', function () {
    // Sidebar overlay click handler
    const overlay = document.querySelector('.sidebar-overlay');
    if (overlay) overlay.addEventListener('click', closeSidebar);

    // Close sidebar on nav item click (mobile)
    document.querySelectorAll('.nav-item').forEach(function (item) {
        item.addEventListener('click', function () {
            if (window.innerWidth <= 768) closeSidebar();
        });
    });

    // Modal overlay click handler
    document.addEventListener('click', function (e) {
        if (e.target.classList.contains('modal-overlay')) {
            e.target.classList.remove('open');
        }
    });

    // Modal close button handler
    document.querySelectorAll('.modal-close').forEach(btn => {
        btn.addEventListener('click', function () {
            const modal = this.closest('.modal-overlay');
            if (modal) modal.classList.remove('open');
        });
    });

    // Auto-dismiss alerts after 4 seconds
    document.querySelectorAll('.alert').forEach(function (a) {
        setTimeout(function () {
            if (a.parentElement) {
                a.style.transition = 'opacity 0.5s ease';
                a.style.opacity = '0';
                setTimeout(function () { a.remove(); }, 500);
            }
        }, 4000);
    });

    // Form validation on input
    document.querySelectorAll('form').forEach(form => {
        showFormValidation(form);
    });

    // Save original button text for loading state
    document.querySelectorAll('button[type="submit"]').forEach(btn => {
        btn.setAttribute('data-original-text', btn.innerHTML);
    });

    // Image preview functionality
    document.querySelectorAll('input[type="file"]').forEach(input => {
        if (input.hasAttribute('data-preview')) {
            input.addEventListener('change', function () {
                previewImage(this, this.getAttribute('data-preview'));
            });
        }
    });

    // Add visual feedback to interactive elements
    document.querySelectorAll('button, a.btn, input[type="submit"]').forEach(el => {
        el.addEventListener('mouseenter', function () {
            if (!this.disabled) {
                this.style.cursor = 'pointer';
            }
        });
    });

    // Prevent accidental double submissions (skip delete forms and forms with named submit buttons)
    document.querySelectorAll('form:not([data-item])').forEach(form => {
        form.addEventListener('submit', function () {
            const submitBtn = this.querySelector('button[type="submit"][name]');
            // Skip if button has a name (PHP relies on it) or form has file input
            if (submitBtn && submitBtn.name) return;
            const btn = this.querySelector('button[type="submit"]');
            if (btn && !btn.disabled) setButtonLoading(btn, true);
        });
    });
});

// Close sidebar on window resize to desktop
window.addEventListener('resize', function () {
    if (window.innerWidth > 768) closeSidebar();
});

// ===== IMAGE PREVIEW =====
function previewImage(input, previewId) {
    const preview = document.getElementById(previewId);
    if (!preview) return;

    if (input.files && input.files[0]) {
        // Validate file size (max 5MB)
        if (input.files[0].size > 5 * 1024 * 1024) {
            showToast('File size must be less than 5MB', 'warning');
            return;
        }

        // Validate file type
        if (!input.files[0].type.startsWith('image/')) {
            showToast('Please select a valid image file', 'danger');
            return;
        }

        const reader = new FileReader();
        reader.onload = function (e) {
            preview.src = e.target.result;
            preview.style.display = 'block';
        };
        reader.readAsDataURL(input.files[0]);
    }
}

// ===== REPORT FORM UPLOAD PREVIEW =====
function rfPreview(input, wrapId, zoneId) {
    const wrap = document.getElementById(wrapId);
    const zone = document.getElementById(zoneId);
    if (!wrap || !input.files || !input.files[0]) return;

    const file = input.files[0];
    if (file.size > 5 * 1024 * 1024) { showToast('File size must be less than 5MB', 'warning'); input.value = ''; return; }
    if (!file.type.startsWith('image/')) { showToast('Please select a valid image file', 'danger'); input.value = ''; return; }

    const reader = new FileReader();
    reader.onload = function (e) {
        const img = wrap.querySelector('img');
        if (img) img.src = e.target.result;
        wrap.style.display = 'block';
        if (zone) zone.style.display = 'none';
    };
    reader.readAsDataURL(file);
}

function rfRemove(inputId, wrapId, zoneId) {
    const input = document.getElementById(inputId);
    const wrap = document.getElementById(wrapId);
    const zone = document.getElementById(zoneId);
    if (input) input.value = '';
    if (wrap) wrap.style.display = 'none';
    if (zone) zone.style.display = '';
}

// ===== CONFIRM DELETE WITH ENHANCED UX =====
function confirmDelete(form) {
    const item = form.getAttribute('data-item') || 'this record';
    if (!confirm(`Are you sure you want to delete "${item}"? This action cannot be undone.`)) {
        return false;
    }
    return true;
}

// ===== TABLE FILTER WITH DEBOUNCE =====
let filterTimeout;
function filterTable(inputId, tableId) {
    clearTimeout(filterTimeout);
    filterTimeout = setTimeout(() => {
        const input = document.getElementById(inputId);
        const table = document.getElementById(tableId);
        if (!input || !table) return;

        const filter = input.value.toLowerCase();
        let visibleRows = 0;

        table.querySelectorAll('tbody tr').forEach(function (row) {
            const matches = row.textContent.toLowerCase().includes(filter);
            row.style.display = matches ? '' : 'none';
            if (matches) visibleRows++;
        });

        // Show "no results" message if needed
        const noResults = table.querySelector('.no-results');
        if (visibleRows === 0) {
            if (!noResults) {
                const tr = table.querySelector('tbody').insertRow();
                tr.className = 'no-results';
                tr.innerHTML = `<td colspan="100%" style="text-align:center;padding:24px;color:#64748b;">No items found</td>`;
            }
        } else if (noResults) {
            noResults.remove();
        }
    }, 300);
}

// ===== CSS ANIMATIONS =====
const style = document.createElement('style');
style.textContent = `
    @keyframes spin {
        to { transform: rotate(360deg); }
    }
    @keyframes slideIn {
        from {
            opacity: 0;
            transform: translateX(100%);
        }
        to {
            opacity: 1;
            transform: translateX(0);
        }
    }
    @keyframes slideOut {
        to {
            opacity: 0;
            transform: translateX(100%);
        }
    }
`;
document.head.appendChild(style);
