/**
 * Protera — Web theme JavaScript
 *
 * Uses jQuery (shared with admin via vendor bundle) and Bootstrap 5 JS for
 * dropdowns, collapse, etc. This file wires up the interactive bits of the
 * homepage: language switcher, product favouriting, back-to-top button,
 * and the add-to-cart demo handler.
 *
 * Alpine 3 is bundled here so per-component files (search-suggest.js,
 * future widgets) can register `window.componentName = function () {...}`
 * factories that the blade-side `x-data="componentName()"` consumes.
 * Single Alpine instance per page — never call Alpine.start() from a
 * per-component file or you get duplicate event handlers.
 *
 * Everything is wrapped in $(function(){ ... }) so handlers bind only after
 * the DOM is ready, and document-delegated events are used for dynamically
 * rendered cards (product cards, favourite hearts) so re-rendered sections
 * keep working.
 */

import $ from 'jquery';
import 'bootstrap/dist/js/bootstrap.bundle.min.js';
import Alpine from 'alpinejs';

// task-116b: import the theme's base stylesheet here so it lands in THIS entry's
// CSS chunk (build/assets/web.css). The package's per-theme Vite build uses
// predictable, non-hashed output names; a *standalone* css/web.css entry would
// share the basename "web" with this js/web.js entry and rollup would rename the
// JS bundle to web2.js (the same gotcha the va-themes/viartas-default build
// documents for admin.css/admin.js). Importing it keeps a single "web" basename
// (web.js + web.css). Loaded first so its base variables/styles sit ahead of the
// component CSS pulled in below (search-suggest, header-search, grid-frontend).
import '../css/web.css';

// Register Alpine factories from per-component files. Each file declares
// `window.factoryName = function () { return { ... } }` — the blade refers
// to it via `x-data="factoryName()"`. Order matters only for Alpine.start()
// at the bottom: registrations must complete before start fires.
//
// search-suggest.js — legacy Core /paieska/suggest dropdown (kept loaded
// in case any non-header surface still mounts it). NOT used by the site
// header any more — replaced by headerSearch() drop-in via task-35.
//
// header-search.js — catalog-focused dropdown wired into the site header
// (Products / Categories / Models / Brands). Pulls from /paieska-katalogas
// /autocomplete and posts click attribution to /paieska-katalogas/record-click.
import './search-suggest.js';
// HeaderSearch migrated to packages/va-modules/header-search (task-23).
// Imported via the @va-modules Vite alias so the Alpine component stays
// bundled in this theme build and shares the theme's Alpine instance.
import '@va-modules/header-search/Resources/assets/js/header-search.js';

// grid-frontend.js — GridBuilder/task-3 frontend renderer's hybrid Alpine
// hooks. The base markup (`<x-gridbuilder::grid-layout>`) is server-side
// rendered + cacheable; this file wakes up Alpine widgets only for blocks
// that opt in via `data-grid-interactive`. The sidecar CSS gets pulled in
// transitively via the JS's own `import '../css/grid-frontend.css'`.
import '@va-modules/grid-builder/Resources/assets/js/grid-frontend.js';

window.Alpine = Alpine;
Alpine.start();

$(function () {
    // Update copyright year in footer
    $('#year').text(new Date().getFullYear());

    // Hero size-picker tabs (Pagal automobilį / Pagal dydį)
    $('.picker-tabs button').on('click', function () {
        var target = $(this).data('target');
        $('.picker-tabs button').removeClass('active');
        $(this).addClass('active');
        $('#byCar, #bySize').hide();
        $('#' + target).fadeIn(150);
    });

    // Favourite toggle on product cards
    // Delegated so re-rendered cards still respond.
    $(document).on('click', '.product-card .fav', function (e) {
        e.preventDefault();
        $(this).toggleClass('active');
        var $i = $(this).find('i');
        if ($(this).hasClass('active')) {
            $i.removeClass('bi-heart').addClass('bi-heart-fill');
        } else {
            $i.removeClass('bi-heart-fill').addClass('bi-heart');
        }
    });

    // Back-to-top button
    var $bt = $('#backTop');
    $(window).on('scroll', function () {
        if ($(window).scrollTop() > 400) $bt.fadeIn(150).css('display', 'flex');
        else $bt.fadeOut(150);
    });
    $bt.on('click', function () {
        $('html, body').animate({ scrollTop: 0 }, 400);
    });

    // Add-to-cart placeholder — bumps the header cart badge and flashes
    // the button green. Real cart wiring will replace this handler when
    // the Cart module ships.
    $(document).on('click', '.btn-cart', function () {
        var $dot = $('.header-icon .badge-dot').first();
        $dot.text(parseInt($dot.text(), 10) + 1);
        $(this).css('background', '#16a34a');
        var self = this;
        setTimeout(function () { $(self).css('background', ''); }, 600);
    });

    // Frontend/task-4 — sticky-shadow handler. `.site-header` is already
    // `position: sticky` via CSS; this just toggles the `.is-scrolled`
    // class once the page has scrolled past 4px so the soft drop-shadow
    // fades in. Vanilla addEventListener with `passive: true` keeps the
    // listener out of the scroll critical path (Chrome warns otherwise).
    var header = document.querySelector('.site-header');
    if (header) {
        var onHeaderScroll = function () {
            if (window.scrollY > 4) {
                header.classList.add('is-scrolled');
            } else {
                header.classList.remove('is-scrolled');
            }
        };
        window.addEventListener('scroll', onHeaderScroll, { passive: true });
        onHeaderScroll();
    }
});
