/**
 * Golden Era Software — Frontend (jQuery + AJAX)
 */
(function ($) {
    'use strict';

    var $header = $('#siteHeader');
    var $nav = $('#mainNav');
    var $navToggle = $('#navToggle');

    // Sticky header
    $(window).on('scroll', function () {
        $header.toggleClass('scrolled', $(this).scrollTop() > 20);
        $('#backToTop').toggleClass('visible', $(this).scrollTop() > 400);
    }).trigger('scroll');

    // Mobile navigation
    $navToggle.on('click', function () {
        var open = $nav.hasClass('open');
        $nav.toggleClass('open', !open);
        $(this).attr('aria-expanded', !open);
    });

    $('.has-dropdown > a').on('click', function (e) {
        if ($(window).width() <= 768) {
            e.preventDefault();
            $(this).parent().toggleClass('open');
        }
    });

    // Close nav on link click (mobile)
    $nav.find('a').on('click', function () {
        if ($(window).width() <= 768) {
            $nav.removeClass('open');
            $navToggle.attr('aria-expanded', 'false');
        }
    });

    // Back to top
    $('#backToTop').on('click', function () {
        $('html, body').animate({ scrollTop: 0 }, 500);
    });

    // Scroll reveal
    function revealOnScroll() {
        $('.reveal').each(function () {
            var $el = $(this);
            var delay = parseInt($el.data('delay') || 0, 10);
            var top = $el.offset().top;
            var winBottom = $(window).scrollTop() + $(window).height() * 0.9;

            if (top < winBottom) {
                setTimeout(function () {
                    $el.addClass('visible');
                }, delay);
            }
        });
    }

    $(window).on('scroll resize', revealOnScroll);
    revealOnScroll();

    // Smooth scroll for anchor links
    $('a[href^="#"]').on('click', function (e) {
        var target = $(this.getAttribute('href'));
        if (target.length) {
            e.preventDefault();
            $('html, body').animate({
                scrollTop: target.offset().top - 80
            }, 500);
        }
    });

    // AJAX: Contact & Quotation forms
    function handleAjaxForm($form, $messageEl) {
        $form.on('submit', function (e) {
            e.preventDefault();

            var $btn = $form.find('button[type="submit"]');
            var $btnText = $btn.find('.btn-text');
            var $btnLoading = $btn.find('.btn-loading');

            $btn.prop('disabled', true);
            $btnText.attr('hidden', true);
            $btnLoading.removeAttr('hidden');
            $messageEl.empty();

            $.ajax({
                url: $form.attr('action'),
                method: 'POST',
                data: $form.serialize(),
                dataType: 'json',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest',
                    'Accept': 'application/json'
                },
                success: function (res) {
                    if (res.success && res.html) {
                        $messageEl.html(res.html);
                        $form[0].reset();
                    }
                },
                error: function (xhr) {
                    var msg = 'Something went wrong. Please try again.';
                    if (xhr.status === 422 && xhr.responseJSON && xhr.responseJSON.errors) {
                        var errors = xhr.responseJSON.errors;
                        msg = Object.values(errors).flat().join('<br>');
                    }
                    $messageEl.html('<div class="form-error">' + msg + '</div>');
                },
                complete: function () {
                    $btn.prop('disabled', false);
                    $btnText.removeAttr('hidden');
                    $btnLoading.attr('hidden', true);
                }
            });
        });
    }

    if ($('#contactForm').length) {
        handleAjaxForm($('#contactForm'), $('#contactFormMessage'));
    }

    if ($('#quotationForm').length) {
        handleAjaxForm($('#quotationForm'), $('#quotationFormMessage'));
    }

    // Hero slideshow
    (function initHeroSlider() {
        var $slider = $('#heroSlider');
        if (!$slider.length) return;

        var $slides = $slider.find('.hero-slide');
        var $dots = $slider.find('.hero-dot');
        var total = $slides.length;
        var current = 0;
        var autoplayMs = 6000;
        var timer = null;
        var plexusRaf = null;

        function goTo(index) {
            if (index < 0) index = total - 1;
            if (index >= total) index = 0;
            current = index;

            var $current = $slides.eq(current);
            $slides.removeClass('is-active').eq(current).addClass('is-active');
            $dots.removeClass('is-active').attr('aria-selected', 'false');
            $dots.eq(current).addClass('is-active').attr('aria-selected', 'true');

            if ($current.hasClass('hero-slide--editorial')) {
                startPlexus($current.find('[data-plexus]')[0]);
            } else {
                stopPlexus();
            }
        }

        function next() { goTo(current + 1); }
        function prev() { goTo(current - 1); }

        function startAutoplay() {
            clearInterval(timer);
            timer = setInterval(next, autoplayMs);
        }

        function pauseAutoplay() {
            clearInterval(timer);
        }

        $dots.on('click', function () {
            goTo(parseInt($(this).data('index'), 10));
            startAutoplay();
        });

        $slider.on('mouseenter focusin', pauseAutoplay);
        $slider.on('mouseleave focusout', startAutoplay);

        // Touch swipe
        var touchStartX = 0;
        $slider[0].addEventListener('touchstart', function (e) {
            touchStartX = e.changedTouches[0].screenX;
        }, { passive: true });
        $slider[0].addEventListener('touchend', function (e) {
            var diff = e.changedTouches[0].screenX - touchStartX;
            if (Math.abs(diff) > 50) {
                diff < 0 ? next() : prev();
                startAutoplay();
            }
        }, { passive: true });

        // Plexus canvas (partner slide)
        function startPlexus(canvas) {
            if (!canvas || !canvas.getContext) return;
            stopPlexus();
            var ctx = canvas.getContext('2d');
            var w, h, nodes = [], maxDist = 120;

            function resize() {
                w = canvas.width = canvas.offsetWidth;
                h = canvas.height = canvas.offsetHeight;
                if (nodes.length < 40) {
                    nodes = [];
                    for (var i = 0; i < 45; i++) {
                        nodes.push({
                            x: Math.random() * w,
                            y: Math.random() * h,
                            vx: (Math.random() - 0.5) * 0.4,
                            vy: (Math.random() - 0.5) * 0.4
                        });
                    }
                }
            }

            function draw() {
                ctx.clearRect(0, 0, w, h);
                nodes.forEach(function (n) {
                    n.x += n.vx;
                    n.y += n.vy;
                    if (n.x < 0 || n.x > w) n.vx *= -1;
                    if (n.y < 0 || n.y > h) n.vy *= -1;
                });
                for (var i = 0; i < nodes.length; i++) {
                    for (var j = i + 1; j < nodes.length; j++) {
                        var dx = nodes[i].x - nodes[j].x;
                        var dy = nodes[i].y - nodes[j].y;
                        var dist = Math.sqrt(dx * dx + dy * dy);
                        if (dist < maxDist) {
                            ctx.strokeStyle = 'rgba(255,255,255,' + (0.15 * (1 - dist / maxDist)) + ')';
                            ctx.beginPath();
                            ctx.moveTo(nodes[i].x, nodes[i].y);
                            ctx.lineTo(nodes[j].x, nodes[j].y);
                            ctx.stroke();
                        }
                    }
                }
                ctx.fillStyle = 'rgba(255,255,255,0.5)';
                nodes.forEach(function (n) {
                    ctx.beginPath();
                    ctx.arc(n.x, n.y, 2, 0, Math.PI * 2);
                    ctx.fill();
                });
                plexusRaf = requestAnimationFrame(draw);
            }

            resize();
            $(window).on('resize.heroPlexus', resize);
            draw();
        }

        function stopPlexus() {
            if (plexusRaf) cancelAnimationFrame(plexusRaf);
            plexusRaf = null;
            $(window).off('resize.heroPlexus');
        }

        goTo(0);
        startAutoplay();
    })();

})(jQuery);
