/**
 * Yatoon / SBS Service Menu - service-menu.js
 */
(function ($) {
    'use strict';

    var NAV_SEL   = '#yatoon-svc-wrap .ysm-cat-nav';
    var TRACK_SEL = '#yatoon-svc-wrap .ysm-featured-track';
    var controlsInjected = false;

    function getNavHeight() {
        var $nav = $(NAV_SEL);
        return $nav.length ? $nav.outerHeight() : 0;
    }
    function getHeaderOffset() {
        return (typeof yatoonMenuData !== 'undefined' && yatoonMenuData.headerOffset)
            ? parseInt(yatoonMenuData.headerOffset, 10) : 0;
    }
    function totalOffset() { return getHeaderOffset() + getNavHeight(); }

    function setScrollMargins() {
        $('#yatoon-svc-wrap .ysm-section').css('scroll-margin-top', (totalOffset() + 12) + 'px');
    }

    function updateNavSticky() {
        var $nav = $(NAV_SEL);
        if (!$nav.length) return;
        $nav.toggleClass('is-stuck', $nav.offset().top - $(window).scrollTop() <= getHeaderOffset() + 1);
    }

    /* Inject arrow buttons and hamburger into DOM only when needed */
    function injectControls() {
        if (controlsInjected) return;
        controlsInjected = true;

        var $row = $('#yatoon-svc-wrap .ysm-cat-nav-row');
        var $nav = $(NAV_SEL);

        // Inject prev arrow before ul
        $row.prepend('<button class="ysm-cat-arrow ysm-cat-prev" style="display:none;">&#8249;</button>');
        // Inject nav icon before prev
        $row.prepend('<button class="ysm-cat-nav-icon" style="display:none;">☰</button>');
        // Inject next arrow after ul
        $row.append('<button class="ysm-cat-arrow ysm-cat-next" style="display:none;">&#8250;</button>');

        // Inject mobile hamburger before nav-row
        var firstCat = $('#yatoon-svc-wrap .ysm-cat-tab').first().text().trim();
        $nav.prepend(
            '<button class="ysm-cat-hamburger" aria-expanded="false" style="display:none;">' +
            '<span class="ysm-cat-hamburger-icon">☰</span>' +
            '<span class="ysm-cat-hamburger-label">' + $('<div>').text(firstCat).html() + '</span>' +
            '<span class="ysm-cat-hamburger-arrow">▾</span>' +
            '</button>'
        );

        // Re-bind arrow clicks after injection
        $(document).on('click', '#yatoon-svc-wrap .ysm-cat-prev', function () {
            var $inner = $('#yatoon-svc-wrap .ysm-cat-nav-inner');
            $inner.animate({ scrollLeft: $inner.scrollLeft() - 200 }, 200, updateNavControls);
        });
        $(document).on('click', '#yatoon-svc-wrap .ysm-cat-next', function () {
            var $inner = $('#yatoon-svc-wrap .ysm-cat-nav-inner');
            $inner.animate({ scrollLeft: $inner.scrollLeft() + 200 }, 200, updateNavControls);
        });
        $('#yatoon-svc-wrap .ysm-cat-nav-inner').on('scroll.ysmArrow', updateNavControls);
    }

    /* Show/hide arrows based on overflow */
    function updateNavControls() {
        var $inner = $('#yatoon-svc-wrap .ysm-cat-nav-inner');
        if (!$inner.length) return;

        var scrollW     = $inner[0].scrollWidth;
        var clientW     = $inner[0].clientWidth;
        var hasOverflow = scrollW > clientW + 4;

        if (hasOverflow) {
            injectControls();
            $('#yatoon-svc-wrap .ysm-cat-prev').css('display', 'flex').prop('disabled', $inner.scrollLeft() <= 0);
            $('#yatoon-svc-wrap .ysm-cat-next').css('display', 'flex').prop('disabled', $inner.scrollLeft() + clientW >= scrollW - 4);
            $('#yatoon-svc-wrap .ysm-cat-nav-icon').css('display', 'flex');
            // Show hamburger on mobile
            if ($(window).width() <= 640) {
                $('#yatoon-svc-wrap .ysm-cat-hamburger').css('display', 'flex');
                $('#yatoon-svc-wrap .ysm-cat-nav-row').hide();
            }
        }
        // If no overflow: controls were never injected, so nothing to hide
    }

    function updateActiveTab() {
        var scrollY   = $(window).scrollTop();
        var offset    = totalOffset() + 16;
        var $sections = $('#yatoon-svc-wrap .ysm-section');
        var activeCat = null;

        $sections.each(function () {
            if ($(this).offset().top - offset <= scrollY) activeCat = $(this).data('cat');
        });
        if (!activeCat && $sections.length) activeCat = $sections.first().data('cat');
        if (!activeCat) return;

        var $tabs = $('#yatoon-svc-wrap .ysm-cat-tab');
        $tabs.removeClass('active').css({
            'background': '#fff',
            'color': '#374151',
            'border-color': '#e5e7eb'
        });
        var $active = $tabs.filter('[data-cat="' + activeCat + '"]');
        $active.addClass('active').css({
            'background': '#050505',
            'color': '#fff',
            'border-color': '#050505'
        });

        var $inner = $('#yatoon-svc-wrap .ysm-cat-nav-inner');
        if ($active.length && $inner.length && $inner[0].scrollWidth > $inner[0].clientWidth) {
            var scrollPos = $active.position().left + $inner.scrollLeft()
                          - ($inner.outerWidth() / 2) + ($active.outerWidth() / 2);
            $inner.animate({ scrollLeft: scrollPos }, 200);
        }

        $('#yatoon-svc-wrap .ysm-cat-hamburger-label').text($active.text().trim());
        $('#yatoon-svc-wrap .ysm-cat-dropdown-item').removeClass('active');
        $('#yatoon-svc-wrap .ysm-cat-dropdown-item[data-cat="' + activeCat + '"]').addClass('active');
    }

    function bindTabClicks() {
        $(document).on('click', '#yatoon-svc-wrap .ysm-cat-tab, #yatoon-svc-wrap .ysm-cat-dropdown-item', function () {
            var $sec = $('#ysm-cat-' + $(this).data('cat'));
            if (!$sec.length) return;
            $('html, body').animate({ scrollTop: $sec.offset().top - totalOffset() - 8 }, 320);
            $('#yatoon-svc-wrap .ysm-cat-dropdown').attr('hidden', true);
            $('#yatoon-svc-wrap .ysm-cat-hamburger').attr('aria-expanded', 'false');
        });
    }

    function bindHamburger() {
        $(document).on('click', '#yatoon-svc-wrap .ysm-cat-hamburger', function () {
            var $dd      = $('#yatoon-svc-wrap .ysm-cat-dropdown');
            var expanded = $(this).attr('aria-expanded') === 'true';
            if (expanded) { $dd.attr('hidden', true); $(this).attr('aria-expanded', 'false'); }
            else          { $dd.removeAttr('hidden'); $(this).attr('aria-expanded', 'true'); }
        });
    }

    function bindFeaturedArrows() {
        $(document).on('click', '#yatoon-svc-wrap .ysm-feat-prev', function () {
            $(TRACK_SEL).animate({ scrollLeft: $(TRACK_SEL).scrollLeft() - 340 }, 250);
        });
        $(document).on('click', '#yatoon-svc-wrap .ysm-feat-next', function () {
            $(TRACK_SEL).animate({ scrollLeft: $(TRACK_SEL).scrollLeft() + 340 }, 250);
        });
    }

    function bindSearch() {
        var $input   = $('#yatoon-svc-wrap .ysm-search-input');
        var $clear   = $('#yatoon-svc-wrap .ysm-search-clear');
        var $results = $('#yatoon-svc-wrap .ysm-search-results');
        var $resList = $('#yatoon-svc-wrap .ysm-search-list');
        var $body    = $('#yatoon-svc-wrap .ysm-menu-body');

        $clear.hide();

        $input.on('input', function () {
            var q = $.trim($(this).val()).toLowerCase();
            if (!q) {
                $results.attr('hidden', true);
                $body.find('.ysm-section').show();
                $clear.hide();
                return;
            }
            $clear.show();
            $body.find('.ysm-section').hide();
            $results.removeAttr('hidden');
            $resList.empty();

            var found = 0;
            $('#yatoon-svc-wrap .ysm-item').each(function () {
                if (($(this).data('name') || '').indexOf(q) !== -1 ||
                    ($(this).data('desc') || '').indexOf(q) !== -1) {
                    $resList.append($(this).clone());
                    found++;
                }
            });
            if (!found) $resList.html('<li style="padding:20px 0;color:#aaa;text-align:center;">No services found</li>');
        });

        $clear.on('click', function () { $input.val('').trigger('input'); });
    }

    $(document).ready(function () {
        if (!$('#yatoon-svc-wrap').length) return;

        setScrollMargins();
        bindTabClicks();
        bindHamburger();
        bindFeaturedArrows();
        bindSearch();

        $(window).on('scroll.ysmNav resize.ysmNav', function () {
            updateNavSticky();
            updateActiveTab();
            setScrollMargins();
            updateNavControls();
        });

        // Check multiple times to catch late rendering
        setTimeout(function() { setScrollMargins(); updateActiveTab(); updateNavControls(); }, 100);
        setTimeout(updateNavControls, 500);
        setTimeout(updateNavControls, 1000);
        $(window).on('load', updateNavControls);
    });

}(jQuery));
