import Vue from 'vue';
import { ready } from '@site/js/utils/dom.js';

/**
 * Search component + global search toggle (vanilla).
 *
 * The component still uses `vue-resource` (`$http`) for the search request
 * — that's out of scope for the legacy removal effort. Only the DOM glue
 * has been converted: window/document listeners, form bindings, and the
 * `.js_toggleSearch` open/close behaviour.
 */
Vue.component('search', {
    props: ['action'],

    data() {
        return {
            term: '',
            pageResultsEnabled: false,
            brandResultsEnabled: false,
            results: [],
            searching: false,
            defaultResults: {
                products: [],
                categories: [],
                pages: [],
                brands: [],
                doctor_surgeries: [],
                debounced_search: null,
            },
        };
    },

    created() {
        const vm = this;
        this.results = this.defaultResults;

        this.debounced_search = window.debouncer(() => {
            if (vm.term.length <= 1) {
                return;
            }
            vm.searching = true;
            vm.$http.get(vm.action + '?term=' + encodeURIComponent(vm.term), {
                before(request) {
                    // Abort the previous request if still in flight.
                    if (vm.previousRequest) {
                        vm.previousRequest.abort();
                    }
                    vm.previousRequest = request;
                },
            }).then((response) => {
                if (response.data.status === 'ok') {
                    vm.results = response.data;
                    vm.searching = false;
                }
            }, () => {
                // Failed request — silently ignore (UI shows last results).
            });
        }, 800);
    },

    mounted() {
        // Click outside clears the term — handler attached once per instance
        // and removed in beforeDestroy so navigating away doesn't leak it.
        this._onWindowClick = () => {
            this.term = '';
        };
        window.addEventListener('click', this._onWindowClick);

        document.querySelectorAll('.searchForm').forEach((form) => {
            form.addEventListener('click', (event) => event.stopPropagation());
            form.addEventListener('submit', (event) => event.preventDefault());
        });
    },

    beforeDestroy() {
        if (this._onWindowClick) {
            window.removeEventListener('click', this._onWindowClick);
            this._onWindowClick = null;
        }
    },

    methods: {
        search() {
            this.debounced_search();
        },

        clearSearch() {
            this.term = '';
        },

        closeMainMenu() {
            // no-op — kept for compatibility with legacy event hooks.
        },

        selectItem(selected_item, type) {
            selected_item.type = type;
            this.results = this.defaultResults;
            this.$dispatch('searchSelection', selected_item);
        },

        formatPrice(price) {
            const formattedPrice = parseFloat(price);
            if (Number.isNaN(formattedPrice)) {
                return '0.00';
            }
            return formattedPrice.toFixed(2);
        },
    },
});

ready(() => {
    const toggles = document.querySelectorAll('.js_toggleSearch');
    if (!toggles.length) {
        return;
    }

    toggles.forEach((toggle) => {
        toggle.addEventListener('click', (event) => {
            event.preventDefault();
            // Stop the click bubbling to the window listener below, which
            // would immediately strip the .active class we just added.
            event.stopPropagation();
            toggle.classList.toggle('active');
        });
    });

    const closeBtn = document.getElementById('closeSearch');
    closeBtn?.addEventListener('click', (event) => {
        event.preventDefault();
        toggles.forEach((toggle) => toggle.classList.remove('active'));
    });

    window.addEventListener('click', () => {
        toggles.forEach((toggle) => toggle.classList.remove('active'));
    });

    document.querySelectorAll('.searchListItem').forEach((item) => {
        item.addEventListener('click', (event) => event.stopPropagation());
    });
});
