// admin/assets/js/admin-script.js - تحسينات شاملة

// انتظار تحميل DOM
document.addEventListener('DOMContentLoaded', function() {
    initMobileOptimizations();
    initFormValidation();
    initImagePreview();
    initAutoRefresh();
    initTooltips();
    initPullToRefresh();
    initSafeAreaSupport();
});

// تحسينات الجوال
function initMobileOptimizations() {
    // Fix 100vh on mobile
    const setVH = () => {
        const vh = window.innerHeight * 0.01;
        document.documentElement.style.setProperty('--vh', `${vh}px`);
    };
    
    setVH();
    window.addEventListener('resize', setVH);
    window.addEventListener('orientationchange', setVH);
    
    // Prevent zoom on input focus for iOS
    if (/iPhone|iPad|iPod/i.test(navigator.userAgent)) {
        document.querySelectorAll('input, select, textarea').forEach(el => {
            el.style.fontSize = '16px';
        });
    }
    
    // تحسين التمرير
    document.querySelectorAll('.modal-body, .messages-container, .tickets-list, .table-responsive').forEach(el => {
        el.style.webkitOverflowScrolling = 'touch';
    });
}

// تحسين النماذج
function initFormValidation() {
    document.querySelectorAll('form').forEach(form => {
        form.addEventListener('submit', function(e) {
            const requiredInputs = this.querySelectorAll('[required]');
            let firstInvalid = null;
            
            requiredInputs.forEach(input => {
                if (!input.value.trim()) {
                    input.classList.add('is-invalid');
                    
                    if (!firstInvalid) {
                        firstInvalid = input;
                    }
                    
                    // رسالة خطأ مخصصة
                    const feedback = document.createElement('div');
                    feedback.className = 'invalid-feedback';
                    feedback.textContent = 'هذا الحقل مطلوب';
                    
                    if (!input.nextElementSibling?.classList.contains('invalid-feedback')) {
                        input.insertAdjacentElement('afterend', feedback);
                    }
                } else {
                    input.classList.remove('is-invalid');
                }
            });
            
            if (firstInvalid) {
                e.preventDefault();
                firstInvalid.scrollIntoView({ behavior: 'smooth', block: 'center' });
                firstInvalid.focus();
                showNotification('الرجاء ملء جميع الحقول المطلوبة', 'warning');
            }
        });
    });
}

// معاينة الصور
function initImagePreview() {
    document.querySelectorAll('input[type="file"][accept*="image"]').forEach(input => {
        input.addEventListener('change', function(e) {
            const previewId = this.getAttribute('data-preview');
            if (!previewId) return;
            
            const preview = document.getElementById(previewId);
            if (!preview) return;
            
            if (this.files && this.files[0]) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    preview.src = e.target.result;
                    preview.style.display = 'block';
                };
                reader.readAsDataURL(this.files[0]);
            }
        });
    });
}

// التحديث التلقائي
function initAutoRefresh() {
    const autoRefreshToggle = document.getElementById('autoRefreshToggle');
    if (!autoRefreshToggle) return;
    
    let interval;
    
    function startRefresh() {
        if (interval) clearInterval(interval);
        interval = setInterval(() => {
            if (!document.hidden) {
                location.reload();
            }
        }, 30000);
    }
    
    function stopRefresh() {
        if (interval) {
            clearInterval(interval);
            interval = null;
        }
    }
    
    autoRefreshToggle.addEventListener('change', function() {
        if (this.checked) {
            startRefresh();
            showNotification('تم تفعيل التحديث التلقائي', 'success');
        } else {
            stopRefresh();
            showNotification('تم إيقاف التحديث التلقائي', 'info');
        }
    });
    
    // إيقاف التحديث عند مغادرة الصفحة
    window.addEventListener('beforeunload', stopRefresh);
}

// إظهار الإشعارات
function showNotification(message, type = 'info', duration = 3000) {
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    
    const icons = {
        success: 'bi-check-circle-fill',
        danger: 'bi-exclamation-triangle-fill',
        warning: 'bi-exclamation-circle-fill',
        info: 'bi-info-circle-fill'
    };
    
    notification.innerHTML = `
        <i class="bi ${icons[type] || icons.info}"></i>
        <span>${message}</span>
    `;
    
    Object.assign(notification.style, {
        position: 'fixed',
        bottom: '20px',
        left: '50%',
        transform: 'translateX(-50%)',
        backgroundColor: type === 'success' ? '#10b981' :
                        type === 'danger' ? '#ef4444' :
                        type === 'warning' ? '#f59e0b' : '#3b82f6',
        color: 'white',
        padding: '12px 24px',
        borderRadius: '50px',
        boxShadow: '0 4px 15px rgba(0,0,0,0.2)',
        zIndex: '9999',
        display: 'flex',
        alignItems: 'center',
        gap: '10px',
        fontSize: '14px',
        fontWeight: '500',
        animation: 'slideUp 0.3s ease'
    });
    
    document.body.appendChild(notification);
    
    setTimeout(() => {
        notification.style.animation = 'slideDown 0.3s ease';
        setTimeout(() => notification.remove(), 300);
    }, duration);
}

// إضافة أنماط CSS للرسوم المتحركة
const style = document.createElement('style');
style.textContent = `
    @keyframes slideUp {
        from {
            transform: translate(-50%, 100%);
            opacity: 0;
        }
        to {
            transform: translate(-50%, 0);
            opacity: 1;
        }
    }
    
    @keyframes slideDown {
        from {
            transform: translate(-50%, 0);
            opacity: 1;
        }
        to {
            transform: translate(-50%, 100%);
            opacity: 0;
        }
    }
    
    .is-invalid {
        border-color: #ef4444 !important;
    }
    
    .invalid-feedback {
        color: #ef4444;
        font-size: 0.85rem;
        margin-top: 0.25rem;
    }
    
    .notification {
        min-width: 280px;
        max-width: 90%;
        text-align: center;
    }
`;
document.head.appendChild(style);

// تحسين السحب للتحديث
function initPullToRefresh() {
    const container = document.querySelector('.main-content');
    if (!container) return;
    
    let touchStartY = 0;
    let touchEndY = 0;
    const threshold = 100;
    
    container.addEventListener('touchstart', function(e) {
        if (this.scrollTop === 0) {
            touchStartY = e.touches[0].clientY;
        }
    }, { passive: true });
    
    container.addEventListener('touchmove', function(e) {
        if (touchStartY > 0) {
            touchEndY = e.touches[0].clientY;
            const diff = touchEndY - touchStartY;
            
            if (diff > threshold) {
                showPullToRefresh();
            }
        }
    }, { passive: true });
    
    container.addEventListener('touchend', function() {
        touchStartY = 0;
        touchEndY = 0;
    }, { passive: true });
}

function showPullToRefresh() {
    const indicator = document.createElement('div');
    indicator.className = 'pull-to-refresh';
    indicator.innerHTML = '<div class="spinner-border text-primary" role="status"></div>';
    
    Object.assign(indicator.style, {
        position: 'fixed',
        top: '20px',
        left: '50%',
        transform: 'translateX(-50%)',
        background: 'white',
        padding: '15px',
        borderRadius: '50%',
        boxShadow: '0 4px 15px rgba(0,0,0,0.2)',
        zIndex: '9999'
    });
    
    document.body.appendChild(indicator);
    
    setTimeout(() => {
        indicator.remove();
        location.reload();
    }, 1000);
}

// دعم safe areas
function initSafeAreaSupport() {
    if (CSS.supports('padding: env(safe-area-inset-bottom)')) {
        document.body.style.paddingBottom = 'env(safe-area-inset-bottom)';
    }
}

// تفعيل tooltips
function initTooltips() {
    const tooltips = document.querySelectorAll('[data-bs-toggle="tooltip"]');
    if (tooltips.length > 0 && typeof bootstrap !== 'undefined') {
        tooltips.forEach(el => new bootstrap.Tooltip(el));
    }
}