/**
 * LICEUL CU PROGRAM SPORTIV "MIRCEA ELIADE"
 * Main JavaScript File - Refactored & Optimized
 */

'use strict';

document.addEventListener('DOMContentLoaded', function() {
    
    // ========== 1. CORE & NAVIGATION ==========
    const AppConfig = {
        init() {
            this.setupHeader();
            this.setupMobileNav();
            this.setupActiveLinks();
            this.setupPreloader();
        },

        setupHeader() {
            const header = document.getElementById('header');
            if (!header || header.classList.contains('header-solid')) return;

            window.addEventListener('scroll', () => {
                if (window.scrollY > 100) {
                    header.classList.add('scrolled');
                } else {
                    header.classList.remove('scrolled');
                }
            });
        },

        setupMobileNav() {
            const toggle = document.getElementById('mobileToggle');
            const nav = document.getElementById('nav');
            
            if (!toggle || !nav) return;
            
            const toggleMenu = () => {
                nav.classList.toggle('active');
                if (toggle.querySelector('i')) {
                     toggle.querySelector('i').className = nav.classList.contains('active') ? 'bi bi-x' : 'bi bi-list';
                }
                document.body.style.overflow = nav.classList.contains('active') ? 'hidden' : '';
            };

            toggle.addEventListener('click', toggleMenu);

            nav.querySelectorAll('a:not(.nav-dropdown > a)').forEach(link => {
                link.addEventListener('click', () => {
                    nav.classList.remove('active');
                    document.body.style.overflow = '';
                });
            });
        },

        setupActiveLinks() {
            const sections = document.querySelectorAll('section[id]');
            const navLinks = document.querySelectorAll('.nav-link');
            if (!sections.length) return;

            window.addEventListener('scroll', () => {
                const scrollY = window.pageYOffset;
                sections.forEach(section => {
                    const sectionTop = section.offsetTop - 150;
                    const sectionId = section.getAttribute('id');
                    if (scrollY > sectionTop && scrollY <= sectionTop + section.offsetHeight) {
                        navLinks.forEach(link => {
                            link.classList.remove('active');
                            if (link.getAttribute('href').includes(`#${sectionId}`)) {
                                link.classList.add('active');
                            }
                        });
                    }
                });
            });
        },

        setupPreloader() {
            const preloader = document.getElementById('preloader');
            if (preloader) {
                window.addEventListener('load', () => {
                    preloader.style.opacity = '0';
                    setTimeout(() => preloader.style.display = 'none', 500);
                });
            }
        }
    };

    // ========== 2. THEME & UX ==========
    const UXManager = {
        init() {
            this.setupDarkMode();
            this.setupBackToTop();
            this.setupSmoothScroll();
        },

        setupDarkMode() {
            const toggle = document.querySelector('.dark-mode-toggle');
            if (!toggle) return;

            const prefersDark = window.matchMedia('(prefers-color-scheme: dark)');
            
            const setTheme = (theme) => {
                document.documentElement.setAttribute('data-theme', theme);
                localStorage.setItem('theme', theme);
                toggle.innerHTML = theme === 'dark' ? '<i class="bi bi-sun-fill"></i>' : '<i class="bi bi-moon-fill"></i>';
            };

            const savedTheme = localStorage.getItem('theme');
            if (savedTheme) {
                setTheme(savedTheme);
            } else if (prefersDark.matches) {
                setTheme('dark');
            }

            toggle.addEventListener('click', () => {
                const current = document.documentElement.getAttribute('data-theme');
                setTheme(current === 'dark' ? 'light' : 'dark');
            });
        },

        setupBackToTop() {
            const button = document.getElementById('backToTop');
            if (!button) return;

            window.addEventListener('scroll', () => {
                if (window.scrollY > 500) button.classList.add('visible');
                else button.classList.remove('visible');
            });

            button.addEventListener('click', (e) => {
                e.preventDefault();
                window.scrollTo({ top: 0, behavior: 'smooth' });
            });
        },

        setupSmoothScroll() {
            document.querySelectorAll('a[href^="#"]').forEach(anchor => {
                anchor.addEventListener('click', function(e) {
                    const href = this.getAttribute('href');
                    if (href === '#' || href === '') return;
                    const target = document.querySelector(href);
                    if (target) {
                        e.preventDefault();
                        const offsetPosition = target.getBoundingClientRect().top + window.pageYOffset - 80;
                        window.scrollTo({ top: offsetPosition, behavior: 'smooth' });
                    }
                });
            });
        }
    };

    // ========== 3. CONTENT & ANIMATIONS ==========
    const ContentManager = {
        init() {
            this.setupCounters();
            this.setupScrollAnimations();
            this.setupTabs();
            this.setupHeroSlideshow();
        },

        setupCounters() {
            const counters = document.querySelectorAll('[data-count]');
            const observer = new IntersectionObserver((entries) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        const el = entry.target;
                        const target = parseInt(el.dataset.count);
                        const suffix = el.dataset.suffix || '';
                        let current = 0;
                        const increment = target / 50;
                        const timer = setInterval(() => {
                            current += increment;
                            if (current >= target) {
                                el.textContent = target + suffix;
                                clearInterval(timer);
                            } else {
                                el.textContent = Math.floor(current) + suffix;
                            }
                        }, 20);
                        observer.unobserve(el);
                    }
                });
            }, { threshold: 0.5 });
            counters.forEach(c => observer.observe(c));
        },

        setupScrollAnimations() {
            const elements = document.querySelectorAll('.fade-in, .stagger');
            const observer = new IntersectionObserver((entries) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        entry.target.classList.add('visible');
                        observer.unobserve(entry.target);
                    }
                });
            }, { threshold: 0.1 });
            elements.forEach(el => observer.observe(el));
        },

        setupTabs() {
            const aboutButtons = document.querySelectorAll('.portfolio-filter[data-tab]');
            if (aboutButtons.length) {
                aboutButtons.forEach(btn => {
                    btn.addEventListener('click', () => {
                        aboutButtons.forEach(b => b.classList.remove('active'));
                        document.querySelectorAll('.tab-content').forEach(tc => {
                            tc.style.display = 'none';
                            tc.classList.remove('active');
                        });
                        btn.classList.add('active');
                        const target = document.getElementById(`tab-${btn.dataset.tab}`);
                        if (target) {
                            target.style.display = 'block';
                            setTimeout(() => target.classList.add('active'), 10);
                        }
                    });
                });
            }
        },

        setupHeroSlideshow() {
            const slides = document.querySelectorAll('.hero-slide');
            if (!slides.length) return;
            let current = 0;
            setInterval(() => {
                slides[current].classList.remove('active');
                current = (current + 1) % slides.length;
                slides[current].classList.add('active');
            }, 5000);
        }
    };

    // ========== 4. MEDIA & INTERACTIONS ==========
    const InteractionManager = {
        init() {
            this.setupContactForm();
            this.setupNewsletter();
            this.setupTestimonials();
        },

        setupContactForm() {
            const form = document.getElementById('contactForm');
            if (!form) return;
            form.addEventListener('submit', (e) => {
                e.preventDefault();
                alert('Mesajul a fost trimis cu succes!');
                form.reset();
            });
        },

        setupNewsletter() {
            document.querySelectorAll('.newsletter-form').forEach(form => {
                form.addEventListener('submit', (e) => {
                    e.preventDefault();
                    alert('Mulțumim pentru abonare!');
                    form.reset();
                });
            });
        },

        setupTestimonials() {
            const data = [
                { text: "Liceul Mircea Eliade mi-a oferit fundamentul pe care mi-am construit cariera sportivă.", name: "Alexandru Munteanu", role: "Absolvent 2018", initials: "AM" },
                { text: "Am învățat aici ce înseamnă disciplina și determinarea.", name: "Elena Vasilescu", role: "Studentă SUA", initials: "EV" },
                { text: "Antrenorii noștri de judo sunt excepționali.", name: "Mihai Rădulescu", role: "Lotul Național", initials: "MR" }
            ];
            let index = 0;
            const textEl = document.getElementById('testimonialText');
            if (!textEl) return;
            
            const update = () => {
                const t = data[index];
                textEl.textContent = `"${t.text}"`;
                document.getElementById('testimonialName').textContent = t.name;
                document.getElementById('testimonialRole').textContent = t.role;
                document.getElementById('testimonialAvatar').textContent = t.initials;
            };

            const btnNext = document.getElementById('nextTestimonial');
            if (btnNext) btnNext.addEventListener('click', () => {
                index = (index + 1) % data.length;
                update();
            });
            
            // AutoPlay
            setInterval(() => { index = (index + 1) % data.length; update(); }, 6000);
        }
    };

    AppConfig.init();
    UXManager.init();
    ContentManager.init();
    InteractionManager.init();
});

// Helper functions for HTML onclick events
const newsData = {
    1: { category: 'Sport', title: 'Echipa de volei campioană', date: '15 Nov 2024', gradient: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)', content: '<p>Echipa de volei juniori a obținut titlul de campioană națională.</p>' },
    2: { category: 'Erasmus+', title: 'Nou proiect Erasmus+', date: '10 Nov 2024', gradient: 'linear-gradient(135deg, #003399 0%, #0052cc 100%)', content: '<p>Liceul a primit finanțare pentru un nou proiect.</p>' },
    3: { category: 'SmartLab', title: 'Inaugurare SmartLab', date: '5 Nov 2024', gradient: 'linear-gradient(135deg, #11998e 0%, #38ef7d 100%)', content: '<p>S-a inaugurat laboratorul digital SmartLab.</p>' }
};

window.openNewsModal = function(id) {
    const news = newsData[id];
    const modal = document.getElementById('newsModal');
    if (!news || !modal) return;
    
    document.getElementById('newsModalHeader').style.background = news.gradient;
    document.getElementById('modalCategory').textContent = news.category;
    document.getElementById('modalTitle').textContent = news.title;
    document.getElementById('modalDate').textContent = news.date;
    document.getElementById('newsModalBody').innerHTML = news.content;
    
    modal.classList.add('active');
    document.body.style.overflow = 'hidden';
};

window.closeNewsModal = function() {
    const modal = document.getElementById('newsModal');
    if (modal) {
        modal.classList.remove('active');
        document.body.style.overflow = '';
    }
};

window.shareNews = function(platform) {
    const url = window.location.href;
    const title = document.getElementById('modalTitle')?.textContent;
    let shareUrl = '';
    if (platform === 'facebook') shareUrl = `https://www.facebook.com/sharer/sharer.php?u=${url}`;
    if (platform === 'whatsapp') shareUrl = `https://api.whatsapp.com/send?text=${title} ${url}`;
    if (shareUrl) window.open(shareUrl, '_blank', 'width=600,height=400');
};