/**
 * AUTO TESTER - Unified JavaScript Framework
 * Description: Complete unified JavaScript for the entire system
 * Version: 2.0.0
 * Author: AUTO TESTER Team
 */

// ============================================
// Global Configuration
// ============================================
const CONFIG = {
    API_BASE_URL: '/backend/api',
    APP_NAME: 'AUTO TESTER',
    VERSION: '2.0.0',
    DEBUG: true,
    TOKEN_KEY: 'autotester_token',
    USER_KEY: 'autotester_user',
    THEME_KEY: 'autotester_theme',
    LANG_KEY: 'autotester_lang'
};

// ============================================
// Utility Functions
// ============================================
const Utils = {
    /**
     * Format date to Arabic format
     */
    formatDate(dateString) {
        const date = new Date(dateString);
        return date.toLocaleDateString('ar-EG');
    },

    /**
     * Format date and time to Arabic format
     */
    formatDateTime(dateString) {
        const date = new Date(dateString);
        return date.toLocaleString('ar-EG');
    },

    /**
     * Format price with Egyptian Pound
     */
    formatPrice(price) {
        return Number(price).toLocaleString('ar-EG') + ' &#x062c;&#x0645;';
    },

    /**
     * Generate unique ID
     */
    generateId() {
        return Date.now().toString(36) + Math.random().toString(36).substr(2);
    },

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

    /**
     * Validate email
     */
    validateEmail(email) {
        const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return re.test(email);
    },

    /**
     * Validate phone (Egyptian format)
     */
    validatePhone(phone) {
        const re = /^(01)[0-2,5]{1}[0-9]{8}$/;
        return re.test(phone.replace(/[\s\-\(\)]/g, ''));
    },

    /**
     * Copy text to clipboard
     */
    async copyToClipboard(text) {
        try {
            await navigator.clipboard.writeText(text);
            return true;
        } catch (err) {
            // Fallback for older browsers
            const textArea = document.createElement('textarea');
            textArea.value = text;
            document.body.appendChild(textArea);
            textArea.select();
            document.execCommand('copy');
            document.body.removeChild(textArea);
            return true;
        }
    },

    /**
     * Download file from URL
     */
    downloadFile(url, filename) {
        const link = document.createElement('a');
        link.href = url;
        link.download = filename;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    },

    /**
     * Get file extension
     */
    getFileExtension(filename) {
        return filename.slice((filename.lastIndexOf('.') - 1 >>> 0) + 2);
    },

    /**
     * Format file size
     */
    formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const k = 1024;
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
    }
};

// ============================================
// API Layer
// ============================================
const API = {
    /**
     * Get authentication token
     */
    getToken() {
        return localStorage.getItem(CONFIG.TOKEN_KEY);
    },

    /**
     * Get current user
     */
    getCurrentUser() {
        const userStr = localStorage.getItem(CONFIG.USER_KEY);
        return userStr ? JSON.parse(userStr) : null;
    },

    /**
     * Set authentication token
     */
    setToken(token) {
        localStorage.setItem(CONFIG.TOKEN_KEY, token);
    },

    /**
     * Set current user
     */
    setCurrentUser(user) {
        localStorage.setItem(CONFIG.USER_KEY, JSON.stringify(user));
    },

    /**
     * Get request headers
     */
    getHeaders() {
        const headers = {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        };

        const token = this.getToken();
        if (token) {
            headers['Authorization'] = 'Bearer ' + token;
        }

        return headers;
    },

    /**
     * Handle API response
     */
    async handleResponse(response) {
        if (!response.ok) {
            if (response.status === 401) {
                this.logout();
                window.location.href = '/auth/login.html?session=expired';
                throw new Error('Session expired');
            }

            const error = await response.json().catch(() => ({}));
            throw new Error(error.message || 'Connection error');
        }

        return response.json();
    },

    /**
     * GET request
     */
    async get(endpoint, params = {}) {
        const url = new URL(CONFIG.API_BASE_URL + endpoint, window.location.origin);
        Object.keys(params).forEach(key => url.searchParams.append(key, params[key]));

        const response = await fetch(url, {
            method: 'GET',
            headers: this.getHeaders()
        });

        return this.handleResponse(response);
    },

    /**
     * POST request
     */
    async post(endpoint, data = {}) {
        const response = await fetch(CONFIG.API_BASE_URL + endpoint, {
            method: 'POST',
            headers: this.getHeaders(),
            body: JSON.stringify(data)
        });

        return this.handleResponse(response);
    },

    /**
     * PUT request
     */
    async put(endpoint, data = {}) {
        const response = await fetch(CONFIG.API_BASE_URL + endpoint, {
            method: 'PUT',
            headers: this.getHeaders(),
            body: JSON.stringify(data)
        });

        return this.handleResponse(response);
    },

    /**
     * DELETE request
     */
    async delete(endpoint, data = {}) {
        const response = await fetch(CONFIG.API_BASE_URL + endpoint, {
            method: 'DELETE',
            headers: this.getHeaders(),
            body: JSON.stringify(data)
        });

        return this.handleResponse(response);
    },

    /**
     * Upload file
     */
    async upload(endpoint, formData) {
        const response = await fetch(CONFIG.API_BASE_URL + endpoint, {
            method: 'POST',
            headers: {
                'Authorization': 'Bearer ' + (this.getToken() || '')
            },
            body: formData
        });

        return this.handleResponse(response);
    },

    /**
     * Logout
     */
    logout() {
        localStorage.removeItem(CONFIG.TOKEN_KEY);
        localStorage.removeItem(CONFIG.USER_KEY);
        sessionStorage.clear();
    },

    // ============================================
    // Authentication APIs
    // ============================================
    auth: {
        async login(email, password, remember = false) {
            const response = await API.post('/auth/login', { email, password, remember });
            
            if (response.success) {
                API.setToken(response.token);
                API.setCurrentUser(response.user);
            }
            
            return response;
        },

        async register(userData) {
            return await API.post('/auth/register', userData);
        },

        async logout() {
            await API.post('/auth/logout').catch(() => {});
            API.logout();
            window.location.href = '/auth/login.html';
        },

        async checkSession() {
            return await API.get('/auth/check');
        },

        async resetPassword(email) {
            return await API.post('/auth/reset-password', { email });
        },

        async verifyCode(phone, code) {
            return await API.post('/auth/verify-phone', { phone, code });
        }
    },

    // ============================================
    // Client APIs
    // ============================================
    client: {
        async dashboard() {
            return await API.get('/client/dashboard');
        },

        async profile() {
            return await API.get('/client/profile');
        },

        async updateProfile(data) {
            return await API.put('/client/profile', data);
        },

        async getRequests(params = {}) {
            return await API.get('/client/requests', params);
        },

        async getRequest(id) {
            return await API.get('/client/requests', { id });
        },

        async createRequest(data) {
            return await API.post('/client/requests', data);
        },

        async getVehicles() {
            return await API.get('/client/vehicles');
        },

        async addVehicle(data) {
            return await API.post('/client/vehicles', data);
        },

        async updateVehicle(data) {
            return await API.put('/client/vehicles', data);
        },

        async deleteVehicle(id) {
            return await API.delete('/client/vehicles', { id });
        },

        async getCertificates() {
            return await API.get('/client/certificates');
        },

        async downloadCertificate(id) {
            window.location.href = `${CONFIG.API_BASE_URL}/client/download-certificate?id=${id}`;
        },

        async getPayments() {
            return await API.get('/client/payments');
        },

        async confirmPayment(requestId, amount, method, receiptFile) {
            const formData = new FormData();
            formData.append('request_id', requestId);
            formData.append('amount', amount);
            formData.append('method', method);
            if (receiptFile) {
                formData.append('receipt', receiptFile);
            }
            
            return await API.upload('/client/payments', formData);
        }
    },

    // ============================================
    // Inspector APIs
    // ============================================
    inspector: {
        async dashboard() {
            return await API.get('/inspector/dashboard');
        },

        async getInspections(params = {}) {
            return await API.get('/inspector/inspections', params);
        },

        async getInspection(id) {
            return await API.get('/inspector/inspections', { id });
        },

        async startInspection(id) {
            return await API.put('/inspector/inspections', { id, status: 'in_progress' });
        },

        async completeInspection(id, results) {
            return await API.put('/inspector/inspections', { 
                id, 
                status: 'completed',
                results 
            });
        },

        async addResults(id, data) {
            return await API.put('/inspector/inspections', { id, ...data });
        },

        async uploadImages(requestId, files, type = 'inspection') {
            const formData = new FormData();
            formData.append('request_id', requestId);
            formData.append('image_type', type);
            
            for (let i = 0; i < files.length; i++) {
                formData.append('images[]', files[i]);
            }
            
            return await API.upload('/inspector/upload-images', formData);
        },

        async getSchedule(date) {
            return await API.get('/inspector/schedule', { date });
        }
    },

    // ============================================
    // Supervisor APIs
    // ============================================
    supervisor: {
        async dashboard() {
            return await API.get('/supervisor/dashboard');
        },

        async getInspectors() {
            return await API.get('/supervisor/inspectors');
        },

        async getInspector(id) {
            return await API.get('/supervisor/inspectors', { id });
        },

        async addInspector(data) {
            return await API.post('/supervisor/inspectors', data);
        },

        async updateInspector(data) {
            return await API.put('/supervisor/inspectors', data);
        },

        async deleteInspector(id) {
            return await API.delete('/supervisor/inspectors', { id });
        },

        async getPendingRequests() {
            return await API.get('/supervisor/pending-requests');
        },

        async assignRequest(requestId, inspectorId, notes = '') {
            return await API.post('/supervisor/assign-inspector', {
                request_id: requestId,
                inspector_id: inspectorId,
                notes
            });
        },

        async getDailyReport(date) {
            return await API.get('/supervisor/reports', { type: 'daily', date });
        },

        async getWeeklyReport(week) {
            return await API.get('/supervisor/reports', { type: 'weekly', week });
        },

        async getAuditList() {
            return await API.get('/supervisor/quality-audit');
        },

        async approveInspection(id, notes = '') {
            return await API.post('/supervisor/quality-audit', { 
                id, 
                status: 'approved',
                notes 
            });
        },

        async rejectInspection(id, notes = '') {
            return await API.post('/supervisor/quality-audit', { 
                id, 
                status: 'rejected',
                notes 
            });
        },

        async getComplaints() {
            return await API.get('/supervisor/complaints');
        },

        async resolveComplaint(id, resolution) {
            return await API.put('/supervisor/complaints', { id, resolution });
        }
    },

    // ============================================
    // Admin APIs
    // ============================================
    admin: {
        async dashboard() {
            return await API.get('/admin/dashboard');
        },

        async getUsers() {
            return await API.get('/admin/users');
        },

        async getUser(id) {
            return await API.get('/admin/users', { id });
        },

        async createUser(data) {
            return await API.post('/admin/users', data);
        },

        async updateUser(data) {
            return await API.put('/admin/users', data);
        },

        async deleteUser(id) {
            return await API.delete('/admin/users', { id });
        },

        async getSettings() {
            return await API.get('/admin/settings');
        },

        async updateSettings(settings) {
            return await API.post('/admin/settings', settings);
        },

        async getStatistics() {
            return await API.get('/admin/statistics');
        },

        async getLogs() {
            return await API.get('/admin/logs');
        }
    },

    // ============================================
    // Common APIs
    // ============================================
    common: {
        async uploadFile(file, type = 'general') {
            const formData = new FormData();
            formData.append('file', file);
            formData.append('type', type);
            
            return await API.upload('/common/upload', formData);
        },

        async getNotifications() {
            return await API.get('/common/notifications');
        },

        async markNotificationRead(id = null) {
            return await API.post('/common/notifications', { id });
        },

        async search(query, type = 'all') {
            return await API.get('/common/search', { q: query, type });
        }
    },

    // ============================================
    // AI APIs
    // ============================================
    ai: {
        async estimateValue(vehicleData) {
            return await API.post('/ai/predict-value', vehicleData);
        },

        async healthCheck(vehicleId) {
            return await API.get('/ai/health-check', { vehicle_id: vehicleId });
        },

        async getRecommendations(vehicleData) {
            return await API.post('/ai/recommendations', vehicleData);
        },

        async askAssistant(message) {
            return await API.post('/ai/assistant', { message });
        }
    }
};

// ============================================
// Authentication Helper
// ============================================
const Auth = {
    /**
     * Check if user is authenticated
     */
    checkAuth(redirectTo = '/auth/login.html') {
        const user = API.getCurrentUser();
        const token = API.getToken();
        
        if (!user || !token) {
            window.location.href = redirectTo;
            return false;
        }
        return user;
    },

    /**
     * Check user role
     */
    checkRole(requiredRole, redirectTo = '/auth/unauthorized.html') {
        const user = this.checkAuth();
        if (!user) return false;
        
        if (user.role !== requiredRole) {
            window.location.href = redirectTo;
            return false;
        }
        return true;
    },

    /**
     * Check allowed roles
     */
    checkRoles(allowedRoles, redirectTo = '/auth/unauthorized.html') {
        const user = this.checkAuth();
        if (!user) return false;
        
        if (!allowedRoles.includes(user.role)) {
            window.location.href = redirectTo;
            return false;
        }
        return true;
    },

    /**
     * Refresh user data
     */
    async refreshUser() {
        try {
            const response = await API.client.profile();
            if (response.success) {
                API.setCurrentUser(response.user);
                return response.user;
            }
        } catch (error) {
            console.error('Error refreshing user:', error);
        }
        return null;
    },

    /**
     * Get role name in Arabic
     */
    getRoleName(role) {
        const roles = {
            'admin': '&#x0645;&#x062f;&#x064a;&#x0631; &#x0627;&#x0644;&#x0646;&#x0638;&#x0627;&#x0645;',
            'supervisor': '&#x0645;&#x0634;&#x0631;&#x0641;',
            'inspector': '&#x0641;&#x0627;&#x062d;&#x0635;',
            'client': '&#x0639;&#x0645;&#x064a;&#x0644;',
            'cashier': '&#x0623;&#x0645;&#x064a;&#x0646; &#x0635;&#x0646;&#x062f;&#x0648;&#x0642;'
        };
        return roles[role] || role;
    }
};

// ============================================
// Notification System
// ============================================
const Notifications = {
    /**
     * Show toast notification
     */
    show(message, type = 'info', duration = 5000) {
        const toast = document.createElement('div');
        toast.className = `toast-notification toast-${type}`;
        toast.innerHTML = `
            <i class="fas fa-${this.getIcon(type)}"></i>
            <span>${message}</span>
            <button class="close-toast" onclick="this.parentElement.remove()">
                <i class="fas fa-times"></i>
            </button>
        `;

        document.body.appendChild(toast);

        // Auto remove
        setTimeout(() => {
            toast.classList.add('toast-hide');
            setTimeout(() => toast.remove(), 300);
        }, duration);
    },

    /**
     * Get icon for notification type
     */
    getIcon(type) {
        const icons = {
            success: 'check-circle',
            error: 'exclamation-circle',
            warning: 'exclamation-triangle',
            info: 'info-circle'
        };
        return icons[type] || 'info-circle';
    },

    /**
     * Show success message
     */
    success(message, duration) {
        this.show(message, 'success', duration);
    },

    /**
     * Show error message
     */
    error(message, duration) {
        this.show(message, 'error', duration);
    },

    /**
     * Show warning message
     */
    warning(message, duration) {
        this.show(message, 'warning', duration);
    },

    /**
     * Show info message
     */
    info(message, duration) {
        this.show(message, 'info', duration);
    },

    /**
     * Show confirmation dialog
     */
    confirm(message, onConfirm, onCancel = null) {
        const modal = document.createElement('div');
        modal.className = 'modal active';
        modal.innerHTML = `
            <div class="modal-content">
                <div class="modal-header">
                    <h3><i class="fas fa-question-circle"></i> &#x062a;&#x0623;&#x0643;&#x064a;&#x062f;</h3>
                    <button class="close-modal" onclick="this.closest('.modal').remove()">
                        <i class="fas fa-times"></i>
                    </button>
                </div>
                <div class="modal-body">
                    <p>${message}</p>
                </div>
                <div class="modal-footer">
                    <button class="btn btn-outline" onclick="this.closest('.modal').remove()">
                        <i class="fas fa-times"></i> &#x0625;&#x0644;&#x063a;&#x0627;&#x0621;
                    </button>
                    <button class="btn btn-primary" id="confirmBtn">
                        <i class="fas fa-check"></i> &#x062a;&#x0623;&#x0643;&#x064a;&#x062f;
                    </button>
                </div>
            </div>
        `;

        document.body.appendChild(modal);

        modal.querySelector('#confirmBtn').addEventListener('click', () => {
            modal.remove();
            if (onConfirm) onConfirm();
        });

        modal.querySelector('.close-modal, .btn-outline').addEventListener('click', () => {
            modal.remove();
            if (onCancel) onCancel();
        });
    }
};

// ============================================
// Form Validation
// ============================================
const Validator = {
    /**
     * Validate form
     */
    validate(form, rules) {
        const errors = {};
        let isValid = true;

        for (const field in rules) {
            const element = form.querySelector(`[name="${field}"]`);
            if (!element) continue;

            const value = element.value.trim();
            const fieldRules = rules[field];

            // Required validation
            if (fieldRules.required && !value) {
                errors[field] = `${fieldRules.label || field} &#x0645;&#x0637;&#x0644;&#x0648;&#x0628;';
                isValid = false;
                continue;
            }

            // Skip other validations if field is empty and not required
            if (!value && !fieldRules.required) continue;

            // Email validation
            if (fieldRules.email && !Utils.validateEmail(value)) {
                errors[field] = `${fieldRules.label || field} &#x063a;&#x064a;&#x0631; &#x0635;&#x062d;&#x064a;&#x062d;`;
                isValid = false;
            }

            // Phone validation
            if (fieldRules.phone && !Utils.validatePhone(value)) {
                errors[field] = `${fieldRules.label || field} &#x063a;&#x064a;&#x0631; &#x0635;&#x062d;&#x064a;&#x062d;`;
                isValid = false;
            }

            // Min length validation
            if (fieldRules.minLength && value.length < fieldRules.minLength) {
                errors[field] = `${fieldRules.label || field} &#x064a;&#x062c;&#x0628; &#x0623;&#x0646; &#x064a;&#x0643;&#x0648;&#x0646; ${fieldRules.minLength} &#x062d;&#x0631;&#x0641;&#x0627;&#x064b;`;
                isValid = false;
            }

            // Max length validation
            if (fieldRules.maxLength && value.length > fieldRules.maxLength) {
                errors[field] = `${fieldRules.label || field} &#x0644;&#x0627; &#x064a;&#x0632;&#x064a;&#x062f; ${fieldRules.maxLength} &#x062d;&#x0631;&#x0641;&#x0627;&#x064b;`;
                isValid = false;
            }

            // Pattern validation
            if (fieldRules.pattern && !new RegExp(fieldRules.pattern).test(value)) {
                errors[field] = fieldRules.message || `${fieldRules.label || field} &#x063a;&#x064a;&#x0631; &#x0635;&#x062d;&#x064a;&#x062d;`;
                isValid = false;
            }
        }

        return { isValid, errors };
    },

    /**
     * Show form errors
     */
    showErrors(form, errors) {
        // Clear previous errors
        form.querySelectorAll('.error-message').forEach(el => el.remove());
        form.querySelectorAll('.form-control.error').forEach(el => el.classList.remove('error'));

        for (const field in errors) {
            const element = form.querySelector(`[name="${field}"]`);
            if (!element) continue;

            element.classList.add('error');

            const errorDiv = document.createElement('div');
            errorDiv.className = 'error-message';
            errorDiv.textContent = errors[field];
            errorDiv.style.color = 'var(--danger)';
            errorDiv.style.fontSize = 'var(--font-size-sm)';
            errorDiv.style.marginTop = 'var(--spacing-1)';

            element.parentNode.appendChild(errorDiv);
        }
    },

    /**
     * Clear form errors
     */
    clearErrors(form) {
        form.querySelectorAll('.error-message').forEach(el => el.remove());
        form.querySelectorAll('.form-control.error').forEach(el => el.classList.remove('error'));
    }
};

// ============================================
// Theme Manager
// ============================================
const Theme = {
    /**
     * Get current theme
     */
    getCurrent() {
        return localStorage.getItem(CONFIG.THEME_KEY) || 'light';
    },

    /**
     * Set theme
     */
    set(theme) {
        localStorage.setItem(CONFIG.THEME_KEY, theme);
        document.documentElement.setAttribute('data-theme', theme);
    },

    /**
     * Toggle theme
     */
    toggle() {
        const current = this.getCurrent();
        const newTheme = current === 'light' ? 'dark' : 'light';
        this.set(newTheme);
        return newTheme;
    },

    /**
     * Initialize theme
     */
    init() {
        this.set(this.getCurrent());
    }
};

// ============================================
// Loading Manager
// ============================================
const Loading = {
    /**
     * Show loading spinner
     */
    show(container = document.body) {
        const loader = document.createElement('div');
        loader.className = 'loader-container';
        loader.innerHTML = `
            <div class="spinner"></div>
            <p>&#x062c;&#x0627;&#x0631;&#x064a; &#x0627;&#x0644;&#x062a;&#x062d;&#x0645;&#x064a;&#x0644;...</p>
        `;
        loader.style.position = 'absolute';
        loader.style.top = '0';
        loader.style.left = '0';
        loader.style.right = '0';
        loader.style.bottom = '0';
        loader.style.background = 'rgba(255, 255, 255, 0.9)';
        loader.style.display = 'flex';
        loader.style.alignItems = 'center';
        loader.style.justifyContent = 'center';
        loader.style.zIndex = '9999';

        container.style.position = 'relative';
        container.appendChild(loader);
        return loader;
    },

    /**
     * Hide loading spinner
     */
    hide(loader) {
        if (loader) {
            loader.remove();
        }
    }
};

// ============================================
// Navigation Manager
// ============================================
const Navigation = {
    /**
     * Initialize navigation
     */
    init() {
        this.setupUserMenu();
        this.setupNotifications();
        this.setupThemeToggle();
    },

    /**
     * Setup user menu
     */
    setupUserMenu() {
        const user = API.getCurrentUser();
        if (!user) return;

        const userElements = document.querySelectorAll('.user-name');
        userElements.forEach(el => {
            el.textContent = user.full_name || user.username;
        });

        const roleElements = document.querySelectorAll('.user-role');
        roleElements.forEach(el => {
            el.textContent = Auth.getRoleName(user.role);
        });
    },

    /**
     * Setup notifications
     */
    setupNotifications() {
        const notificationBell = document.querySelector('.notification-bell');
        if (!notificationBell) return;

        notificationBell.addEventListener('click', async () => {
            try {
                const notifications = await API.common.getNotifications();
                this.showNotificationDropdown(notifications.data || []);
            } catch (error) {
                console.error('Error loading notifications:', error);
            }
        });
    },

    /**
     * Show notification dropdown
     */
    showNotificationDropdown(notifications) {
        // Implementation for notification dropdown
        console.log('Notifications:', notifications);
    },

    /**
     * Setup theme toggle
     */
    setupThemeToggle() {
        const themeToggle = document.querySelector('.theme-toggle');
        if (!themeToggle) return;

        themeToggle.addEventListener('click', () => {
            Theme.toggle();
        });
    }
};

// ============================================
// Application Initialization
// ============================================
const App = {
    /**
     * Initialize application
     */
    init() {
        // Initialize theme
        Theme.init();

        // Initialize navigation
        Navigation.init();

        // Setup global error handler
        window.addEventListener('error', (event) => {
            console.error('Global error:', event.error);
            if (CONFIG.DEBUG) {
                Notifications.error('&#x062d;&#x062f;&#x062b; &#x062e;&#x0637;&#x0623; &#x063a;&#x064a;&#x0631; &#x0645;&#x062a;&#x0648;&#x0642;&#x0639;. &#x064a;&#x0631;&#x062c;&#x0649; &#x0627;&#x0644;&#x0645;&#x062d;&#x0627;&#x0648;&#x0644;&#x0629; &#x0641;&#x064a; &#u0645;&#x0633;&#x062a;&#x0642;&#x0628;&#x0644; &#x0627;&#x0644;&#x0645;&#x0637;&#x0648;&#x064a;');
            }
        });

        // Setup form validation
        document.addEventListener('submit', (event) => {
            const form = event.target;
            if (form.dataset.validate) {
                event.preventDefault();
                this.handleFormSubmit(form);
            }
        });

        console.log(`${CONFIG.APP_NAME} v${CONFIG.VERSION} initialized`);
    },

    /**
     * Handle form submission
     */
    async handleFormSubmit(form) {
        const rules = JSON.parse(form.dataset.validate || '{}');
        const { isValid, errors } = Validator.validate(form, rules);

        if (!isValid) {
            Validator.showErrors(form, errors);
            return;
        }

        // Show loading
        const loader = Loading.show(form);

        try {
            const formData = new FormData(form);
            const data = Object.fromEntries(formData.entries());

            const apiEndpoint = form.dataset.api;
            if (apiEndpoint) {
                const response = await API.post(apiEndpoint, data);
                
                if (response.success) {
                    Notifications.success(response.message || '&#x062a;&#x0645; &#x0627;&#x0644;&#x062a;&#x0646;&#x0641;&#x064a;&#x0630; &#x0628;&#x0646;&#x062c;&#x0627;&#x062d;');
                    
                    // Reset form if specified
                    if (form.dataset.reset === 'true') {
                        form.reset();
                    }

                    // Redirect if specified
                    const redirect = form.dataset.redirect;
                    if (redirect) {
                        setTimeout(() => {
                            window.location.href = redirect;
                        }, 1000);
                    }
                } else {
                    Notifications.error(response.message || '&#x062d;&#x062f;&#x062b; &#x062e;&#x0637;&#x0623;');
                }
            }
        } catch (error) {
            console.error('Form submission error:', error);
            Notifications.error('&#x062d;&#x062f;&#x062b; &#x0641;&#x064a; &#x0627;&#x062a;&#x0635;&#x0627;&#x0644; &#x0627;&#x0644;&#x062e;&#x0627;&#x062f;&#x0645;. &#x064a;&#x0631;&#x062c;&#x0649; &#x0627;&#x0644;&#x0645;&#x062d;&#x0627;&#x0648;&#x0644;&#x0629; &#x0644;&#x0627;&#x062d;&#x0642;&#x0627;&#x064b;');
        } finally {
            Loading.hide(loader);
        }
    }
};

// ============================================
// Export to global scope
// ============================================
window.CONFIG = CONFIG;
window.Utils = Utils;
window.API = API;
window.Auth = Auth;
window.Notifications = Notifications;
window.Validator = Validator;
window.Theme = Theme;
window.Loading = Loading;
window.Navigation = Navigation;
window.App = App;

// ============================================
// Auto-initialize when DOM is ready
// ============================================
document.addEventListener('DOMContentLoaded', () => {
    App.init();
});

// ============================================
// Legacy function support
// ============================================
window.formatDate = Utils.formatDate;
window.formatDateTime = Utils.formatDateTime;
window.formatPrice = Utils.formatPrice;
window.showMessage = Notifications.info;
