/**
 * nihongo.net - Main JavaScript
 * Handles interactive functionality for the website
 */

// === Global initializers (moved from inline scripts) ===
(function(){
	document.addEventListener('DOMContentLoaded', function(){
		// 1) Header Language Switcher
		(function initLanguageSwitcher(){
			var langToggle = document.getElementById('langToggle');
			var langDropdown = document.getElementById('langDropdown');
			var langCurrent = document.querySelector('.lang-current');
			var langOptions = document.querySelectorAll('.lang-option');
			if (!langToggle || !langDropdown) return;
			langToggle.addEventListener('click', function(e){ e.preventDefault(); langDropdown.classList.toggle('active'); langToggle.classList.toggle('active'); });
			document.addEventListener('click', function(e){ if (!langToggle.contains(e.target) && !langDropdown.contains(e.target)) { langDropdown.classList.remove('active'); langToggle.classList.remove('active'); } });
			langOptions.forEach(function(option){ option.addEventListener('click', function(){ var selectedLang = this.getAttribute('data-lang'); if (langCurrent) { langCurrent.textContent = selectedLang === 'jp' ? 'JP' : 'EN'; } langOptions.forEach(function(opt){ opt.classList.remove('active'); }); this.classList.add('active'); langDropdown.classList.remove('active'); langToggle.classList.remove('active'); }); });
		})();

		// 2) Home typewriter (guarded; only if hero present and no char spans)
		(function initHomeTypewriter(){
			var hero = document.querySelector('section.hero .hero-content');
			var hasCharSpans = hero && hero.querySelector('.char');
			if (!hero || hasCharSpans) return;
			var titleEl = hero.querySelector('.hero-title');
			var subtitleEl = hero.querySelector('.hero-subtitle');
			if (!titleEl) return;
			var prefersReducedMotion = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
			if (prefersReducedMotion || (window.innerWidth && window.innerWidth <= 767)) return;
			var titleFull = titleEl.textContent || '';
			var subtitleFull = subtitleEl ? (subtitleEl.textContent || '') : '';
			function reserveWidth(el, text){ if (!el || !text) return; var probe = document.createElement('span'); var cs = window.getComputedStyle(el); probe.style.position='absolute'; probe.style.visibility='hidden'; probe.style.whiteSpace='pre'; probe.style.fontFamily=cs.fontFamily; probe.style.fontSize=cs.fontSize; probe.style.fontWeight=cs.fontWeight; probe.style.letterSpacing=cs.letterSpacing; probe.style.lineHeight=cs.lineHeight; probe.textContent=text; document.body.appendChild(probe); var w = probe.offsetWidth; document.body.removeChild(probe); el.style.display='inline-block'; el.style.whiteSpace='pre-wrap'; el.style.width=w+'px'; }
			reserveWidth(titleEl, titleFull); if (subtitleEl) reserveWidth(subtitleEl, subtitleFull);
			titleEl.textContent=''; if (subtitleEl) subtitleEl.textContent='';
			var titleIndex=0, subtitleIndex=0, speedMs=25;
			function typeTitle(){ if (titleIndex < titleFull.length){ titleEl.textContent += titleFull.charAt(titleIndex++); setTimeout(typeTitle, speedMs); } else if (subtitleEl && subtitleFull.length){ setTimeout(typeSubtitle, speedMs); } }
			function typeSubtitle(){ if (subtitleIndex < subtitleFull.length){ subtitleEl.textContent += subtitleFull.charAt(subtitleIndex++); setTimeout(typeSubtitle, speedMs); } }
			setTimeout(typeTitle, 150);
		})();

		// 3) News hero rotator
		(function initNewsHero(){
			var heroEl = document.getElementById('news-hero');
			var imgEl = document.getElementById('news-hero-image');
			var captionEl = document.getElementById('news-hero-caption');
			if (!heroEl || !imgEl || !captionEl) return;
			var slides = (function(){
				var data = [];
				var titles = [];
				try { titles = heroEl.getAttribute('data-titles') ? JSON.parse(heroEl.getAttribute('data-titles')) : []; } catch(e) { titles = []; }
				var sources = ['assets/img/n1.jpg','assets/img/n2.jpg','assets/img/n3.jpg','assets/img/n4.jpg','assets/img/n5.jpg','assets/img/n6.jpg','assets/img/n7.jpg','assets/img/n8.jpg','assets/img/n9.jpg','assets/img/n10.jpg','assets/img/n11.jpg','assets/img/n12.jpg'];
				sources.forEach(function(src, i){ data.push({src: src, title: titles[i] || (captionEl.textContent || '')}); });
				return data;
			})();
			var idx = 0;
			function resizeHero(){ var header = document.querySelector('.header'); var h = header ? header.offsetHeight : 0; heroEl.style.minHeight = 'calc(100vh - '+h+'px)'; heroEl.style.height = 'calc(100svh - '+h+'px)'; }
			resizeHero(); window.addEventListener('resize', resizeHero);
			setInterval(function(){ idx = (idx+1)%slides.length; var next=slides[idx]; imgEl.src = next.src; captionEl.textContent = next.title; }, 5000);
		})();

		// 6) Voices hero carousel
		(function initVoicesCarousel(){
			var carousel = document.querySelector('.hero-carousel');
			if (!carousel) return;
			var slides = document.querySelectorAll('.carousel-slide');
			var dots = document.querySelectorAll('.dot');
			var prevBtn = document.querySelector('.carousel-prev');
			var nextBtn = document.querySelector('.carousel-next');
			var currentSlide = 0; var intervalId;
			function showSlide(index){
				slides.forEach(function(s){ s.classList.remove('active'); });
				dots.forEach(function(d){ d.classList.remove('active'); });
				slides[index].classList.add('active');
				dots[index].classList.add('active');
				currentSlide = index;
			}
			function next(){ showSlide((currentSlide + 1) % slides.length); }
			function prev(){ showSlide((currentSlide - 1 + slides.length) % slides.length); }
			function start(){ intervalId = setInterval(next, 3000); }
			function stop(){ if (intervalId) { clearInterval(intervalId); intervalId = null; } }
			dots.forEach(function(dot, i){ dot.addEventListener('click', function(){ showSlide(i); stop(); start(); }); });
			if (prevBtn) prevBtn.addEventListener('click', function(){ prev(); stop(); start(); });
			if (nextBtn) nextBtn.addEventListener('click', function(){ next(); stop(); start(); });
			carousel.addEventListener('mouseenter', stop);
			carousel.addEventListener('mouseleave', start);
			start();
		})();

		// 4) Courses slideshow
		(function initCoursesSlideshow(){
			var slides = document.querySelectorAll('.slide');
			if (!slides || !slides.length) return;
			var current = 0;
			setInterval(function(){
				slides[current].classList.remove('active');
				slides[current].classList.add('prev');
				current = (current + 1) % slides.length;
				slides[current].classList.remove('prev');
				slides[current].classList.add('active');
			}, 3000);
		})();

		// 5) Voices page interactions
		(function initVoicesInteractions(){
			var testimonialsContainer = document.getElementById('testimonials-container');
			var loadMoreBtn = document.getElementById('load-more-btn');
			var loadMoreContainer = document.getElementById('load-more-container');
			if (testimonialsContainer && loadMoreBtn && loadMoreContainer){
				var dataAttr = testimonialsContainer.getAttribute('data-testimonials');
				var testimonials = [];
				try { testimonials = dataAttr ? JSON.parse(dataAttr) : []; } catch(e) { testimonials = []; }
				var currentIndex = 0; var cardsPerLoad = 3; var isLoading = false;
				function createCard(t){ return '<div class="testimonial-card"><div class="testimonial-content">'+(t.image?('<div class="testimonial-image"><img src="assets/img/'+t.image+'" alt="'+t.name+'" /></div>'):'')+'<div class="testimonial-header"><h3 class="testimonial-title">'+t.title+'</h3><div class="testimonial-rating">'+('★'.repeat(t.rating||0))+'</div></div><p class="testimonial-comment">'+t.comment+'</p><div class="testimonial-author"><div class="testimonial-info"><h4>'+t.name+'</h4><p>'+t.country+' / '+t.course+'</p>'+(t.date?('<p class="testimonial-date">'+t.date+'</p>'):'')+'</div></div></div></div>'; }
				function loadMore(){ var end = Math.min(currentIndex + cardsPerLoad, testimonials.length); testimonials.slice(currentIndex, end).forEach(function(t){ testimonialsContainer.insertAdjacentHTML('beforeend', createCard(t)); }); currentIndex = end; if (currentIndex >= testimonials.length) { loadMoreContainer.style.display = 'none'; } }
				loadMore(); loadMoreBtn.addEventListener('click', loadMore);
				window.addEventListener('scroll', function(){ if (isLoading || currentIndex >= testimonials.length) return; var st = window.pageYOffset || document.documentElement.scrollTop; var wh = window.innerHeight; var dh = document.documentElement.scrollHeight; if (st + wh >= dh - 100) { isLoading = true; setTimeout(function(){ loadMore(); isLoading = false; }, 300); } });
			}
			var video = document.getElementById('interview-video'); var playBtn = document.getElementById('play-button'); var overlay = document.querySelector('.video-overlay');
			if (video && playBtn && overlay){ playBtn.addEventListener('click', function(){ video.play(); overlay.classList.add('hidden'); }); video.addEventListener('play', function(){ overlay.classList.add('hidden'); }); video.addEventListener('pause', function(){ overlay.classList.remove('hidden'); }); video.addEventListener('ended', function(){ overlay.classList.remove('hidden'); }); }
			var qaItems = document.querySelectorAll('.qa-item');
			if (qaItems && qaItems.length){ qaItems.forEach(function(item){ var q = item.querySelector('.question'); var a = item.querySelector('.answer-content'); if (!q || !a) return; q.addEventListener('click', function(){ var isActive = item.classList.contains('active'); qaItems.forEach(function(other){ if (other !== item){ other.classList.remove('active'); var oa = other.querySelector('.answer-content'); if (oa) oa.style.display='none'; } }); if (isActive){ item.classList.remove('active'); a.style.display='none'; } else { item.classList.add('active'); a.style.display='block'; } }); }); }
		})();
	});
})();

document.addEventListener('DOMContentLoaded', function() {
    
    // Mobile Navigation Toggle
    const mobileMenuToggle = document.querySelector('.mobile-menu-toggle');
    const mobileNav = document.querySelector('.mobile-nav');
    
    if (mobileMenuToggle && mobileNav) {
        mobileMenuToggle.addEventListener('click', function() {
            mobileNav.classList.toggle('active');
            
            // Animate hamburger menu
            const spans = this.querySelectorAll('span');
            spans.forEach((span, index) => {
                if (mobileNav.classList.contains('active')) {
                    if (index === 0) span.style.transform = 'rotate(45deg) translate(5px, 5px)';
                    if (index === 1) span.style.opacity = '0';
                    if (index === 2) span.style.transform = 'rotate(-45deg) translate(7px, -6px)';
                } else {
                    span.style.transform = 'none';
                    span.style.opacity = '1';
                }
            });
        });
        
        // Close mobile menu when clicking outside
        document.addEventListener('click', function(e) {
            if (!mobileMenuToggle.contains(e.target) && !mobileNav.contains(e.target)) {
                mobileNav.classList.remove('active');
                const spans = mobileMenuToggle.querySelectorAll('span');
                spans.forEach(span => {
                    span.style.transform = 'none';
                    span.style.opacity = '1';
                });
            }
        });
    }
    
    // Language Switcher (dropdowns)
    const langDropdownToggle = document.getElementById('langDropdownToggle');
    const langDropdownMenu = document.getElementById('langDropdownMenu');
    const mobileLangDropdownToggle = document.getElementById('mobileLangDropdownToggle');
    const mobileLangDropdownMenu = document.getElementById('mobileLangDropdownMenu');

    function toggleMenu(btn, menu) {
        if (!btn || !menu) return;
        const isOpen = menu.style.display === 'block';
        menu.style.display = isOpen ? 'none' : 'block';
        btn.setAttribute('aria-expanded', String(!isOpen));
    }

    if (langDropdownToggle && langDropdownMenu) {
        langDropdownToggle.addEventListener('click', function(e) {
            e.stopPropagation();
            toggleMenu(langDropdownToggle, langDropdownMenu);
        });
    }

    if (mobileLangDropdownToggle && mobileLangDropdownMenu) {
        mobileLangDropdownToggle.addEventListener('click', function(e) {
            e.stopPropagation();
            toggleMenu(mobileLangDropdownToggle, mobileLangDropdownMenu);
        });
    }

    // Handle language selection
    document.querySelectorAll('.lang-option').forEach(option => {
        option.addEventListener('click', function() {
            const lang = this.getAttribute('data-lang');
            // Update toggle labels
            if (langDropdownToggle) langDropdownToggle.textContent = `${lang.toUpperCase()} ▼`;
            if (mobileLangDropdownToggle) mobileLangDropdownToggle.textContent = `${lang.toUpperCase()} ▼`;
            // Close menus
            if (langDropdownMenu) langDropdownMenu.style.display = 'none';
            if (mobileLangDropdownMenu) mobileLangDropdownMenu.style.display = 'none';
            
            // TODO: Insert real i18n switching here
            showNotification(`Language switched to ${lang.toUpperCase()}`);
        });
    });

    // Close dropdowns when clicking outside
    document.addEventListener('click', function() {
        if (langDropdownMenu) {
            langDropdownMenu.style.display = 'none';
            if (langDropdownToggle) langDropdownToggle.setAttribute('aria-expanded', 'false');
        }
        if (mobileLangDropdownMenu) {
            mobileLangDropdownMenu.style.display = 'none';
            if (mobileLangDropdownToggle) mobileLangDropdownToggle.setAttribute('aria-expanded', 'false');
        }
    });
    
    // Smooth Scrolling for Anchor Links
    const anchorLinks = document.querySelectorAll('a[href^="#"]');
    
    anchorLinks.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            
            const targetId = this.getAttribute('href');
            const targetElement = document.querySelector(targetId);
            
            if (targetElement) {
                const headerHeight = document.querySelector('.header').offsetHeight;
                const targetPosition = targetElement.offsetTop - headerHeight;
                
                window.scrollTo({
                    top: targetPosition,
                    behavior: 'smooth'
                });
            }
        });
    });
    
    // Header Scroll Effect
    const header = document.querySelector('.header');
    let lastScrollTop = 0;
    
    window.addEventListener('scroll', function() {
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
        
        if (scrollTop > 100) {
            header.style.background = 'rgba(255, 255, 255, 0.98)';
            header.style.boxShadow = '0 2px 20px rgba(0, 0, 0, 0.1)';
        } else {
            header.style.background = 'rgba(255, 255, 255, 0.95)';
            header.style.boxShadow = 'none';
        }
        
        lastScrollTop = scrollTop;
    });
    
    // Form Validation and Submission
    const contactForm = document.querySelector('.contact-form form');
    
    if (contactForm) {
        contactForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            // Basic form validation
            const formData = new FormData(this);
            const requiredFields = ['name', 'email', 'message'];
            let isValid = true;
            
            requiredFields.forEach(field => {
                const input = this.querySelector(`[name="${field}"]`);
                if (!input.value.trim()) {
                    isValid = false;
                    showFieldError(input, 'This field is required');
                } else {
                    clearFieldError(input);
                }
            });
            
            // Email validation
            const emailInput = this.querySelector('[name="email"]');
            if (emailInput.value.trim() && !isValidEmail(emailInput.value)) {
                isValid = false;
                showFieldError(emailInput, 'Please enter a valid email address');
            }
            
            if (isValid) {
                // Show loading state
                const submitBtn = this.querySelector('.form-submit');
                const originalText = submitBtn.textContent;
                submitBtn.textContent = 'Sending...';
                submitBtn.disabled = true;
                
                // Simulate form submission
                setTimeout(() => {
                    showNotification('Thank you! Your message has been sent successfully.', 'success');
                    this.reset();
                    submitBtn.textContent = originalText;
                    submitBtn.disabled = false;
                }, 2000);
            }
        });
    }
    
    // Intersection Observer for Animations and data-animate utilities
    const observerOptions = { threshold: 0.1, rootMargin: '0px 0px -50px 0px' };
    const observer = new IntersectionObserver((entries) => {
        entries.forEach((entry) => {
            if (entry.isIntersecting) {
                entry.target.classList.add('fade-in-up');
                entry.target.classList.add('is-visible');
            }
        });
    }, observerOptions);

    const animateElements = document.querySelectorAll('.feature-card, .course-card, .news-card, .testimonial-card, .step-card, [data-animate]');
    animateElements.forEach((el) => observer.observe(el));
    
    // Course Filter (if implemented)
    const courseFilters = document.querySelectorAll('.course-filter');
    
    courseFilters.forEach(filter => {
        filter.addEventListener('click', function(e) {
            e.preventDefault();
            
            const filterValue = this.getAttribute('data-filter');
            
            // Remove active class from all filters
            courseFilters.forEach(f => f.classList.remove('active'));
            
            // Add active class to clicked filter
            this.classList.add('active');
            
            // Filter courses (if implemented)
            filterCourses(filterValue);
        });
    });
    
    // Testimonial Slider (if multiple testimonials)
    let currentTestimonial = 0;
    const testimonials = document.querySelectorAll('.testimonial-card');
    const testimonialContainer = document.querySelector('.testimonials-grid');
    
    if (testimonials.length > 3 && testimonialContainer) {
        // Create navigation dots
        const dotsContainer = document.createElement('div');
        dotsContainer.className = 'testimonial-dots';
        dotsContainer.style.cssText = 'display: flex; justify-content: center; gap: 10px; margin-top: 2rem;';
        
        for (let i = 0; i < Math.ceil(testimonials.length / 3); i++) {
            const dot = document.createElement('button');
            dot.className = 'testimonial-dot';
            dot.style.cssText = 'width: 12px; height: 12px; border-radius: 50%; border: none; background: #ddd; cursor: pointer;';
            dot.addEventListener('click', () => showTestimonial(i));
            dotsContainer.appendChild(dot);
        }
        
        testimonialContainer.parentNode.appendChild(dotsContainer);
        showTestimonial(0);
    }
    
    // Utility Functions
    function showNotification(message, type = 'info') {
        const notification = document.createElement('div');
        notification.className = `notification notification-${type}`;
        notification.style.cssText = `
            position: fixed;
            top: 100px;
            right: 20px;
            background: ${type === 'success' ? '#27ae60' : '#e74c3c'};
            color: white;
            padding: 1rem 1.5rem;
            border-radius: 8px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.2);
            z-index: 10000;
            transform: translateX(100%);
            transition: transform 0.3s ease;
        `;
        notification.textContent = message;
        
        document.body.appendChild(notification);
        
        // Animate in
        setTimeout(() => {
            notification.style.transform = 'translateX(0)';
        }, 100);
        
        // Remove after 3 seconds
        setTimeout(() => {
            notification.style.transform = 'translateX(100%)';
            setTimeout(() => {
                document.body.removeChild(notification);
            }, 300);
        }, 3000);
    }
    
    function showFieldError(input, message) {
        clearFieldError(input);
        
        const errorDiv = document.createElement('div');
        errorDiv.className = 'field-error';
        errorDiv.style.cssText = 'color: #e74c3c; font-size: 0.9rem; margin-top: 0.5rem;';
        errorDiv.textContent = message;
        
        input.parentNode.appendChild(errorDiv);
        input.style.borderColor = '#e74c3c';
    }
    
    function clearFieldError(input) {
        const existingError = input.parentNode.querySelector('.field-error');
        if (existingError) {
            existingError.remove();
        }
        input.style.borderColor = '#ecf0f1';
    }
    
    function isValidEmail(email) {
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return emailRegex.test(email);
    }
    
    function filterCourses(filter) {
        const courses = document.querySelectorAll('.course-card');
        
        courses.forEach(course => {
            if (filter === 'all' || course.getAttribute('data-level') === filter) {
                course.style.display = 'block';
            } else {
                course.style.display = 'none';
            }
        });
    }
    
    function showTestimonial(index) {
        const testimonials = document.querySelectorAll('.testimonial-card');
        const dots = document.querySelectorAll('.testimonial-dot');
        
        testimonials.forEach((testimonial, i) => {
            if (i >= index * 3 && i < (index + 1) * 3) {
                testimonial.style.display = 'block';
            } else {
                testimonial.style.display = 'none';
            }
        });
        
        dots.forEach((dot, i) => {
            if (i === index) {
                dot.style.background = '#e74c3c';
            } else {
                dot.style.background = '#ddd';
            }
        });
        
        currentTestimonial = index;
    }
    
    // Lazy Loading for img
    const img = document.querySelectorAll('img[data-src]');
    
    const imageObserver = new IntersectionObserver((entries, observer) => {
        entries.forEach(entry => {
            if (entry.isIntersecting) {
                const img = entry.target;
                img.src = img.dataset.src;
                img.classList.remove('lazy');
                imageObserver.unobserve(img);
            }
        });
    });
    
    img.forEach(img => imageObserver.observe(img));
    
    // Back to Top Button
    const backToTopBtn = document.createElement('button');
    backToTopBtn.innerHTML = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><path d="M12 19V5" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/><path d="M5 12L12 5L19 12" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>';
    backToTopBtn.className = 'back-to-top';
    backToTopBtn.style.cssText = `
        position: fixed;
        bottom: 30px;
        right: 30px;
        width: 56px;
        height: 56px;
        border-radius: 50%;
        background: #000000;
        color: #ffffff;
        border: none;
        display: grid;
        place-items: center;
        cursor: pointer;
        opacity: 0;
        visibility: hidden;
        transition: transform 0.2s ease, box-shadow 0.2s ease, opacity 0.3s ease, visibility 0.3s ease, background 0.2s ease;
        z-index: 1000;
        box-shadow: 0 10px 30px rgba(0, 0, 0, 0.35);
    `;
    
    document.body.appendChild(backToTopBtn);
    
    window.addEventListener('scroll', () => {
        if (window.pageYOffset > 300) {
            backToTopBtn.style.opacity = '1';
            backToTopBtn.style.visibility = 'visible';
        } else {
            backToTopBtn.style.opacity = '0';
            backToTopBtn.style.visibility = 'hidden';
        }
    });
    
    backToTopBtn.addEventListener('click', () => {
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });
    });

    // Subtle hover/active interactions
    backToTopBtn.addEventListener('mouseenter', () => {
        backToTopBtn.style.transform = 'translateY(-2px)';
        backToTopBtn.style.boxShadow = '0 16px 40px rgba(0, 0, 0, 0.45)';
        backToTopBtn.style.background = '#111111';
    });
    backToTopBtn.addEventListener('mouseleave', () => {
        backToTopBtn.style.transform = 'translateY(0)';
        backToTopBtn.style.boxShadow = '0 10px 30px rgba(0, 0, 0, 0.35)';
        backToTopBtn.style.background = '#000000';
    });
    backToTopBtn.addEventListener('mousedown', () => {
        backToTopBtn.style.transform = 'translateY(0) scale(0.98)';
    });
    backToTopBtn.addEventListener('mouseup', () => {
        backToTopBtn.style.transform = 'translateY(-2px)';
    });
    
    // Initialize tooltips (if any)
    const tooltips = document.querySelectorAll('[data-tooltip]');
    
    tooltips.forEach(element => {
        element.addEventListener('mouseenter', function() {
            const tooltip = document.createElement('div');
            tooltip.className = 'tooltip';
            tooltip.textContent = this.getAttribute('data-tooltip');
            tooltip.style.cssText = `
                position: absolute;
                background: #2c3e50;
                color: white;
                padding: 0.5rem;
                border-radius: 4px;
                font-size: 0.9rem;
                z-index: 1000;
                pointer-events: none;
                white-space: nowrap;
            `;
            
            document.body.appendChild(tooltip);
            
            const rect = this.getBoundingClientRect();
            tooltip.style.left = rect.left + (rect.width / 2) - (tooltip.offsetWidth / 2) + 'px';
            tooltip.style.top = rect.top - tooltip.offsetHeight - 10 + 'px';
            
            this.tooltip = tooltip;
        });
        
        element.addEventListener('mouseleave', function() {
            if (this.tooltip) {
                document.body.removeChild(this.tooltip);
                this.tooltip = null;
            }
        });
    });
    
    // Modern Contact Form Validation and Interactions (for contact.php)
    const modernContactForm = document.getElementById('contactForm');
    
    if (modernContactForm) {
        const inputs = modernContactForm.querySelectorAll('.modern-input, .modern-select, .modern-textarea');
        const submitBtn = document.getElementById('submitBtn');
        const messageTextarea = document.getElementById('message');
        const messageCount = document.getElementById('messageCount');

        // Character count for message
        if (messageTextarea && messageCount) {
            messageTextarea.addEventListener('input', function() {
                const count = this.value.length;
                messageCount.textContent = count;
                
                if (count > 900) {
                    messageCount.style.color = '#e74c3c';
                } else if (count > 800) {
                    messageCount.style.color = '#f39c12';
                } else {
                    messageCount.style.color = '#7f8c8d';
                }
            });
        }

        // Input validation and styling
        inputs.forEach(input => {
            const container = input.closest('.input-container');
            const validationElement = container.parentElement.querySelector('.validation-message');
            
            // Input focus and blur events
            input.addEventListener('focus', function() {
                container.classList.remove('error', 'success');
                if (validationElement) {
                    validationElement.textContent = '';
                    validationElement.className = 'validation-message';
                }
            });

            input.addEventListener('blur', function() {
                validateField(this);
            });

            input.addEventListener('input', function() {
                // Real-time validation for email
                if (this.type === 'email' && this.value) {
                    validateEmail(this);
                }
            });
        });

        // Form submission
        modernContactForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            let isValid = true;
            inputs.forEach(input => {
                if (!validateField(input)) {
                    isValid = false;
                }
            });

            if (isValid) {
                submitForm();
            }
        });

        // Validation functions
        function validateField(field) {
            const container = field.closest('.input-container');
            const validationElement = container.parentElement.querySelector('.validation-message');
            let isValid = true;
            let message = '';

            // Remove previous validation states
            container.classList.remove('error', 'success');
            if (validationElement) {
                validationElement.textContent = '';
                validationElement.className = 'validation-message';
            }

            // Required field validation
            if (field.hasAttribute('required') && !field.value.trim()) {
                isValid = false;
                message = 'This field is required';
            }

            // Pattern validation
            if (field.hasAttribute('pattern') && field.value.trim()) {
                const pattern = new RegExp(field.getAttribute('pattern'));
                if (!pattern.test(field.value)) {
                    isValid = false;
                    message = field.getAttribute('title') || 'Invalid format';
                }
            }

            // Email validation
            if (field.type === 'email' && field.value.trim()) {
                const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                if (!emailPattern.test(field.value)) {
                    isValid = false;
                    message = 'Please enter a valid email address';
                }
            }

            // Phone validation
            if (field.type === 'tel' && field.value.trim()) {
                const phonePattern = /^[\+]?[0-9\s\-\(\)]{10,20}$/;
                if (!phonePattern.test(field.value)) {
                    isValid = false;
                    message = 'Please enter a valid phone number';
                }
            }

            // Message length validation
            if (field.tagName === 'TEXTAREA' && field.value.trim()) {
                if (field.value.length < 10) {
                    isValid = false;
                    message = 'Message must be at least 10 characters long';
                } else if (field.value.length > 1000) {
                    isValid = false;
                    message = 'Message must be less than 1000 characters';
                }
            }

            // Apply validation state
            if (field.value.trim()) {
                if (isValid) {
                    container.classList.add('success');
                    if (validationElement) {
                        validationElement.textContent = '✓ Valid';
                        validationElement.classList.add('success');
                    }
                } else {
                    container.classList.add('error');
                    if (validationElement) {
                        validationElement.textContent = message;
                        validationElement.classList.add('error');
                    }
                }
            }

            return isValid;
        }

        function validateEmail(emailField) {
            const container = emailField.closest('.input-container');
            const validationElement = container.parentElement.querySelector('.validation-message');
            
            if (emailField.value.trim()) {
                const emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                if (emailPattern.test(emailField.value)) {
                    container.classList.remove('error');
                    container.classList.add('success');
                    if (validationElement) {
                        validationElement.textContent = '✓ Valid email';
                        validationElement.className = 'validation-message success';
                    }
                } else {
                    container.classList.remove('success');
                    container.classList.add('error');
                    if (validationElement) {
                        validationElement.textContent = 'Please enter a valid email address';
                        validationElement.className = 'validation-message error';
                    }
                }
            }
        }

        function submitForm() {
            // Show loading state
            submitBtn.classList.add('loading');
            submitBtn.disabled = true;

            // Simulate form submission (replace with actual form submission)
            setTimeout(() => {
                // Submit the form
                modernContactForm.submit();
            }, 1500);
        }
    }

    // FAQ Functionality (for contact.php)
    const faqQuestions = document.querySelectorAll('.faq-question');
    
    if (faqQuestions.length > 0) {
        const questionBubble = document.getElementById('questionBubble');
        const answerBubble = document.getElementById('answerBubble');
        const questionTitle = document.getElementById('questionTitle');
        const answerText = document.getElementById('answerText');

        // FAQ Data (EN/JP)
        const isJP = (document.documentElement.getAttribute('lang') === 'ja') || document.body.classList.contains('lang-jp');
        const faqDataEn = {
            1: { title: 'Do you offer free trial lessons?', text: 'Yes, we offer free trial lessons. Please feel free to apply.' },
            2: { title: 'How are the fees structured?', text: 'We use a point system that allows flexible learning. Please contact us for details.' },
            3: { title: 'Are lessons online only?', text: 'Primarily online lessons, but offline options are available for those who prefer them.' },
            4: { title: 'Is it okay for beginners?', text: 'Yes, we accommodate everyone from complete beginners to advanced learners. We provide instruction tailored to your level.' },
            5: { title: 'What are the J-Bridge usage fees?', text: 'Companies pay success fees upon successful hiring. Job seekers can use the service for free.' },
            6: { title: 'Is visa support available?', text: 'Yes, we provide visa application support for those who find employment through J-Bridge.' }
        };
        const faqDataJp = {
            1: { title: '無料体験レッスンはありますか？', text: 'はい、無料体験レッスンをご用意しています。お気軽にお申し込みください。' },
            2: { title: '料金体系はどうなっていますか？', text: '柔軟に学べるポイント制を採用しています。詳細はお問い合わせください。' },
            3: { title: 'レッスンはオンラインのみですか？', text: '主にオンラインですが、ご希望の方にはオフラインの選択肢もございます。' },
            4: { title: '初心者でも大丈夫ですか？', text: 'はい、完全な初心者から上級者までレベルに合わせて指導しますのでご安心ください。' },
            5: { title: 'J-Bridgeの利用料金はいくらですか？', text: '企業様は採用決定時に成功報酬をお支払いいただきます。求職者の方は無料でご利用いただけます。' },
            6: { title: 'ビザサポートは利用できますか？', text: 'J-Bridge経由で就職された方にはビザ申請サポートをご提供しています。' }
        };
        const faqData = isJP ? faqDataJp : faqDataEn;

        // Add click event listeners to FAQ questions
        faqQuestions.forEach(question => {
            question.addEventListener('click', function() {
                const faqId = this.getAttribute('data-faq');
                const faqInfo = faqData[faqId];
                
                if (faqInfo) {
                    // Remove active class from all questions
                    faqQuestions.forEach(q => q.classList.remove('active'));
                    
                    // Add active class to clicked question
                    this.classList.add('active');
                    
                    // Update question and answer bubbles
                    questionTitle.textContent = faqInfo.title;
                    answerText.textContent = faqInfo.text;
                    
                    // Show both bubbles
                    questionBubble.classList.add('active');
                    answerBubble.classList.add('active');
                }
            });
        });

        // Close bubbles when clicking outside
        if (questionBubble) {
            questionBubble.addEventListener('click', function(e) {
                if (e.target === this) {
                    this.classList.remove('active');
                    answerBubble.classList.remove('active');
                    faqQuestions.forEach(q => q.classList.remove('active'));
                }
            });
        }
        
        if (answerBubble) {
            answerBubble.addEventListener('click', function(e) {
                if (e.target === this) {
                    this.classList.remove('active');
                    questionBubble.classList.remove('active');
                    faqQuestions.forEach(q => q.classList.remove('active'));
                }
            });
        }
    }
    
    console.log('nihongo.net - JavaScript loaded successfully!');

    // Header inline language active indicator
    (function initInlineLangIndicator(){
        const container = document.querySelector('.language-switcher.inline-lang');
        if (!container) return;
        const indicator = container.querySelector('.lang-active-indicator');
        const links = container.querySelectorAll('.lang-inline');
        if (!indicator || links.length === 0) return;
        function positionIndicator(){
            const active = container.querySelector('.lang-inline.active') || links[0];
            const rect = active.getBoundingClientRect();
            const parentRect = container.getBoundingClientRect();
            const left = rect.left - parentRect.left;
            indicator.style.left = left + 'px';
            indicator.style.width = rect.width + 'px';
        }
        positionIndicator();
        window.addEventListener('resize', positionIndicator);
        // animate on hover switch
        links.forEach(link => {
            link.addEventListener('mouseenter', () => {
                const rect = link.getBoundingClientRect();
                const parentRect = container.getBoundingClientRect();
                indicator.style.left = (rect.left - parentRect.left) + 'px';
                indicator.style.width = rect.width + 'px';
            });
            link.addEventListener('mouseleave', positionIndicator);
        });
    })();

    // ===== Scroll-trigger storytelling (steps activating visuals) =====
    (function initScrollStory(){
        const story = document.querySelector('.scroll-story');
        if (!story) return;
        const steps = story.querySelectorAll('.story-step');
        const visual = story.querySelector('.story-visual');
        if (!steps.length || !visual) return;
        const stepObserver = new IntersectionObserver((entries) => {
            entries.forEach((e) => {
                if (e.isIntersecting) {
                    steps.forEach(s => s.classList.remove('is-active'));
                    e.target.classList.add('is-active');
                    const img = e.target.getAttribute('data-visual');
                    if (img) {
                        visual.style.backgroundImage = `url(${img})`;
                        visual.style.backgroundSize = 'cover';
                        visual.style.backgroundPosition = 'center';
                    }
                }
            });
        }, { threshold: 0.6, rootMargin: '-10% 0% -10% 0%' });
        steps.forEach(step => stepObserver.observe(step));
    })();

    // ===== J-Bridge hero sizing for mobile: center text visually =====
    (function initJBridgeHeroSizer(){
        const section = document.querySelector('.j-bridge-hero');
        if (!section) return;
        function resize(){
            const isMobile = window.innerWidth <= 768;
            const header = document.querySelector('.header');
            const headerH = header ? header.offsetHeight : 0;
            if (isMobile) {
                const vh = window.innerHeight || document.documentElement.clientHeight;
                const target = Math.max(400, vh - headerH);
                section.style.minHeight = target + 'px';
                section.style.height = target + 'px';
            } else {
                section.style.minHeight = '';
                section.style.height = '';
            }
        }
        resize();
        window.addEventListener('resize', resize);
    })();

    // ===== Lightweight parallax mouse move (desktop only) =====
    (function initParallax(){
        if (window.matchMedia && window.matchMedia('(hover: none)').matches) return;
        const container = document.querySelector('.parallax-container');
        if (!container) return;
        const layers = container.querySelectorAll('.parallax-layer');
        container.addEventListener('mousemove', (e) => {
            const rect = container.getBoundingClientRect();
            const cx = (e.clientX - rect.left) / rect.width - 0.5;
            const cy = (e.clientY - rect.top) / rect.height - 0.5;
            layers.forEach((layer) => {
                const depth = parseFloat(layer.getAttribute('data-depth') || '0.1');
                const tx = -cx * depth * 30;
                const ty = -cy * depth * 30;
                layer.style.transform = `translate(${tx}px, ${ty}px)`;
            });
        });
    })();

    // ===== HERO SLIDER WITH ADVANCED PAGINATION =====
    (function initHeroSlider() {
        class HeroSlider {
            constructor() {
                this.currentIndex = 0;
                this.totalimg = 0;
                this.interval = null;
                this.intervalTime = 4000; // 4 seconds as requested
                this.isAutoPlaying = true;
                this.isTransitioning = false;
                
                this.elements = {
                    heroimg: null,
                    indicators: null,
                    prevBtn: null,
                    nextBtn: null,
                    paginationInfo: null,
                    heroSection: null
                };
                
                this.init();
            }
            
            init() {
                this.cacheElements();
                this.bindEvents();
                this.updatePaginationInfo();
                this.startAutoPlay();
            }
            
            cacheElements() {
                this.elements.heroimg = document.querySelectorAll('.hero-image');
                this.elements.indicators = document.querySelectorAll('.hero-indicator');
                this.elements.paginationInfo = document.querySelector('.hero-pagination-info');
                this.elements.heroSection = document.querySelector('.hero');
                
                this.totalimg = this.elements.heroimg.length;
                
                console.log(`Hero Slider initialized with ${this.totalimg} img`);
            }
            
            bindEvents() {
                // Indicator events
                this.elements.indicators.forEach((indicator, index) => {
                    indicator.addEventListener('click', () => this.goToImage(index));
                });
                
                // Hover events
                if (this.elements.heroSection) {
                    this.elements.heroSection.addEventListener('mouseenter', () => this.pauseAutoPlay());
                    this.elements.heroSection.addEventListener('mouseleave', () => this.resumeAutoPlay());
                }
                
                // Visibility change events
                document.addEventListener('visibilitychange', () => this.handleVisibilityChange());
            }
            
            handleVisibilityChange() {
                if (document.hidden) {
                    this.pauseAutoPlay();
                } else {
                    this.resumeAutoPlay();
                }
            }
            
            showImage(index) {
                if (this.isTransitioning || index === this.currentIndex) return;
                
                this.isTransitioning = true;
                
                // Remove active class from all img and indicators
                this.elements.heroimg.forEach(img => img.classList.remove('active'));
                this.elements.indicators.forEach(indicator => indicator.classList.remove('active'));
                
                // Add active class to current image and indicator
                this.elements.heroimg[index].classList.add('active');
                this.elements.indicators[index].classList.add('active');
                
                this.currentIndex = index;
                
                // Update pagination info
                this.updatePaginationInfo();
                
                // Reset transition flag after animation completes
                setTimeout(() => {
                    this.isTransitioning = false;
                }, 1000);
            }
            
            nextImage() {
                if (this.isTransitioning) return;
                
                const nextIndex = (this.currentIndex + 1) % this.totalimg;
                this.showImage(nextIndex);
            }
            
            previousImage() {
                if (this.isTransitioning) return;
                
                const prevIndex = (this.currentIndex - 1 + this.totalimg) % this.totalimg;
                this.showImage(prevIndex);
            }
            
            goToImage(index) {
                if (this.isTransitioning || index === this.currentIndex) return;
                
                this.showImage(index);
            }
            
            updatePaginationInfo() {
                if (this.elements.paginationInfo) {
                    this.elements.paginationInfo.innerHTML = `
                        <div class="hero-pagination-counter">
                            ${this.currentIndex + 1} / ${this.totalimg}
                        </div>
                    `;
                }
            }
            
            startAutoPlay() {
                if (this.interval) return;
                
                this.interval = setInterval(() => {
                    this.nextImage();
                }, this.intervalTime);
                
                this.isAutoPlaying = true;
            }
            
            pauseAutoPlay() {
                if (this.interval) {
                    clearInterval(this.interval);
                    this.interval = null;
                    this.isAutoPlaying = false;
                }
            }
            
            resumeAutoPlay() {
                if (!this.isAutoPlaying) {
                    this.startAutoPlay();
                }
            }
            
            restartAutoPlay() {
                this.pauseAutoPlay();
                this.startAutoPlay();
            }
            
            toggleAutoPlay() {
                if (this.isAutoPlaying) {
                    this.pauseAutoPlay();
                } else {
                    this.resumeAutoPlay();
                }
            }
        }

        // Initialize the slider when DOM is ready
        // Create global instance for external access
        window.heroSlider = new HeroSlider();
        
        // Add some helpful console methods for debugging
        console.log('Hero Slider loaded! Auto-play enabled every 4 seconds.');
        console.log('Click indicator dots to jump to specific img.');
    })();

});