/* =============================================
   KURSI JOK - Main JavaScript
   ============================================= */

// ============ LANGUAGE TOGGLE ============
let currentLang = localStorage.getItem('lang') || 'id';

function toggleLanguage() {
    currentLang = currentLang === 'id' ? 'en' : 'id';
    localStorage.setItem('lang', currentLang);
    applyLanguage();
}

function applyLanguage() {
    // Update all lang labels (desktop + mobile)
    document.querySelectorAll('#langLabel, #langLabelMobile').forEach(el => {
        el.textContent = currentLang === 'id' ? 'EN' : 'ID';
    });
    document.querySelectorAll('[data-en][data-id]').forEach(el => {
        el.textContent = currentLang === 'id' ? el.dataset.id : el.dataset.en;
    });
    document.querySelectorAll('[data-en-html][data-id-html]').forEach(el => {
        el.innerHTML = currentLang === 'id' ? el.dataset.idHtml : el.dataset.enHtml;
    });
}

document.addEventListener('DOMContentLoaded', () => {
    applyLanguage();
});

// ============ MOBILE OFFCANVAS MENU ============
function openMobileMenu() {
    const menu     = document.getElementById('mobileMenu');
    const backdrop = document.getElementById('menuBackdrop');
    backdrop.style.display = 'block';
    document.body.style.overflow = 'hidden';
    // trigger reflow for transition
    backdrop.offsetHeight;
    backdrop.classList.add('show');
    menu.classList.add('show');
}

function closeMobileMenu() {
    const menu     = document.getElementById('mobileMenu');
    const backdrop = document.getElementById('menuBackdrop');
    menu.classList.remove('show');
    backdrop.classList.remove('show');
    document.body.style.overflow = '';
    setTimeout(() => { backdrop.style.display = 'none'; }, 300);
}

function toggleMobileGroup(btn) {
    const submenu = btn.nextElementSibling;
    const isOpen  = submenu.classList.contains('open');
    // close all open groups
    document.querySelectorAll('.mobile-submenu.open').forEach(s => s.classList.remove('open'));
    document.querySelectorAll('.mobile-menu-toggle.open').forEach(b => b.classList.remove('open'));
    if (!isOpen) {
        submenu.classList.add('open');
        btn.classList.add('open');
    }
}

// Close on ESC key
document.addEventListener('keydown', e => {
    if (e.key === 'Escape') closeMobileMenu();
});


// ============ POPUP ============
function showPopup() {
    document.getElementById('popupOverlay').classList.add('show');
    document.getElementById('popupBox').classList.add('show');
}

function closePopup() {
    document.getElementById('popupOverlay').classList.remove('show');
    document.getElementById('popupBox').classList.remove('show');
}

// Auto-show popup after 3s on first visit
document.addEventListener('DOMContentLoaded', () => {
    const shown = sessionStorage.getItem('popupShown');
    if (!shown) {
        setTimeout(() => {
            const box = document.getElementById('popupBox');
            if (box) { showPopup(); sessionStorage.setItem('popupShown', '1'); }
        }, 3000);
    }
});

// ============ GALLERY FILTER ============
function filterGallery(cat) {
    document.querySelectorAll('.filter-tab').forEach(t => {
        t.classList.toggle('active', t.dataset.filter === cat);
    });
    document.querySelectorAll('[data-cat]').forEach(item => {
        if (cat === 'all' || item.dataset.cat === cat) {
            item.style.display = '';
        } else {
            item.style.display = 'none';
        }
    });
}

// ============ GALLERY LIGHTBOX ============
function openLightbox(src, title) {
    const modal = document.getElementById('lightboxModal');
    if (!modal) return;
    document.getElementById('lightboxImg').src = src;
    document.getElementById('lightboxTitle').textContent = title || '';
    new bootstrap.Modal(modal).show();
}

// ============ VIDEO MODAL ============
function openVideo(embedUrl) {
    const modal = document.getElementById('videoModal');
    if (!modal) return;
    document.getElementById('videoFrame').src = embedUrl + '?autoplay=1';
    const m = new bootstrap.Modal(modal);
    m.show();
    modal.addEventListener('hidden.bs.modal', () => {
        document.getElementById('videoFrame').src = '';
    }, { once: true });
}

function stopVideo() {
    const frame = document.getElementById('videoFrame');
    if (frame) frame.src = '';
}

// ============ SCROLL ANIMATIONS ============
document.addEventListener('DOMContentLoaded', () => {
    const observer = new IntersectionObserver((entries) => {
        entries.forEach(e => {
            if (e.isIntersecting) {
                e.target.classList.add('visible');
                observer.unobserve(e.target);
            }
        });
    }, { threshold: 0.1, rootMargin: '0px 0px -40px 0px' });
    document.querySelectorAll('.fade-up').forEach(el => observer.observe(el));
});

// ============ COUNTER ANIMATION ============
function animateCounter(el) {
    const target = parseInt(el.dataset.target, 10);
    const duration = 1500;
    const step = target / (duration / 16);
    let current = 0;
    const timer = setInterval(() => {
        current += step;
        if (current >= target) { current = target; clearInterval(timer); }
        el.textContent = Math.floor(current).toLocaleString();
    }, 16);
}

document.addEventListener('DOMContentLoaded', () => {
    const obs = new IntersectionObserver((entries) => {
        entries.forEach(e => {
            if (e.isIntersecting) {
                e.target.querySelectorAll('[data-target]').forEach(animateCounter);
                obs.unobserve(e.target);
            }
        });
    }, { threshold: 0.3 });
    document.querySelectorAll('.stats-section').forEach(el => obs.observe(el));
});

// ============ NAVBAR SCROLL EFFECT ============
window.addEventListener('scroll', () => {
    const nav = document.getElementById('mainNav');
    if (!nav) return;
    if (window.scrollY > 80) {
        nav.classList.add('scrolled');
        nav.style.boxShadow = '0 2px 20px rgba(0,0,0,.12)';
    } else {
        nav.classList.remove('scrolled');
        nav.style.boxShadow = '';
    }
});

// ============ CONTACT FORM ============
const contactForm = document.getElementById('contactForm');
if (contactForm) {
    contactForm.addEventListener('submit', function(e) {
        const btn = this.querySelector('[type=submit]');
        btn.disabled = true;
        btn.innerHTML = '<span class="spinner-border spinner-border-sm me-2"></span>Mengirim...';
    });
}
