/* ===== NAVBAR MENU CODE ===== */

// Mobile menu toggle
const mobileMenuButton = document.getElementById('mobile-menu-button');
const mobileMenu = document.getElementById('mobile-menu');

if (mobileMenuButton && mobileMenu) {
    mobileMenuButton.addEventListener('click', (e) => {
        e.stopPropagation();
        mobileMenu.classList.toggle('hidden');
        mobileMenuButton.classList.toggle('hamburger-active');
    });
}

// Mobile dropdown toggles
const mobileDropdownToggles = document.querySelectorAll('.mobile-dropdown-toggle');

mobileDropdownToggles.forEach(toggle => {
    toggle.addEventListener('click', (e) => {
        e.stopPropagation();
        const dropdown = toggle.nextElementSibling;
        const icon = toggle.querySelector('svg');

        // Close other dropdowns
        mobileDropdownToggles.forEach(otherToggle => {
            if (otherToggle !== toggle) {
                const otherDropdown = otherToggle.nextElementSibling;
                const otherIcon = otherToggle.querySelector('svg');
                if (otherDropdown) otherDropdown.classList.remove('active');
                if (otherIcon) otherIcon.classList.remove('rotate-180');
            }
        });

        // Toggle current dropdown
        if (dropdown) dropdown.classList.toggle('active');
        if (icon) icon.classList.toggle('rotate-180');
    });
});

// Close mobile menu when clicking outside
document.addEventListener('click', (e) => {
    if (mobileMenuButton && mobileMenu &&
        !mobileMenuButton.contains(e.target) &&
        !mobileMenu.contains(e.target)) {
        mobileMenu.classList.add('hidden');
        mobileMenuButton.classList.remove('hamburger-active');

        // Close all mobile dropdowns
        const mobileDropdowns = document.querySelectorAll('.mobile-dropdown');
        const dropdownIcons = document.querySelectorAll('.mobile-dropdown-toggle svg');

        mobileDropdowns.forEach(dropdown => {
            dropdown.classList.remove('active');
        });

        dropdownIcons.forEach(icon => {
            icon.classList.remove('rotate-180');
        });
    }
});

// Close mobile menu when window is resized to desktop size
window.addEventListener('resize', () => {
    if (window.innerWidth >= 1024 && mobileMenu) {
        mobileMenu.classList.add('hidden');
        if (mobileMenuButton) mobileMenuButton.classList.remove('hamburger-active');

        // Close all mobile dropdowns
        const mobileDropdowns = document.querySelectorAll('.mobile-dropdown');
        const dropdownIcons = document.querySelectorAll('.mobile-dropdown-toggle svg');

        mobileDropdowns.forEach(dropdown => {
            dropdown.classList.remove('active');
        });

        dropdownIcons.forEach(icon => {
            icon.classList.remove('rotate-180');
        });
    }
});

// Close desktop dropdowns when clicking outside
document.addEventListener('click', (e) => {
    const dropdowns = document.querySelectorAll('.dropdown');
    dropdowns.forEach(dropdown => {
        if (!dropdown.contains(e.target)) {
            const dropdownMenu = dropdown.querySelector('.dropdown-menu, .mega-dropdown');
            if (dropdownMenu) {
                dropdownMenu.classList.remove('show');
            }
        }
    });
});

// Prevent dropdown from closing when clicking inside
document.querySelectorAll('.dropdown-menu, .mega-dropdown').forEach(menu => {
    menu.addEventListener('click', (e) => {
        e.stopPropagation();
    });
});

/* ===== HERO SLIDER CODE ===== */

class HeroSlider {
    constructor() {
        // DOM elementlerini seç
        this.slides = document.querySelectorAll('.slide');
        this.dots = document.querySelectorAll('.dot');
        this.progressBar = document.querySelector('.progress-bar');

        // Slider durumu
        this.currentSlide = 0;
        this.totalSlides = this.slides.length;
        this.isAnimating = false;
        this.isPaused = false;

        // Zamanlayıcılar
        this.autoPlayInterval = null;
        this.progressInterval = null;
        this.autoPlayDuration = 4000; // 5 saniye

        // Dokunma kontrolleri
        this.touchStartX = 0;
        this.touchStartY = 0;
        this.touchEndX = 0;
        this.touchEndY = 0;
        this.minSwipeDistance = 50;

        // Slider varsa başlat
        if (this.slides.length > 0) {
            this.init();
        }
    }

    init() {
        // İlk durumu ayarla
        this.setupInitialState();

        // Event listener'ları bağla
        this.bindEvents();

        // Otomatik oynatmayı başlat
        this.startAutoPlay();

    }

    setupInitialState() {
        // Tüm slide'ları gizle
        this.slides.forEach((slide, index) => {
            slide.classList.remove('active');
            if (index !== 0) {
                slide.style.transform = 'translateX(100%)';
                slide.style.opacity = '0';
                slide.style.visibility = 'hidden';
            }
        });

        // İlk slide'ı göster
        if (this.slides[0]) {
            this.slides[0].classList.add('active');
            this.slides[0].style.transform = 'translateX(0)';
            this.slides[0].style.opacity = '1';
            this.slides[0].style.visibility = 'visible';
        }

        // İlk dot'u aktif yap
        if (this.dots[0]) {
            this.dots[0].classList.add('active');
        }

        // Progress bar'ı sıfırla
        if (this.progressBar) {
            this.progressBar.style.width = '0%';
        }
    }

    bindEvents() {
        // Dot navigation
        this.dots.forEach((dot, index) => {
            dot.addEventListener('click', (e) => {
                e.preventDefault();
                if (!this.isAnimating && index !== this.currentSlide) {
                    this.goToSlide(index);
                    this.resetAutoPlay();
                }
            });

            // Keyboard accessibility
            dot.addEventListener('keydown', (e) => {
                if (e.key === 'Enter' || e.key === ' ') {
                    e.preventDefault();
                    if (!this.isAnimating && index !== this.currentSlide) {
                        this.goToSlide(index);
                        this.resetAutoPlay();
                    }
                }
            });
        });

        // Klavye kontrolleri
        document.addEventListener('keydown', (e) => {
            if (this.isAnimating) return;

            switch (e.key) {
                case 'ArrowLeft':
                    e.preventDefault();
                    this.previousSlide();
                    this.resetAutoPlay();
                    break;
                case 'ArrowRight':
                    e.preventDefault();
                    this.nextSlide();
                    this.resetAutoPlay();
                    break;
                case ' ': // Space bar
                    e.preventDefault();
                    this.toggleAutoPlay();
                    break;
            }
        });

        // Mouse olayları
        const sliderContainer = document.querySelector('main');
        if (sliderContainer) {
            sliderContainer.addEventListener('mouseenter', () => {
                this.pauseAutoPlay();
            });

            sliderContainer.addEventListener('mouseleave', () => {
                this.resumeAutoPlay();
            });

            // Touch olayları
            sliderContainer.addEventListener('touchstart', this.handleTouchStart.bind(this), { passive: true });
            sliderContainer.addEventListener('touchend', this.handleTouchEnd.bind(this), { passive: true });
        }

        // Sayfa görünürlüğü değişikliklerini dinle
        document.addEventListener('visibilitychange', () => {
            if (document.hidden) {
                this.pauseAutoPlay();
            } else {
                this.resumeAutoPlay();
            }
        });

        // Pencere boyutu değişikliklerini dinle
        let resizeTimeout;
        window.addEventListener('resize', () => {
            clearTimeout(resizeTimeout);
            resizeTimeout = setTimeout(() => {
                this.handleResize();
            }, 250);
        });
    }

    handleTouchStart(e) {
        this.touchStartX = e.changedTouches[0].screenX;
        this.touchStartY = e.changedTouches[0].screenY;
    }

    handleTouchEnd(e) {
        if (this.isAnimating) return;

        this.touchEndX = e.changedTouches[0].screenX;
        this.touchEndY = e.changedTouches[0].screenY;

        const deltaX = this.touchStartX - this.touchEndX;
        const deltaY = this.touchStartY - this.touchEndY;

        // Yatay hareket dikey hareketten fazlaysa
        if (Math.abs(deltaX) > Math.abs(deltaY)) {
            if (Math.abs(deltaX) > this.minSwipeDistance) {
                if (deltaX > 0) {
                    // Sola kaydır - sonraki slide
                    this.nextSlide();
                } else {
                    // Sağa kaydır - önceki slide
                    this.previousSlide();
                }
                this.resetAutoPlay();
            }
        }
    }

    handleResize() {
        // Responsive düzenlemeler
        if (window.innerWidth < 768) {
            this.autoPlayDuration = 6000; // Mobilde daha yavaş
        } else {
            this.autoPlayDuration = 5000;
        }
    }

    goToSlide(targetIndex) {
        if (this.isAnimating || targetIndex === this.currentSlide || targetIndex < 0 || targetIndex >= this.totalSlides) {
            return;
        }

        this.isAnimating = true;
        const currentSlideEl = this.slides[this.currentSlide];
        const targetSlideEl = this.slides[targetIndex];
        const direction = targetIndex > this.currentSlide ? 'next' : 'prev';

        // Progress bar'ı durdur
        this.stopProgress();

        // Dot'ları güncelle
        this.updateDots(targetIndex);

        // Animasyon başlat
        this.animateSlideTransition(currentSlideEl, targetSlideEl, direction, () => {
            this.currentSlide = targetIndex;
            this.isAnimating = false;

            // Progress bar'ı başlat
            if (!this.isPaused) {
                this.startProgress();
            }
        });
    }

    animateSlideTransition(currentSlide, targetSlide, direction, callback) {
        // Yeni slide'ı hazırla
        targetSlide.style.visibility = 'visible';
        targetSlide.style.opacity = '0';

        if (direction === 'next') {
            targetSlide.style.transform = 'translateX(100%)';
        } else {
            targetSlide.style.transform = 'translateX(-100%)';
        }

        // Animasyon için requestAnimationFrame kullan
        requestAnimationFrame(() => {
            // Mevcut slide'ı çıkar
            currentSlide.style.opacity = '0';
            if (direction === 'next') {
                currentSlide.style.transform = 'translateX(-100%)';
            } else {
                currentSlide.style.transform = 'translateX(100%)';
            }

            // Yeni slide'ı getir
            targetSlide.style.opacity = '1';
            targetSlide.style.transform = 'translateX(0)';
            targetSlide.classList.add('active');

            // Animasyon tamamlandığında temizlik yap
            setTimeout(() => {
                currentSlide.classList.remove('active');
                currentSlide.style.visibility = 'hidden';

                if (callback) callback();
            }, 800); // CSS transition süresi ile eşleşmeli
        });
    }

    updateDots(activeIndex) {
        this.dots.forEach((dot, index) => {
            if (index === activeIndex) {
                dot.classList.add('active');
                dot.setAttribute('aria-current', 'true');
            } else {
                dot.classList.remove('active');
                dot.removeAttribute('aria-current');
            }
        });
    }

    nextSlide() {
        const nextIndex = (this.currentSlide + 1) % this.totalSlides;
        this.goToSlide(nextIndex);
    }

    previousSlide() {
        const prevIndex = (this.currentSlide - 1 + this.totalSlides) % this.totalSlides;
        this.goToSlide(prevIndex);
    }

    startAutoPlay() {
        if (this.autoPlayInterval) return;

        this.autoPlayInterval = setInterval(() => {
            if (!this.isAnimating && !this.isPaused) {
                this.nextSlide();
            }
        }, this.autoPlayDuration);

        this.startProgress();
    }

    stopAutoPlay() {
        if (this.autoPlayInterval) {
            clearInterval(this.autoPlayInterval);
            this.autoPlayInterval = null;
        }
        this.stopProgress();
    }

    pauseAutoPlay() {
        this.isPaused = true;
        this.stopProgress();
    }

    resumeAutoPlay() {
        this.isPaused = false;
        if (this.autoPlayInterval && !this.isAnimating) {
            this.startProgress();
        }
    }

    resetAutoPlay() {
        this.stopAutoPlay();
        setTimeout(() => {
            if (!this.isPaused) {
                this.startAutoPlay();
            }
        }, 100);
    }

    toggleAutoPlay() {
        if (this.isPaused) {
            this.resumeAutoPlay();
            if (!this.autoPlayInterval) {
                this.startAutoPlay();
            }
        } else {
            this.pauseAutoPlay();
        }
    }

    startProgress() {
        if (!this.progressBar) return;

        this.stopProgress();
        this.progressBar.style.width = '0%';

        // CSS animasyonu ile progress bar'ı doldur
        requestAnimationFrame(() => {
            this.progressBar.style.transition = `width ${this.autoPlayDuration}ms linear`;
            this.progressBar.style.width = '100%';
        });
    }

    stopProgress() {
        if (!this.progressBar) return;

        // Mevcut genişliği al ve animasyonu durdur
        const currentWidth = this.progressBar.getBoundingClientRect().width;
        const containerWidth = this.progressBar.parentElement.getBoundingClientRect().width;
        const currentPercentage = (currentWidth / containerWidth) * 100;

        this.progressBar.style.transition = 'none';
        this.progressBar.style.width = currentPercentage + '%';
    }

    destroy() {
        // Temizlik işlemleri
        this.stopAutoPlay();

        // Event listener'ları kaldır
        this.dots.forEach(dot => {
            dot.replaceWith(dot.cloneNode(true));
        });
    }
}

// Slider'ı başlat
document.addEventListener('DOMContentLoaded', () => {
    // Slider elementlerinin var olup olmadığını kontrol et
    const slides = document.querySelectorAll('.slide');
    if (slides.length > 0) {
        window.heroSlider = new HeroSlider();
    }
});

// Sayfa yüklendiğinde de kontrol et
window.addEventListener('load', () => {
    if (!window.heroSlider) {
        const slides = document.querySelectorAll('.slide');
        if (slides.length > 0) {
            window.heroSlider = new HeroSlider();
        }
    }
});

// FAQ Functionality
document.addEventListener('DOMContentLoaded', function () {
    const faqQuestions = document.querySelectorAll('.faq-question');

    faqQuestions.forEach(question => {
        question.addEventListener('click', function () {
            const faqNumber = this.getAttribute('data-faq');
            const answer = document.querySelector(`[data-faq-content="${faqNumber}"]`);
            const icon = this.querySelector('.faq-icon');

            // Close all other FAQ items
            faqQuestions.forEach(otherQuestion => {
                if (otherQuestion !== this) {
                    const otherFaqNumber = otherQuestion.getAttribute('data-faq');
                    const otherAnswer = document.querySelector(`[data-faq-content="${otherFaqNumber}"]`);
                    const otherIcon = otherQuestion.querySelector('.faq-icon');

                    otherAnswer.style.maxHeight = '0px';
                    otherIcon.style.transform = 'rotate(0deg)';
                }
            });

            // Toggle current FAQ item
            if (answer.style.maxHeight === '0px' || !answer.style.maxHeight) {
                answer.style.maxHeight = answer.scrollHeight + 'px';
                icon.style.transform = 'rotate(45deg)';
            } else {
                answer.style.maxHeight = '0px';
                icon.style.transform = 'rotate(0deg)';
            }
        });
    });
});

function showPackages(processor) {
    // Tüm paketleri gizle
    document.getElementById('intel-packages').classList.add('hidden');
    document.getElementById('amd-packages').classList.add('hidden');

    // Seçilen paketi göster
    document.getElementById(processor + '-packages').classList.remove('hidden');

    // Buton stillerini güncelle
    document.querySelectorAll('.processor-btn').forEach(btn => {
        btn.classList.remove('active');
        if (processor === 'intel') {
            btn.classList.remove('bg-blue-600', 'bg-orange-600');
            btn.classList.add('bg-verinay-gray-2');
        } else {
            btn.classList.remove('bg-blue-600', 'bg-orange-600');
            btn.classList.add('bg-verinay-gray-2');
        }
    });

    // Aktif butonu vurgula
    const activeBtn = document.getElementById(processor + '-btn');
    activeBtn.classList.add('active');
    if (processor === 'intel') {
        activeBtn.classList.remove('bg-verinay-gray-2');
        activeBtn.classList.add('bg-blue-600');
    } else {
        activeBtn.classList.remove('bg-verinay-gray-2');
        activeBtn.classList.add('bg-orange-600');
    }
}

// Smooth scroll fonksiyonu
function smoothScrollTo(targetId) {
    const target = document.getElementById(targetId);
    if (target) {
        target.scrollIntoView({
            behavior: 'smooth',
            block: 'start'
        });
    }
}

// DOM yüklendiğinde çalışacak kod
document.addEventListener('DOMContentLoaded', function () {

    // Tüm butonları kontrol et ve uygun event listener'ları ekle
    const buttons = document.querySelectorAll('button');

    buttons.forEach(button => {
        const buttonText = button.textContent.trim();

        // Minecraft sayfası için
        if (buttonText.includes('Minecraft Paketleri')) {
            button.addEventListener('click', function () {
                smoothScrollTo('packages-section');
            });
        }

        // cPanel/Hosting sayfası için
        if (buttonText.includes('Hosting Paketleri')) {
            button.addEventListener('click', function () {
                smoothScrollTo('hosting-packages-section');
            });
        }

        // Her iki sayfa için Özellikler butonu
        if (buttonText.includes('Özellikler')) {
            button.addEventListener('click', function () {
                smoothScrollTo('features-section');
            });
        }

        // Web Hosting Başlat butonu için
        if (buttonText.includes('Web Hosting Başlat')) {
            button.addEventListener('click', function () {
                smoothScrollTo('hosting-packages-section');
            });
        }
    });

    // Alan Adı Ara butonu
    const btnSearchDomain = document.getElementById('btn-search-domain');
    if (btnSearchDomain) {
        btnSearchDomain.addEventListener('click', function () {
            smoothScrollTo('domain-search-section');
        });
    }

    // Fiyatları İncele butonu  
    const btnViewPrices = document.getElementById('btn-view-prices');
    if (btnViewPrices) {
        btnViewPrices.addEventListener('click', function () {
            smoothScrollTo('domain-price-section');
        });
    }

    // Minecraft Paketleri butonu (fa-cube icon)
    const minecraftBtn = document.querySelector('button i.fa-cube');
    if (minecraftBtn) {
        minecraftBtn.parentElement.addEventListener('click', function () {
            smoothScrollTo('packages-section');
        });
    }

    // Hosting Paketleri butonu (fa-box icon)
    const hostingBtn = document.querySelector('button i.fa-box');
    if (hostingBtn) {
        hostingBtn.parentElement.addEventListener('click', function () {
            smoothScrollTo('hosting-packages-section');
        });
    }

    // Özellikler butonu (fa-list icon)
    const featuresBtn = document.querySelector('button i.fa-list');
    if (featuresBtn) {
        featuresBtn.parentElement.addEventListener('click', function () {
            smoothScrollTo('features-section');
        });
    }
});

// Opsiyonel: Daha gelişmiş smooth scroll fonksiyonu
function advancedSmoothScroll(targetId, offset = 100) {
    const target = document.getElementById(targetId);
    if (target) {
        const targetPosition = target.offsetTop - offset;
        window.scrollTo({
            top: targetPosition,
            behavior: 'smooth'
        });
    }
}