/**
 * FRESH Theme — The Culinary Edge
 * Main JavaScript
 */

(function () {
    'use strict';

    /* ===== Header Scroll ===== */
    const header = document.getElementById('site-header');
    if (header) {
        const onScroll = () => {
            header.classList.toggle('is-scrolled', window.scrollY > 60);
        };
        window.addEventListener('scroll', onScroll, { passive: true });
        onScroll();
    }

    /* ===== Mobile Menu ===== */
    const toggle = document.getElementById('mobile-toggle');
    const nav = document.getElementById('main-nav');
    if (toggle && nav) {
        toggle.addEventListener('click', () => {
            const open = nav.classList.toggle('is-open');
            toggle.classList.toggle('is-active');
            toggle.setAttribute('aria-expanded', open);
            document.body.style.overflow = open ? 'hidden' : '';
        });

        // Close on link click
        nav.querySelectorAll('a').forEach(link => {
            link.addEventListener('click', () => {
                nav.classList.remove('is-open');
                toggle.classList.remove('is-active');
                toggle.setAttribute('aria-expanded', 'false');
                document.body.style.overflow = '';
            });
        });
    }

    /* ===== Smooth Scroll ===== */
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function (e) {
            const id = this.getAttribute('href');
            if (id === '#') return;
            const target = document.querySelector(id);
            if (target) {
                e.preventDefault();
                const offset = header ? header.offsetHeight + 20 : 80;
                const top = target.getBoundingClientRect().top + window.scrollY - offset;
                window.scrollTo({ top, behavior: 'smooth' });
            }
        });
    });

    /* ===== Scroll Animations (Intersection Observer) ===== */
    const initAnimations = () => {
        const targets = document.querySelectorAll('.fade-up, .stagger-children, .knife-reveal');
        if (!targets.length || !('IntersectionObserver' in window)) return;

        const observer = new IntersectionObserver(
            (entries) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        entry.target.classList.add('is-visible');
                        observer.unobserve(entry.target);
                    }
                });
            },
            { threshold: 0.15, rootMargin: '0px 0px -40px 0px' }
        );

        targets.forEach(el => observer.observe(el));
    };

    /* ===== Contact Form AJAX ===== */
    const initForm = () => {
        const form = document.getElementById('fresh-contact-form');
        if (!form || typeof freshTheme === 'undefined') return;

        form.addEventListener('submit', async (e) => {
            e.preventDefault();

            const feedback = document.getElementById('form-feedback');
            const btn = form.querySelector('button[type="submit"]');
            const original = btn.textContent;

            btn.textContent = 'שולח...';
            btn.disabled = true;

            const data = new FormData(form);
            data.append('action', 'fresh_contact');
            data.append('nonce', freshTheme.nonce);

            try {
                const res = await fetch(freshTheme.ajax, { method: 'POST', body: data });
                const json = await res.json();

                if (feedback) {
                    feedback.textContent = json.data?.message || (json.success ? 'נשלח בהצלחה!' : 'שגיאה');
                    feedback.style.color = json.success ? 'var(--fresh-accent)' : 'var(--fresh-error)';
                }

                if (json.success) form.reset();
            } catch {
                if (feedback) {
                    feedback.textContent = 'שגיאת רשת. נסה שוב.';
                    feedback.style.color = 'var(--fresh-error)';
                }
            } finally {
                btn.textContent = original;
                btn.disabled = false;
            }
        });

        // Input focus glow
        form.querySelectorAll('input, textarea').forEach(input => {
            input.addEventListener('focus', () => {
                input.style.borderColor = 'rgba(200, 255, 0, 0.4)';
            });
            input.addEventListener('blur', () => {
                input.style.borderColor = 'rgba(255, 255, 255, 0.08)';
            });
        });
    };

    /* ===== Active Nav Highlight ===== */
    const initActiveNav = () => {
        const sections = document.querySelectorAll('section[id]');
        if (!sections.length) return;

        const navLinks = document.querySelectorAll('.main-nav__link');

        const observer = new IntersectionObserver(
            (entries) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        const id = entry.target.id;
                        navLinks.forEach(link => {
                            link.classList.toggle(
                                'is-active',
                                link.getAttribute('href') === `#${id}`
                            );
                        });
                    }
                });
            },
            { threshold: 0.3 }
        );

        sections.forEach(s => observer.observe(s));
    };

    /* ===== Init ===== */
    document.addEventListener('DOMContentLoaded', () => {
        initAnimations();
        initForm();
        initActiveNav();
    });

})();
