// Notification System
function notify(message, type = 'success') {
    const container = document.getElementById('notifications-container');
    if (!container) {
        const div = document.createElement('div');
        div.id = 'notifications-container';
        div.className = 'notifications-container';
        document.body.appendChild(div);
    }
    
    const notification = document.createElement('div');
    notification.className = `notification ${type}`;
    
    let icon = 'fa-check-circle';
    if (type === 'error') icon = 'fa-times-circle';
    if (type === 'info') icon = 'fa-info-circle';
    if (type === 'warning') icon = 'fa-exclamation-triangle';
    
    notification.innerHTML = `
        <i class="fas ${icon}"></i>
        <div class="notification-content">${message}</div>
    `;
    
    document.getElementById('notifications-container').appendChild(notification);
    
    setTimeout(() => {
        notification.style.opacity = '0';
        notification.style.transform = 'translateX(100%)';
        notification.style.transition = 'all 0.5s ease-in';
        setTimeout(() => notification.remove(), 500);
    }, 4000);
}

// Modal System
function openModal(modalId) {
    document.getElementById(modalId).classList.add('active');
}

function closeModal(modalId) {
    document.getElementById(modalId).classList.remove('active');
}

// Global AJAX helper
async function apiCall(endpoint, data = null) {
    // Check if the first parameter is actually a button (for manual calls)
    let btn = null;
    if (data && data.btn) {
        btn = data.btn;
        data = data.data;
    }

    if (btn) btn.classList.add('btn-loading');

    try {
        const isFormData = data instanceof FormData;
        const options = {
            method: data ? 'POST' : 'GET',
            headers: {
                'X-User-Timezone': Intl.DateTimeFormat().resolvedOptions().timeZone
            }
        };
        
        if (data) {
            if (isFormData) {
                options.body = data;
            } else {
                options.headers['Content-Type'] = 'application/json';
                options.body = JSON.stringify(data);
            }
        }
        
        const basePath = window.APP_CONFIG ? window.APP_CONFIG.BASE_PATH : '/';
        const response = await fetch(`${basePath}api/${endpoint}.php`, options);
        const result = await response.json();
        return result;
    } catch (error) {
        console.error('API Error:', error);
        notify('Something went wrong!', 'error');
        return { success: false, message: error.message };
    } finally {
        if (btn) btn.classList.remove('btn-loading');
    }
}

// Global Busy Indication Helper
function setLoading(btn, isLoading) {
    if (!btn) return;
    if (isLoading) {
        btn.classList.add('btn-loading');
        btn.disabled = true;
    } else {
        btn.classList.remove('btn-loading');
        btn.disabled = false;
    }
}

// Global Form Submission Interceptor
document.addEventListener('submit', function(e) {
    const form = e.target;
    // Don't intercept if the form has a data-no-busy attribute
    if (form.hasAttribute('data-no-busy')) return;

    const submitBtn = form.querySelector('button[type="submit"]');
    if (submitBtn) {
        // If it's a standard form (no AJAX), it will stay in loading state until page reloads
        submitBtn.classList.add('btn-loading');
        
        // Prevent double submission
        if (submitBtn.dataset.submitting === 'true') {
            e.preventDefault();
            return;
        }
        submitBtn.dataset.submitting = 'true';
    }
});

// Sidebar responsiveness toggle
function toggleSidebar() {
    const sidebar = document.getElementById('sidebar');
    const overlay = document.getElementById('sidebarOverlay');
    sidebar.classList.toggle('active');
    overlay.classList.toggle('active');
}

// Global Confirmation Helper
function confirmAction(options = {}) {
    const {
        title = 'Confirm Action',
        message = 'Are you sure you want to proceed? This action cannot be undone.',
        confirmText = 'Delete',
        confirmClass = 'var(--danger)'
    } = options;

    const modal = document.getElementById('confirmModal');
    const confirmBtn = document.getElementById('confirmBtn');
    
    document.getElementById('confirmTitle').innerText = title;
    document.getElementById('confirmMessage').innerText = message;
    confirmBtn.innerText = confirmText;
    confirmBtn.style.background = confirmClass;

    return new Promise((resolve) => {
        const cancelBtn = modal.querySelector('button[onclick*="confirmModal"]');
        
        const handleConfirm = () => {
            confirmBtn.removeEventListener('click', handleConfirm);
            cancelBtn.removeEventListener('click', handleCancel);
            closeModal('confirmModal');
            resolve(true);
        };

        const handleCancel = () => {
            confirmBtn.removeEventListener('click', handleConfirm);
            cancelBtn.removeEventListener('click', handleCancel);
            resolve(false);
        };

        confirmBtn.addEventListener('click', handleConfirm);
        cancelBtn.addEventListener('click', handleCancel);
        
        openModal('confirmModal');
    });
}

// Sidebar Collapse Logic
function toggleSidebarCollapse() {
    const sidebar = document.getElementById('sidebar');
    const mainContent = document.getElementById('mainContent');
    const icon = document.getElementById('collapseIcon');
    
    sidebar.classList.toggle('collapsed');
    mainContent.classList.toggle('collapsed');
    
    const isCollapsed = sidebar.classList.contains('collapsed');
    localStorage.setItem('sidebarCollapsed', isCollapsed);
    
    // Update icon
    icon.className = 'fas fa-bars';
}

// Apply saved sidebar state on load
document.addEventListener('DOMContentLoaded', function() {
    const isCollapsed = localStorage.getItem('sidebarCollapsed') === 'true';
    if (isCollapsed) {
        document.getElementById('sidebar').classList.add('collapsed');
        document.getElementById('mainContent').classList.add('collapsed');
        const icon = document.getElementById('collapseIcon');
        if (icon) icon.className = 'fas fa-bars';
    }
});

// Global Phone Number Input Restriction
document.addEventListener('input', function(e) {
    if (e.target && (e.target.name === 'phone' || e.target.type === 'tel')) {
        const cleanValue = e.target.value.replace(/[^\d+-\s()]/g, '');
        if (e.target.value !== cleanValue) {
            e.target.value = cleanValue;
        }
    }
});

/**
 * Utility for client-side image compression
 * Reduces payload size and server-side processing time
 */
async function compressImage(file) {
    if (!file.type.startsWith('image/')) return file;
    
    return new Promise((resolve) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = (e) => {
            const img = new Image();
            img.src = e.target.result;
            img.onload = () => {
                const canvas = document.createElement('canvas');
                let width = img.width;
                let height = img.height;
                
                // Max 1200px dimension
                const maxDim = 1200;
                if (width > height && width > maxDim) {
                    height *= maxDim / width;
                    width = maxDim;
                } else if (height > maxDim) {
                    width *= maxDim / height;
                    height = maxDim;
                }
                
                canvas.width = width;
                canvas.height = height;
                const ctx = canvas.getContext('2d');
                ctx.drawImage(img, 0, 0, width, height);
                
                canvas.toBlob((blob) => {
                    resolve(new File([blob], file.name, { type: 'image/jpeg' }));
                }, 'image/jpeg', 0.7); // 70% quality
            };
        };
    });
}
