// كود لجعل شريط التنقل ثابتًا عند التمرير
window.addEventListener('scroll', function() {
    const header = document.querySelector('header');
    if (!header) return;
    if (window.scrollY > 50) {
        header.style.boxShadow = '0 2px 15px rgba(0, 0, 0, 0.1)';
        header.style.background = '#fff';
    } else {
        header.style.boxShadow = 'none';
        header.style.background = '#fff';
    }
});

// زر القائمة للموبايل
document.addEventListener('DOMContentLoaded', function() {
    const menuBtn = document.querySelector('.mobile-menu-btn');
    const nav = document.querySelector('header nav');
    const headerContact = document.querySelector('.header-contact');
    if (menuBtn && nav) {
        menuBtn.addEventListener('click', function() {
            nav.classList.toggle('active');
            if (headerContact) {
                headerContact.classList.toggle('active');
            }
            // تغيير أيقونة الزر
            const icon = menuBtn.querySelector('i');
            if (nav.classList.contains('active')) {
                icon.classList.remove('fa-bars');
                icon.classList.add('fa-times');
            } else {
                icon.classList.remove('fa-times');
                icon.classList.add('fa-bars');
            }
        });

        // إغلاق القائمة عند الضغط على رابط
        nav.querySelectorAll('a').forEach(function(link) {
            link.addEventListener('click', function() {
                nav.classList.remove('active');
                if (headerContact) {
                    headerContact.classList.remove('active');
                }
                const icon = menuBtn.querySelector('i');
                icon.classList.remove('fa-times');
                icon.classList.add('fa-bars');
            });
        });
    }
});

// كود لنموذج الحجز مع تحسينات
const bookingForm = document.getElementById('quick-booking-form');
if (bookingForm) {
    bookingForm.addEventListener('submit', function(e) {
        e.preventDefault();

        // جمع بيانات النموذج
        const name = this.querySelector('input[type="text"]').value.trim();
        const phone = this.querySelector('input[type="tel"]').value.trim();
        const service = this.querySelector('select').value;

        // تحقق من صحة رقم الجوال اليمني
        const phoneRegex = /^(7|01|05|77|78|79|70|71|73|72|74|75|76|77|78|79)\d{6,8}$/;
        if (!name || !phone || !service) {
            showSuccessMsg('يرجى تعبئة جميع الحقول.');
            return;
        }
        if (!phoneRegex.test(phone)) {
            showSuccessMsg('يرجى إدخال رقم جوال صحيح.');
            return;
        }

        // عرض رسالة نجاح جذابة
        showSuccessMsg(`شكراً لك ${name}! تم استلام طلبك وسنتواصل معك على الرقم ${phone} خلال دقائق.`);

             // فتح واتساب تلقائياً مع رسالة جاهزة إلى رقم الورشة
        setTimeout(() => {
            // إرسال إلى رقم المركز الموحد (مالك الموقع)
            const owner = '967784396822';
            const text = `مرحباً، لدي طلب حجز:\nالاسم: ${name}\nجوال العميل: ${phone}\nالخدمة: ${service}`;
            window.open(`https://wa.me/${owner}?text=${encodeURIComponent(text)}`, '_blank');
        }, 1200);

        this.reset();
    });
}

// رسالة نجاح عصرية
function showSuccessMsg(msg) {
    let msgBox = document.getElementById('successMsgBox');
    if (!msgBox) {
        msgBox = document.createElement('div');
        msgBox.id = 'successMsgBox';
        msgBox.style.position = 'fixed';
        msgBox.style.top = '30px';
        msgBox.style.left = '50%';
        msgBox.style.transform = 'translateX(-50%)';
        msgBox.style.background = '#2563eb';
        msgBox.style.color = '#fff';
        msgBox.style.padding = '18px 32px';
        msgBox.style.borderRadius = '8px';
        msgBox.style.fontSize = '1.1rem';
        msgBox.style.zIndex = '9999';
        msgBox.style.boxShadow = '0 4px 24px rgba(37,99,235,0.15)';
        document.body.appendChild(msgBox);
    }
    msgBox.innerText = msg;
    msgBox.style.display = 'block';
    setTimeout(() => { msgBox.style.display = 'none'; }, 3500);
}

// كود لإضافة تأثير التمرير السلس للروابط
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        const targetId = this.getAttribute('href');
        if (!targetId || targetId === '#') return;
        const targetElement = document.querySelector(targetId);
        if (targetElement) {
            e.preventDefault();
            targetElement.scrollIntoView({
                behavior: 'smooth',
                block: 'start'
            });
        }
    });
});

// كود لتهيئة الخريطة
function initMap() {
    if (typeof L === 'undefined') return;
    const workshopLocation = [15.392064, 44.188224];
    const map = L.map('map').setView(workshopLocation, 15);
    L.tileLayer('https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors'
    }).addTo(map);
    L.marker(workshopLocation).addTo(map)
        .bindPopup('مركز نيوتك<br> صنعاء - حي النهضة<br><a href="https://goo.gl/maps/tyVjEDns8yZc8Yum6?g_st=aw" target="_blank" rel="noopener">عرض على الخريطة</a>')
        .openPopup();
}

document.addEventListener('DOMContentLoaded', function() {
    if (document.getElementById('map')) {
        initMap();
    }
});

// تهيئة الخريطة عند تحميل الصفحة + تأثيرات عند التمرير + عداد الإحصاءات
document.addEventListener('DOMContentLoaded', function() {
    // إذا كان هناك عنصر خريطة في الصفحة
    if (document.getElementById('map')) {
        initMap();
    }

    // إضافة تأثيرات للعناصر عند التمرير   
    const animateOnScroll = function() {   
        const elements = document.querySelectorAll('.service-item, .feature, .testimonial, .gallery-item');
        elements.forEach(element => {
            const elementPosition = element.getBoundingClientRect().top;
            const screenPosition = window.innerHeight / 1.3;
            if (elementPosition < screenPosition) {
                element.style.opacity = 1;
                element.style.transform = 'translateY(0)';
            }
        });
    };

    // تهيئة الخصائص الأولية للعناصر
    const items = document.querySelectorAll('.service-item, .feature, .testimonial, .gallery-item');
    items.forEach(item => {
        item.style.opacity = 0;
        item.style.transform = 'translateY(20px)';
        item.style.transition = 'all 0.6s ease';
    });

    // تفعيل عند التمرير
    window.addEventListener('scroll', animateOnScroll);
    // تفعيل مرة أولى عند التحميل
    animateOnScroll();

    // تفعيل عداد الإحصاءات عند ظهورها
    const counters = document.querySelectorAll('.counter');
    if (counters.length > 0) {
        const observer = new IntersectionObserver((entries, obs) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    startCounter(entry.target);
                    obs.unobserve(entry.target);
                }
            });
        }, { threshold: 0.7 });
        counters.forEach(counter => observer.observe(counter));
    }
});

// عداد إحصاءات فردي
function startCounter(counter) {
    const target = +counter.getAttribute('data-target');
    const speed = 200;
    let count = 0;
    const increment = Math.ceil(target / speed);

    function update() {
        if (count < target) {
            count += increment;
            counter.innerText = Math.min(count, target);
            setTimeout(update, 10);
        } else {
            counter.innerText = target;
        }
    }
    update();
}

// كود زر "العودة إلى الأعلى"
const backToTop = document.getElementById('backToTop');
if (backToTop) {
    window.addEventListener('scroll', () => {
        if (window.scrollY > 300) {
            backToTop.style.display = 'block';
        } else {
            backToTop.style.display = 'none';
        }
    });
    backToTop.addEventListener('click', () => {
        window.scrollTo({ top: 0, behavior: 'smooth' });
    });
}

// إرسال نموذج التواصل إلى واتساب
document.addEventListener('DOMContentLoaded', function() {
    const contactForm = document.querySelector('.contact-form') || document.querySelector('.contact-form-modern');
    if (contactForm) {
        contactForm.addEventListener('submit', function(e) {
            e.preventDefault();
            const name = (contactForm.querySelector('input[type="text"]') || contactForm.querySelector('#contact-name')).value.trim();
            const phone = (contactForm.querySelector('input[type="tel"]') || contactForm.querySelector('#contact-phone')).value.trim();
            const emailEl = contactForm.querySelector('input[type="email"]') || contactForm.querySelector('#contact-email');
            const email = emailEl ? emailEl.value.trim() : '';
            const messageEl = contactForm.querySelector('textarea') || contactForm.querySelector('#contact-message');
            const message = messageEl ? messageEl.value.trim() : '';

            let whatsappMsg = `مرحباً، لدي رسالة من الموقع:\n`;
            whatsappMsg += `الاسم: ${name}\n`;
            whatsappMsg += `رقم الجوال: ${phone}\n`;
            if(email) whatsappMsg += `البريد الإلكتروني: ${email}\n`;
            whatsappMsg += `الرسالة: ${message}`;

            window.open(`https://wa.me/967784396822?text=${encodeURIComponent(whatsappMsg)}`, '_blank');
        });
    }
});

// كود لتحسين عرض الصور في المعرض
const galleryItems = document.querySelectorAll('.gallery-item');
const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if(entry.isIntersecting) {
            entry.target.classList.add('fadeInUp');
        }
    });
}, { threshold: 0.2 });

galleryItems.forEach(item => observer.observe(item));

 // كود لتحسين أداء تحميل الصور
 document.addEventListener('DOMContentLoaded', function() {
    const lazyImages = document.querySelectorAll('img[data-src]');
    const imageObserver = new IntersectionObserver((entries) => {
        entries.forEach(entry => {
            if(entry.isIntersecting) {
                const img = entry.target;
                img.src = img.dataset.src;
                img.onload = () => img.classList.add('fadeIn');
                imageObserver.unobserve(img);
            }
        });
    }, { threshold: 0.2 });

    lazyImages.forEach(img => imageObserver.observe(img));
});

// كود لتحسين أداء تحميل خريطة الموقع
document.addEventListener('DOMContentLoaded', function() {
    const map = document.getElementById('map');
    if (map) {
        const mapObserver = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    // تحميل خريطة جوجل
                    const script = document.createElement('script');
                    script.src = 'https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap';
                    document.body.appendChild(script);
                    mapObserver.unobserve(map);
                }
            });
        }, { threshold: 0.2 });

        mapObserver.observe(map);
    }
});

// كود لتحسين أداء تحميل خريطة الموقع باستخدام Leaflet
document.addEventListener('DOMContentLoaded', function() {
    const map = document.getElementById('map');
    if (map) {
        const mapObserver = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    // تحميل خريطة Leaflet
                    const script = document.createElement('script');
                    script.src = 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.js';
                    document.body.appendChild(script);
                    mapObserver.unobserve(map);
                }
            });
        }, { threshold: 0.2 });

        mapObserver.observe(map);
    }
});
// كود لتحسين أداء تحميل خطوط جوجل
document.addEventListener('DOMContentLoaded', function() {
    const link = document.createElement('link');
    link.href = 'https://fonts.googleapis.com/css2?family=Cairo:wght@400;600;700&display=swap';
    link.rel = 'stylesheet';
    document.head.appendChild(link);
});

// كود لتحسين أداء تحميل مكتبة Font Awesome
document.addEventListener('DOMContentLoaded', function() {
    const link = document.createElement('link');
    link.href = 'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css';
    link.rel = 'stylesheet';
    document.head.appendChild(link);
});
// كود لتحسين أداء تحميل مكتبة AOS
document.addEventListener('DOMContentLoaded', function() {
    const link = document.createElement('link');
    link.href = 'https://cdnjs.cloudflare.com/ajax/libs/aos/2.3.1/aos.css';
    link.rel = 'stylesheet';
    document.head.appendChild(link);
});

// كود لتحسين أداء تحميل مكتبة AOS
document.addEventListener('DOMContentLoaded', function() {
    const script = document.createElement('script');
    script.src = 'https://cdnjs.cloudflare.com/ajax/libs/aos/2.3.1/aos.js';
    document.body.appendChild(script);
});

      // عداد الإحصائيات
      const counters = document.querySelectorAll('.counter');
      const speed = 200; // سرعة العد

      counters.forEach(counter => {
        const updateCount = () => {
          const target = +counter.getAttribute('data-target');
          const count = +counter.innerText;

          const increment = target / speed;

          if (count < target) {
            counter.innerText = Math.ceil(count + increment);
            setTimeout(updateCount, 1);
          } else {
            counter.innerText = target;
          }
        };

        updateCount();
         }); 
                // تبويبات تفاعلية لقسم المعرفة
                document.addEventListener('DOMContentLoaded', function() {
                    const tabBtns = document.querySelectorAll('.knowledge-tab-btn');
                    const tabContents = document.querySelectorAll('.knowledge-tab-content');
                    tabBtns.forEach(btn => {
                        btn.addEventListener('click', function() {
                            tabBtns.forEach(b => b.classList.remove('active'));
                            tabContents.forEach(c => c.classList.remove('active'));
                            btn.classList.add('active');
                            document.getElementById('tab-' + btn.dataset.tab).classList.add('active');
                        })
                    });
                });


                document.addEventListener('DOMContentLoaded', function() {
    const addBtn = document.getElementById('add-review-btn');
    const formWrapper = document.getElementById('review-form-wrapper');
    const cancelBtn = document.getElementById('cancel-review-btn');
    const stars = document.querySelectorAll('.star-rating .star');
    const starsInput = document.getElementById('reviewer-stars');
    const reviewsList = document.getElementById('reviews-list');
    const form = document.getElementById('review-form');

    // 🔹 دالة لحفظ التقييمات
    function saveReviews() {
        const reviews = [];
        document.querySelectorAll('.review-item').forEach(item => {
            reviews.push({
                name: item.querySelector('.review-header strong').textContent,
                stars: item.querySelectorAll('.review-stars .star.selected').length,
                comment: item.querySelector('.review-comment').textContent
            });
        });
        localStorage.setItem('reviews', JSON.stringify(reviews));
    }

    // 🔹 دالة لتحميل التقييمات
    function loadReviews() {
        const saved = localStorage.getItem('reviews');
        if (saved) {
            const reviews = JSON.parse(saved);
            reviews.forEach(r => {
                addReviewToDOM(r.name, r.stars, r.comment, false);
            });
        }
    }

    // 🔹 إضافة تقييم للواجهة
    function addReviewToDOM(name, stars, comment, save = true) {
        const reviewDiv = document.createElement('div');
        reviewDiv.className = 'review-item';
        let starsHtml = '';
        for (let i = 0; i < stars; i++) starsHtml += '<span class="star selected">★</span>';
        for (let i = stars; i < 5; i++) starsHtml += '<span class="star">★</span>';
        
        reviewDiv.innerHTML = `
            <div class='review-header'>
                <strong>${name}</strong>
                <span class='review-stars'>${starsHtml}</span>
                <button class="delete-btn">X</button>
            </div>
            <div class='review-comment'>${comment}</div>
        `;

        // 🔹 وظيفة زر الحذف
        reviewDiv.querySelector('.delete-btn').addEventListener('click', () => {
            reviewDiv.remove();
            saveReviews();
        });

        reviewsList.prepend(reviewDiv);
        if (save) saveReviews();
    }

    // 🔹 عرض النموذج
    addBtn.onclick = function() {
        formWrapper.style.display = 'block';
        addBtn.style.display = 'none';
    };

    // 🔹 إلغاء النموذج
    cancelBtn.onclick = function() {
        formWrapper.style.display = 'none';
        addBtn.style.display = 'inline-block';
    };

    // 🔹 تفاعل النجوم
    stars.forEach(star => {
        star.addEventListener('mouseenter', function() {
            const val = parseInt(star.dataset.value);
            stars.forEach((s, i) => { s.classList.toggle('hovered', i < val); });
        });
        star.addEventListener('mouseleave', function() {
            stars.forEach(s => s.classList.remove('hovered'));
        });
        star.addEventListener('click', function() {
            const val = parseInt(star.dataset.value);
            starsInput.value = val;
            stars.forEach(s => s.classList.remove('selected'));
            for (let i = 0; i < val; i++) stars[i].classList.add('selected');
        });
    });

    // 🔹 عند إرسال التقييم
    form.onsubmit = function(e) {
        e.preventDefault();
        const name = document.getElementById('reviewer-name').value.trim();
        const starsVal = parseInt(starsInput.value);
        const comment = document.getElementById('reviewer-comment').value.trim();
        if (!name || !comment || starsVal < 1) return;
        addReviewToDOM(name, starsVal, comment);
        form.reset();
        starsInput.value = 0;
        document.querySelectorAll('.star-rating .star').forEach(s => s.classList.remove('selected'));
        formWrapper.style.display = 'none';
        addBtn.style.display = 'inline-block';
    };

    // 🔹 تحميل التقييمات عند فتح الصفحة
    loadReviews();
});