import Plugin from 'src/plugin-system/plugin.class';

export default class BcAquaSwitchListing extends Plugin {
    init() {
        this._bindEvents();
        this._applyListViewClasses();
        this._observeListingChanges();
    }

    _bindEvents() {
        const form = this.el;

        if (form) {
            form.addEventListener('change', (event) => {
                if (event.target.matches('input[type="radio"]')) {
                    this._onStyleChange(event.target.value);
                }
            });
        }
    }

    _onStyleChange(value) {
        let uri = window.location.href;

        if (uri.includes('#')) {
            uri = uri.replace('#', '');
        }

        if (uri.includes('boxLayout')) {
            uri = uri.replace(/(boxLayout=)[^&]+/, `$1${value}`);
        } else {
            const hasParams = /[a-z\d]+=[a-z\d]+/gi.test(uri);
            uri += hasParams ? `&boxLayout=${value}` : `?boxLayout=${value}`;
        }

        window.location.href = uri;
    }

    _applyListViewClasses() {
        const standardBoxes = document.querySelectorAll('.box-standard.bc-listbox');
        const minimalBoxes = document.querySelectorAll('.box-minimal.bc-listbox');

        standardBoxes.forEach((box) => {
            const parent = box.closest('div');
            if (parent && !parent.classList.contains('listview')) {
                parent.classList.add('listview');
            }
        });

        minimalBoxes.forEach((box) => {
            const parent = box.closest('div');
            if (parent && !parent.classList.contains('listview-defualt')) {
                parent.classList.add('listview-defualt');
            }
        });
    }

    _observeListingChanges() {
        const listing = document.querySelector('.cms-element-product-listing');
        if (!listing) return;

        // Use MutationObserver instead of DOMSubtreeModified
        this.observer = new MutationObserver(() => {
            this._applyListViewClasses();
        });

        this.observer.observe(listing, {
            childList: true,
            subtree: true,
        });
    }

    destroy() {
        if (this.observer) {
            this.observer.disconnect();
        }
    }
}