/* Yatoon: scoped i18n wrapper -- keeps __() out of the global namespace. */
(function () {
/**
 * Yatoon i18n bridge.
 *
 * Every user-facing literal in this file is wrapped in __(). This resolves it
 * against the WordPress JS translation catalog registered for this handle via
 * wp_set_script_translations(), so a locale's .json file translates the
 * interactive booking flow -- not just the PHP-rendered chrome around it.
 *
 * The fallback matters: if wp-i18n is unavailable for any reason (an
 * aggressive JS optimizer, a very old core, a hand-rolled enqueue) __() must
 * still return the original English rather than throwing and taking the whole
 * booking form down with it. A missing translation is a cosmetic problem; a
 * dead booking form is a lost sale.
 */
var __ = (function () {
    var d = 'yatoon-booking-system';
    if (typeof window !== 'undefined' && window.wp && window.wp.i18n && typeof window.wp.i18n.__ === 'function') {
        return function (s) { return window.wp.i18n.__(s, d); };
    }
    return function (s) { return s; };
})();

/**
 * 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').attr('aria-pressed', 'false');
        var $active = $tabs.filter('[data-cat="' + activeCat + '"]');
        $active.addClass('active').attr('aria-pressed', 'true');

        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) {
                $('<li class="ysm-search-empty"></li>')
                    .text((window.yatoonMenuData && yatoonMenuData.strings && yatoonMenuData.strings.noServices) || __('No services found'))
                    .appendTo($resList);
            }
        });

        $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));

})();
