document.addEventListener('DOMContentLoaded', () => {
    const searchbarBoxType = 'searchbar-box';
    const searchbarType = 'searchbar';
    const searchbarResultType = 'searchbar-result';
    const searchbarLoadingType = 'searchbar-loading';


    const searchbarBoxes = document.querySelectorAll(`[data-type=${searchbarBoxType}]`);

    searchbarBoxes.forEach((searchbarBox) => {
        const searchbar = searchbarBox.querySelector(`[data-type=${searchbarType}]`);
        const searchbarResult = searchbarBox.querySelector(`[data-type=${searchbarResultType}]`);
        const searchbarLoading = searchbarBox.querySelector(`[data-type=${searchbarLoadingType}]`);

        if (!searchbar || !searchbarResult)
            return;

        searchbar.addEventListener("input", async () => {
            const searchTerm = searchbar.value;

            searchbarResult.innerHTML = '';

            if (!searchTerm) {
                searchbarResult.dataset.active = 'false';
                return;
            }

            searchbarResult.dataset.active = 'true';
            searchbarLoading.dataset.active = 'true';

            const formData = new URLSearchParams();
            formData.append('action', 'ajax_search');
            formData.append('security', ajax_search_object.nonce);
            formData.append('term', searchTerm);

            const response = await fetch(ajax_search_object.url, {
                method: "POST",
                body: formData,
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                }
            });

            const data = await response.json();
            searchbarLoading.dataset.active = 'false';

            if (!response.ok) {
                Toastify({
                    text: data.message,
                    duration: 3000,
                    gravity: "top", // `top` or `bottom`
                    position: "center", // `left`, `center` or `right`
                    stopOnFocus: true, // Prevents dismissing of toast on hover
                    style: {
                        background: "var(--color-red-500)",
                        borderRadius: "8px",
                        fontSize: "var(--text-body-s)"
                    }
                }).showToast();
                return
            }

            let resultHtml = '';
            resultHtml += `
            <div class="flex flex-row mb-4">
                <div class="flex-1 text-body-s">نتایج جست‌وجوی 
                    <span class="text-primary">${searchTerm}</span>
                    در محصولات
                </div>
                <button class="text-body-s text-primary cursor-pointer" onclick="(e) => e.target.submit()">مشاهده بیشتر</button>
            </div>
        `;

            resultHtml += '<ul class="flex flex-col gap-y-1">'

            if (data.data.length === 0) {
                resultHtml += '<li class="text-detail">نتیجه‌ای یافت نشد.</li>'
            }

            data.data.forEach(item => {
                let regular_price = price_formater(item['regular_price']);
                let sale_price = price_formater(item['sale_price']);

                let discountHtml = "";
                if (item['discount'])
                    discountHtml = `
                    <div class="flex flex-row items-center gap-x-1">
                        <span class="text-detail px-2 bg-red-500 text-white rounded-full self-start leading-5">٪${item['discount']}</span>
                        <span class="text-detail text-fg-2 line-through leading-none text-left">${regular_price} تومانء</span>
                    </div>
                `;

                let image = item['image'];
                let imageHtml = "";
                if (image) {
                    imageHtml = `<img src="${image['src']}" alt="${image['alt']}"/>`;
                }

                resultHtml += `
                <li class="flex">
                    <a class="flex flex-row gap-x-3 w-full transition-colors hover:bg-neutral-100" href="${item['link']}">
                        <div class="border border-border rounded-xl w-(--product-s-width) h-(--product-s-height) overflow-hidden">
                            ${imageHtml}
                        </div> 
                        <div class="flex-1 grid grid-cols-4">
                            <div class="col-span-3 flex flex-col gap-y-1">
                                <span class="text-detail text-fg-2">${item['category']}</span>
                                <p class="text-body-s">${item['title']}</p>
                            </div>
                            <div class="col-span-1 flex flex-col items-end self-center gap-2">
                                ${discountHtml}
                                <span class="text-body leading-none text-left">${sale_price} تومانء</span>
                            </div>                  
                        </div>
                    </a>
                </li>
            `;
            });

            resultHtml += "</ul>";
            searchbarResult.innerHTML = resultHtml;
        });
    });
});

document.addEventListener('DOMContentLoaded', () => {
    const searchbarBoxType = 'searchbar-box';
    const searchbarType = 'searchbar';
    const searchHistoryType = 'searchbar-history';
    const searchHistoryContentType = 'searchbar-history-content';

    const searchbarBoxes = document.querySelectorAll(`[data-type=${searchbarBoxType}]`);

    searchbarBoxes.forEach((searchbarBox) => {
        const searchbar = searchbarBox.querySelector(`[data-type=${searchbarType}]`);
        const searchHistory = searchbarBox.querySelector(`[data-type=${searchHistoryType}]`);
        const searchHistoryContent = searchbarBox.querySelector(`[data-type=${searchHistoryContentType}]`);

        if (!searchHistory || !searchHistoryContent)
            return;

        let data = JSON.parse(localStorage.getItem("search-history")) ?? [];

        if (data.length === 0) {
            searchHistory.dataset.active = 'false';
        } else {
            searchHistory.dataset.active = 'true';

            let resultHtml = '';
            data.forEach(term => {
                resultHtml += `
                    <li class="px-4 py-1 cursor-pointer transition hover:bg-neutral-100 border border-border rounded-full">
                        ${term}
                    </li>
                `;
            });

            searchHistoryContent.innerHTML = resultHtml;
        }

        const items = searchHistoryContent.querySelectorAll("li");
        items.forEach(item => {
            item.addEventListener('click', () => {
                searchbar.value = item.innerText;
                searchbarBox.submit();
            });
        });
    });
});