// Global utility functions for Recipe Control Pro
window.APP_CONFIG = {
    BASE_PATH: '/rcp/',
    API_BASE: '/rcp/api/'
};

// Currency formatting
window.formatZAR = (amount) => {
    return 'R ' + parseFloat(amount || 0).toLocaleString('en-ZA', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
    });
};

// Enhanced fetch with error handling
window.rcpFetch = async (endpoint, options = {}) => {
    try {
        const response = await fetch(window.APP_CONFIG.API_BASE + endpoint, {
            headers: {
                'Content-Type': 'application/json',
                ...options.headers
            },
            ...options
        });
        
        if (response.status === 401) {
            window.location.href = window.APP_CONFIG.BASE_PATH + 'pages/login.php';
            throw new Error('Authentication required');
        }
        
        if (response.status === 403) {
            showAlert('Access denied. Insufficient permissions.', 'danger');
            throw new Error('Access denied');
        }
        
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        
        return await response.json();
    } catch (error) {
        console.error('API Error:', error);
        throw error;
    }
};

// Alert system
window.showAlert = (message, type = 'info', duration = 5000) => {
    // Remove existing alerts
    document.querySelectorAll('.alert-dismissible').forEach(alert => {
        if (alert.parentNode) alert.remove();
    });
    
    const alert = document.createElement('div');
    alert.className = `alert alert-${type} alert-dismissible fade show`;
    alert.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    
    const container = document.querySelector('.container-fluid, .container');
    if (container) {
        container.insertBefore(alert, container.firstChild);
        
        if (duration > 0) {
            setTimeout(() => {
                if (alert.parentNode) alert.remove();
            }, duration);
        }
    }
};

// Loading state management
window.showLoading = (element) => {
    if (element) {
        element.disabled = true;
        const originalText = element.innerHTML;
        element.innerHTML = '<span class="spinner-border spinner-border-sm" role="status"></span> Loading...';
        return () => {
            element.disabled = false;
            element.innerHTML = originalText;
        };
    }
    return () => {};
};

// Form validation
window.validateForm = (formData, requiredFields) => {
    const errors = [];
    requiredFields.forEach(field => {
        if (!formData.get(field)?.trim()) {
            errors.push(`${field} is required`);
        }
    });
    return errors;
};

// Debounce function
window.debounce = (func, wait) => {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
};

// Safe HTML escaping
window.escapeHtml = (unsafe) => {
    if (!unsafe) return '';
    return unsafe
        .replace(/&/g, "&amp;")
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#039;");
};

// Initialize when page loads
document.addEventListener('DOMContentLoaded', () => {
    // Auto-hide alerts after 5 seconds
    setTimeout(() => {
        document.querySelectorAll('.alert:not(.alert-permanent)').forEach(alert => {
            if (alert.parentNode) alert.remove();
        });
    }, 5000);
});