// ============================
// SAYFA SCRIPT - DETAY SAYFALARI İÇİN ÖZEL SCRİPTLER
// ============================

(function () {
    'use strict';

    // ============================
    // 1. SAYFA YÜKLENDİĞİNDE
    // ============================

    document.addEventListener('DOMContentLoaded', function () {
        console.log('📄 Detay sayfası yüklendi.');

        // Aktif dili güncelle
        const aktifDil = localStorage.getItem('stncodeDil') || 'TR';
        if (window.STNcode && window.STNcode.dilDegistir) {
            window.STNcode.dilDegistir(aktifDil);
        }

        // Galeri görsellerine tıklama olayı
        galeriTikla();

        // Demo formu gönderme
        demoFormGonder();

        // Yumuşak kaydırma
        smoothScroll();

        // GALERİ ALT ETİKETLERİNİ GÜNCELLE (YENİ)
        galleryAltGuncelle(aktifDil);
    });

    // ============================
    // 3. GALERİ ALT ETİKETLERİNİ GÜNCELLE (YENİ)
    // ============================

    function galleryAltGuncelle(dilKodu) {
        const metinler = window.STNcode?.DIL?.[dilKodu];
        if (!metinler) return;

        // Tüm data-alt-key özelliğine sahip resimleri güncelle
        document.querySelectorAll('[data-alt-key]').forEach(img => {
            const key = img.getAttribute('data-alt-key');
            if (metinler[key]) {
                img.alt = metinler[key];
            }
        });

        // Tüm form placeholder'larını güncelle (data-placeholder-key ile)
        document.querySelectorAll('[data-placeholder-key]').forEach(input => {
            const key = input.getAttribute('data-placeholder-key');
            if (metinler[key]) {
                input.placeholder = metinler[key];
            }
        });

        // Tüm select option'ları güncelle (data-option-key ile)
        document.querySelectorAll('[data-option-key]').forEach(option => {
            const key = option.getAttribute('data-option-key');
            if (metinler[key]) {
                option.textContent = metinler[key];
            }
        });
    }

    // ============================
    // 4. DİL DEĞİŞTİĞİNDE ALT ETİKETLERİ GÜNCELLE (YENİ)
    // ============================

    document.addEventListener('dilDegisti', function (e) {
        const dilKodu = e.detail.dil;
        galleryAltGuncelle(dilKodu);
        console.log('🔄 Galeri alt etiketleri güncellendi:', dilKodu);
    });

    // ============================
    // 5. GALERİ TIKLAMA (LIGHTBOX)
    // ============================

    function galeriTikla() {
        const galleryItems = document.querySelectorAll('.gallery-item');

        galleryItems.forEach(item => {
            item.addEventListener('click', function () {
                const img = this.querySelector('img');
                if (img) {
                    const imageUrl = img.getAttribute('src');
                    const altText = img.getAttribute('alt') || 'Görsel';

                    const lightbox = document.createElement('div');
                    lightbox.className = 'lightbox-overlay';
                    lightbox.innerHTML = `
                        <div class="lightbox-content">
                            <button class="lightbox-close">&times;</button>
                            <img src="${imageUrl}" alt="${altText}" />
                            <p class="lightbox-caption">${altText}</p>
                        </div>
                    `;

                    document.body.appendChild(lightbox);
                    document.body.style.overflow = 'hidden';

                    const closeBtn = lightbox.querySelector('.lightbox-close');
                    closeBtn.addEventListener('click', function () {
                        lightbox.remove();
                        document.body.style.overflow = '';
                    });

                    lightbox.addEventListener('click', function (e) {
                        if (e.target === this) {
                            lightbox.remove();
                            document.body.style.overflow = '';
                        }
                    });

                    document.addEventListener('keydown', function escHandler(e) {
                        if (e.key === 'Escape') {
                            if (document.querySelector('.lightbox-overlay')) {
                                document.querySelector('.lightbox-overlay').remove();
                                document.body.style.overflow = '';
                                document.removeEventListener('keydown', escHandler);
                            }
                        }
                    });
                }
            });
        });
    }

    // ============================
    // 6. DEMO FORM GÖNDERME (AJAX)
    // ============================

    function demoFormGonder() {
        const forms = document.querySelectorAll('.demo-form, .contact-form');

        forms.forEach(form => {
            form.addEventListener('submit', function (e) {
                e.preventDefault();

                const submitBtn = this.querySelector('.btn[type="submit"]');
                const originalText = submitBtn ? submitBtn.textContent : '📩 Gönder';
                const successMessage = this.querySelector('.success-message');

                if (submitBtn) {
                    submitBtn.textContent = '⏳ Gönderiliyor...';
                    submitBtn.disabled = true;
                    submitBtn.classList.add('loading');
                }

                const formData = new FormData(this);

                fetch(this.action, {
                    method: 'POST',
                    body: formData
                })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            if (successMessage) {
                                successMessage.textContent = '✅ ' + (data.message || 'Talebiniz başarıyla gönderildi! En kısa sürede dönüş yapılacaktır.');
                                successMessage.classList.add('show');
                            } else {
                                alert('✅ Talebiniz başarıyla gönderildi! En kısa sürede dönüş yapılacaktır.');
                            }
                            this.reset();
                        } else {
                            alert('❌ ' + (data.message || 'Bir hata oluştu. Lütfen tekrar deneyin.'));
                        }
                    })
                    .catch(error => {
                        console.error('Form gönderme hatası:', error);
                        alert('❌ Bir hata oluştu. Lütfen tekrar deneyin.');
                    })
                    .finally(() => {
                        if (submitBtn) {
                            submitBtn.textContent = originalText;
                            submitBtn.disabled = false;
                            submitBtn.classList.remove('loading');
                        }
                    });
            });
        });
    }

    // ============================
    // 7. YUMUŞAK KAYDIRMA
    // ============================

    function smoothScroll() {
        document.querySelectorAll('a[href^="#"]').forEach(anchor => {
            anchor.addEventListener('click', function (e) {
                const href = this.getAttribute('href');
                if (href === '#') return;

                const target = document.querySelector(href);
                if (target) {
                    e.preventDefault();
                    const navbarHeight = document.getElementById('navbar')?.offsetHeight || 80;
                    const targetPosition = target.getBoundingClientRect().top + window.pageYOffset - navbarHeight;
                    window.scrollTo({
                        top: targetPosition,
                        behavior: 'smooth'
                    });
                }
            });
        });
    }

    // ============================
    // 8. LIGHTBOX CSS (Dinamik Ekle)
    // ============================

    function addLightboxStyles() {
        const style = document.createElement('style');
        style.textContent = `
            .lightbox-overlay {
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(10, 25, 47, 0.95);
                z-index: 9999;
                display: flex;
                align-items: center;
                justify-content: center;
                padding: 40px;
                animation: lightboxFade 0.3s ease;
            }

            @keyframes lightboxFade {
                from { opacity: 0; }
                to { opacity: 1; }
            }

            .lightbox-content {
                position: relative;
                max-width: 90%;
                max-height: 90%;
                background: var(--primary-light, #172A45);
                border-radius: 12px;
                padding: 20px;
                box-shadow: 0 25px 60px rgba(0, 0, 0, 0.8);
                border: 1px solid rgba(255, 255, 255, 0.05);
            }

            .lightbox-content img {
                max-width: 100%;
                max-height: 70vh;
                border-radius: 8px;
                display: block;
                margin: 0 auto;
            }

            .lightbox-caption {
                color: #8892B0;
                text-align: center;
                margin-top: 12px;
                font-size: 0.95rem;
            }

            .lightbox-close {
                position: absolute;
                top: -40px;
                right: -40px;
                background: transparent;
                border: none;
                color: white;
                font-size: 2.5rem;
                cursor: pointer;
                transition: 0.3s ease;
                padding: 0 8px;
                line-height: 1;
            }

            .lightbox-close:hover {
                color: #00D4FF;
                transform: rotate(90deg);
            }

            @media (max-width: 768px) {
                .lightbox-overlay {
                    padding: 20px;
                }
                .lightbox-content {
                    padding: 12px;
                }
                .lightbox-close {
                    top: -35px;
                    right: 5px;
                    font-size: 2rem;
                }
                .lightbox-content img {
                    max-height: 60vh;
                }
            }

            @media (max-width: 480px) {
                .lightbox-content img {
                    max-height: 50vh;
                }
                .lightbox-close {
                    font-size: 1.6rem;
                    top: -30px;
                }
                .lightbox-caption {
                    font-size: 0.8rem;
                    margin-top: 8px;
                }
            }
        `;
        document.head.appendChild(style);
    }

    addLightboxStyles();

    // ============================
    // 9. URL'DEN PROGRAM PARAMETRESİ OKU
    // ============================

    function getUrlParameter(name) {
        const urlParams = new URLSearchParams(window.location.search);
        return urlParams.get(name);
    }

    const programParam = getUrlParameter('program');
    if (programParam) {
        const select = document.querySelector('.demo-form select[name="program"]');
        if (select) {
            const option = select.querySelector(`option[value="${programParam}"]`);
            if (option) {
                select.value = programParam;
            }
        }
    }

    console.log('✅ STNcode Sayfa Script yüklendi.');

})();

// ============================
// ANA SAYFA İÇİN PLACEHOLDER VE OPTION GÜNCELLEME
// ============================

function anaSayfaFormGuncelle(dilKodu) {
    var metinler = window.STNcode?.DIL?.[dilKodu];
    if (!metinler) return;

    // Placeholder'ları güncelle
    document.querySelectorAll('[data-placeholder-key]').forEach(function (input) {
        var key = input.getAttribute('data-placeholder-key');
        if (metinler[key]) {
            input.placeholder = metinler[key];
        }
    });

    // Select option'ları güncelle
    document.querySelectorAll('[data-option-key]').forEach(function (option) {
        var key = option.getAttribute('data-option-key');
        if (metinler[key]) {
            option.textContent = metinler[key];
        }
    });

    // Alt etiketlerini güncelle
    document.querySelectorAll('[data-alt-key]').forEach(function (img) {
        var key = img.getAttribute('data-alt-key');
        if (metinler[key]) {
            img.alt = metinler[key];
        }
    });
}

// Dil değiştiğinde çalıştır
document.addEventListener('dilDegisti', function (e) {
    anaSayfaFormGuncelle(e.detail.dil);
});

// Sayfa yüklendiğinde çalıştır
document.addEventListener('DOMContentLoaded', function () {
    var aktifDil = localStorage.getItem('stncodeDil') || 'TR';
    anaSayfaFormGuncelle(aktifDil);
});