/* ==========================================
    GLOBAL CART (HAR BIR SAHIFA UCHUN)
========================================== */

let cart = JSON.parse(localStorage.getItem('cart')) || [];


/* ==========================================
    MAHSULOT SAHIFASIDA "SAVATGA QO‘SHISH"
========================================== */

const addToCartButtons = document.querySelectorAll('.add-to-cart');

addToCartButtons.forEach(btn => {
    btn.addEventListener('click', () => {
        const name = btn.getAttribute('data-name');
        const price = parseFloat(btn.getAttribute('data-price'));

        cart.push({ name, price });
        localStorage.setItem('cart', JSON.stringify(cart));

        alert(`${name} savatga qo‘shildi!`);

        // Agar cart sahifasida bo‘lsa → yangilasin
        renderCart();
    });
});


/* ==========================================
     CART SAHIFASI ELEMENTLARI
========================================== */

const cartItems = document.querySelector('.cart-items');
const totalElem = document.getElementById('total');
const searchInput = document.getElementById('search');
const cartModal = document.getElementById('cartModal');


/* ==========================================
        SAVATNI CHIZISH FUNKSIYASI
========================================== */

function renderCart(filter = "") {
    if (!cartItems) return; // boshqa sahifalarda hech narsa qilmaydi

    cartItems.innerHTML = "";
    let total = 0;

    cart.forEach((item, index) => {
        if (item.name.toLowerCase().includes(filter.toLowerCase())) {

            total += item.price;

            const div = document.createElement('div');
            div.classList.add("cart-item");

            div.innerHTML = `
                <span>${item.name} - $${item.price}</span>
                <button onclick="removeItem(${index})">🗑</button>
            `;

            cartItems.appendChild(div);
        }
    });

    totalElem.textContent = "Jami: $" + total;
}


/* ==========================================
            MAHSULOTNI O‘CHIRISH
========================================== */

function removeItem(index) {
    cart.splice(index, 1);
    localStorage.setItem("cart", JSON.stringify(cart));
    renderCart(searchInput ? searchInput.value : "");
}


/* ==========================================
              BUYURTMA BERISH
========================================== */

function checkout() {
    if (cart.length === 0) {
        alert("Savat bo‘sh!");
        return;
    }

    alert("Buyurtmangiz qabul qilindi!");
    cart = [];
    localStorage.setItem("cart", JSON.stringify(cart));
    renderCart();
}


/* ==========================================
                QIDIRUV
========================================== */

if (searchInput) {
    searchInput.addEventListener("input", () => {
        renderCart(searchInput.value);
    });
}


/* ==========================================
              MODAL SAVAT (Uzum uslub)
========================================== */

function openCart() {
    if (cartModal) {
        renderCart();
        cartModal.style.display = "flex";
    }
}

function closeCart() {
    if (cartModal) {
        cartModal.style.display = "none";
    }
}


/* ==========================================
      SAHIFA YUKLANGANDA ISHGA TUSHIRISH
========================================== */

renderCart();
// === Qidiruv tizimi + Highlight ===
document.addEventListener('DOMContentLoaded', () => {
    const productList = document.querySelector('.product-list');
    if (!productList) return;

    // --- QIDIRUV ELEMENTLARI ---
    const searchBox = document.createElement('div');
    searchBox.className = 'search-box';

    const searchInput = document.createElement('input');
    searchInput.type = "search";
    searchInput.placeholder = "Telefon nomi, narx yoki xotira bo‘yicha qidiring...";
    searchInput.id = "searchInput";

    const clearBtn = document.createElement('button');
    clearBtn.textContent = "Tozalash";
    clearBtn.id = "clearSearch";

    searchBox.appendChild(searchInput);
    searchBox.appendChild(clearBtn);
    productList.parentNode.insertBefore(searchBox, productList);

    // --- MAHSULOTLAR ---
    const products = [...document.querySelectorAll('.product')];

    function normalize(t) {
        return (t || "").toLowerCase();
    }

    // highlight funksiyasi
    function highlight(text, query) {
        if (!query) return text;
        const regex = new RegExp(`(${query})`, "gi");
        return text.replace(regex, `<mark>$1</mark>`);
    }

    // Qidiruv bajarish
    function searchProducts(val) {
        const q = normalize(val);

        products.forEach(prod => {
            const nameElem = prod.querySelector("h3");
            const pTags = prod.querySelectorAll("p");

            const fullText =
                normalize(nameElem.innerText) +
                " " +
                normalize([...pTags].map(p => p.innerText).join(" "));

            if (fullText.includes(q)) {
                prod.style.display = "block";

                // highlight qo‘llash
                nameElem.innerHTML = highlight(nameElem.innerText, val);

                pTags.forEach(p => {
                    p.innerHTML = highlight(p.innerText, val);
                });

            } else {
                prod.style.display = "none";
            }
        });
    }

    // real-time qidiruv
    searchInput.addEventListener("input", (e) => {
        searchProducts(e.target.value);
    });

    // tozalash tugmasi
    clearBtn.addEventListener("click", () => {
        searchInput.value = "";
        searchProducts("");

        // highlightlarni olib tashlash
        products.forEach(prod => {
            const nameElem = prod.querySelector("h3");
            const pTags = prod.querySelectorAll("p");

            nameElem.innerHTML = nameElem.innerText;
            pTags.forEach(p => p.innerHTML = p.innerText);
        });
    });
});
