import { ready, delegate } from '@site/js/utils/dom.js';
import * as Cookies from '@site/js/utils/cookies.js';

/**
 * Multi-currency selector (vanilla).
 *
 * Listens for clicks on `.currencySelector a`, writes a `currency` cookie,
 * swaps the symbol/code in the selector label, and shows the matching
 * price spans inside `.multiPriceBlock`.
 *
 * The legacy version also rewrote the browse-page URL with `price_min` /
 * `price_max` / `currency_ratio` query params and triggered `filterAjax()`.
 * That whole code path depended on the now-deleted `shop/js/mtc_filter.js`
 * (the browse page is fully Vue-driven now), so it is gone here.
 */
ready(() => {
    delegate(document, '.currencySelector a', 'click', (event, target) => {
        event.preventDefault();

        const currency = target.dataset.currency;
        const currencySymbol = target.dataset.currencySymbol;
        if (!currency || !currencySymbol) {
            return;
        }

        const selector = document.querySelector('.selectedCurrency');
        if (!selector) {
            return;
        }

        const currentCurrency = selector.dataset.currentCurrency;
        const currentCurrencySymbol = selector.dataset.currentCurrencySymbol;

        // Persist the choice for 100 days, site-wide.
        Cookies.set('currency', currency, {
            expires: 100,
            path: '/',
        });

        // Swap the displayed code + symbol in the selector label.
        selector.innerHTML = selector.innerHTML
            .replace(currentCurrency, currency)
            .replace(currentCurrencySymbol, currencySymbol);

        selector.dataset.currentCurrency = currency;
        selector.dataset.currentCurrencySymbol = currencySymbol;

        // Reveal the matching price span inside every multi-price block.
        document.querySelectorAll('.multiPriceBlock span').forEach(span => {
            span.style.display = 'none';
            span.classList.remove('show');
        });
        document.querySelectorAll(`.multiPriceBlock .${currency}`).forEach(span => {
            span.style.display = '';
            span.classList.add('show');
        });

        // The "non-GBP totals are approximate" hint shows only for non-GBP.
        const multiCurrencyTotal = document.getElementById('multiCurrencyTotal');
        if (multiCurrencyTotal) {
            multiCurrencyTotal.classList.toggle('show', currency !== 'GBP');
        }
    });
});
