var FILTER_DATA = {
    "order": null,
    "category": null,
    "size": [],
    "brand": [],
    "color": [],
    "price": {
        "min": null,
        "max": null
    },
    "start": 0,
    "end": 24

};
window.addEventListener('load', function () {
    closeLoading();
    handleResponsiveDesign();
    if (filter_data.category !== "null") {
        FILTER_DATA.category = filter_data.category;
    }
});

function rangeControl() {
    const priceRange = document.getElementById('priceRange');
    const priceRangeDisplay = document.getElementById('priceRangeDisplay');

    noUiSlider.create(priceRange, {
        start: [0, 10000000],
        connect: true,
        range: {
            'min': 0,
            'max': 10000000
        },
        step: 1000,
        tooltips: [true, true],
        format: {
            to: function (value) {
                return Math.round(value);
            },
            from: function (value) {
                return Number(value);
            }
        }
    });

    priceRange.noUiSlider.on('update', function (values, handle) {
        FILTER_DATA["price"].min = values[0];
        FILTER_DATA["price"].max = values[1];
        priceRangeDisplay.textContent = `${formatNumber(values[1])} - ${formatNumber(values[0])}`;
    });
}

function handleResponsiveDesign() {
    var filter_content = filterContent();

    if (window.innerWidth <= 768) {
        // کد برای حالت موبایل
        document.getElementById("filter_products").addEventListener('click', function () {
            showMenu(filter_content, "فیلتر محصولات");
            rangeControl();
        });
    } else {
        // کد برای حالت دسکتاپ
        document.getElementById("side_area").innerHTML = filter_content;
        rangeControl();
    }

}


// اجرای تابع هنگام تغییر اندازه صفحه
window.addEventListener('resize', handleResponsiveDesign);

function showLoading() {
    var loadingElement = document.getElementById('loading_area');
    if (loadingElement) {
        loadingElement.classList.remove("d-none");
    }
}

function closeLoading() {
    var loadingElement = document.getElementById('loading_area');
    if (loadingElement) {
        loadingElement.classList.add("d-none");
    }
}


document.getElementById("sort_products").addEventListener('click', function () {
    let content = `
    <div class="p-2">
        <span onclick="sortProducts(this,'related')" class="clickable">مرتبط ‌ترین</span>
        <hr>
        <span onclick="sortProducts(this,'newest')" class="clickable">جدید ‌ترین</span>
        <hr>
        <span onclick="sortProducts(this,'cheapest')" class="clickable">ارزان ترین</span>
        <hr>
        <span onclick="sortProducts(this,'expensive')" class="clickable">گران ترین</span>
    </div>
    `;

    showMenu(content, "ترتیب محصولات");
});

function filterContent() {
    FILTER_DATA["start"] = 0;
    FILTER_DATA["end"] = 24;
    let brand_area = "";
    filter_data.brand.forEach(brand => {
        brand_area += `<div class="">
                <input class="form-check-input h3 p-2" type="checkbox" onclick="selectBrand(this,'${brand}')" ` + (FILTER_DATA.brand.includes(brand) ? 'checked' : "") + `>
                <span class="mx-2 ">
                    ${brand}
                </span>
            </div>`
    });
    let size_area = "";
    filter_data.size.forEach(size => {
        size_area += `<div class="">
                <input class="form-check-input h3 p-2" type="checkbox" onclick="selectSize(this,'${size}')"  ` + (FILTER_DATA.size.includes(size) ? 'checked' : "") + `>
                <label class="form-check-label mx-2" for="flexCheckChecked">
                    ${size}
                </label>
            </div>`
    });
    let color_area = "";
    filter_data.color.forEach(color => {
        color_area += `<div class="form-check mt-2">
                <button class="btn rounded-0 p-2 px-3 border-secondary border-opacity-25 ` + (FILTER_DATA.color.includes(color[1]) ? 'color-btn-active' : "") + `"
                        style="background-color: #${color[1]}"
                        onclick="selectColor(this,'${color[1]}')"></button>
                <label class="mx-2">
                    ${color[0]}
                </label>
            </div>`;
    })
    let content = `<div class="accordion rounded-0" id="accordionPanelsStayOpenExample" > 
 <button onclick="filterBtn(this)" class="btn btn-outline-dark rounded-0 mt-3 sticky-top btn-light mx-3">اعمال فیلترها</button>

  <div class="accordion-item rounded-0 border-top-0">
    <h2 class="accordion-header rounded-0" dir="ltr">
      <button class="accordion-button rounded-0 bg-white" type="button" data-bs-toggle="collapse" data-bs-target="#panelsStayOpen-collapseOne" aria-expanded="true" aria-controls="panelsStayOpen-collapseOne">
        قیمت
      </button>
    </h2>
    <div id="panelsStayOpen-collapseOne" class="accordion-collapse collapse show">
      <div class="accordion-body ">
        <div class="px-4 mt-5">
            <div id="priceRange"></div>
            <p class="mt-3">بازه قیمت: <span id="priceRangeDisplay" class="persian-number"></span> تومان</p>
        </div>
      </div>
    </div>
  </div>
  <div class="accordion-item  rounded-0">
    <h2 class="accordion-header  rounded-0"  dir="ltr">
      <button class="accordion-button collapsed  rounded-0 bg-white" type="button" data-bs-toggle="collapse" data-bs-target="#panelsStayOpen-collapseTwo" aria-expanded="false" aria-controls="panelsStayOpen-collapseTwo">
        برند
      </button>
    </h2>
    <div id="panelsStayOpen-collapseTwo" class="accordion-collapse collapse">
      <div class="accordion-body">
` + brand_area + `
      </div>
    </div>
  </div>
  <div class="accordion-item  rounded-0"  dir="ltr">
    <h2 class="accordion-header  rounded-0">
      <button class="accordion-button collapsed  rounded-0 bg-white" type="button" data-bs-toggle="collapse" data-bs-target="#panelsStayOpen-collapseThree" aria-expanded="false" aria-controls="panelsStayOpen-collapseThree">
        سایز
      </button>
    </h2>
    <div id="panelsStayOpen-collapseThree" class="accordion-collapse collapse">
      <div class="accordion-body" dir="rtl">
` + size_area + `      </div>
    </div>
  </div>
  <div class="accordion-item  rounded-0"  dir="ltr">
    <h2 class="accordion-header  rounded-0">
      <button class="accordion-button collapsed  rounded-0 bg-white" type="button" data-bs-toggle="collapse" data-bs-target="#panelsStayOpen-collapseFour" aria-expanded="false" aria-controls="panelsStayOpen-collapseThree">
        رنگ
      </button>
    </h2>
    <div id="panelsStayOpen-collapseFour" class="accordion-collapse collapse">
      <div class="accordion-body" dir="rtl">
` + color_area + `
      </div>
    </div>
  </div>
</div>`;


    return content
}


ORDERS = {
    "newest": "جدیدترین",
    "cheapest": "ارزانترین",
    "expensive": "گرانترین",
    "related": "مرتبط ترین",
}

async function sortProducts(self, order) {
    if (!self.classList.contains("disabled")) {
        self.classList.add("disabled")
        document.getElementById("sort_products").querySelector("span").innerHTML = ORDERS[order];
        FILTER_DATA["order"] = order;
        let res = await filter_api();
        if (res.status === "success") {
            document.getElementById("products_area").innerHTML = "";
            res.products.forEach(product => {
                document.getElementById("products_area").innerHTML += createProductViewCard(product);
            });
            if (res.more) {
                document.getElementById("products_area").innerHTML += "<botton onclick='moreProductBtn(this)' class='btn btn-secondary col-12 mt-3 py-1'>محصولات بیشتر</botton>";

            }
        }
        self.classList.remove("disabled")
        closeMenu();
    }
}

function createProductViewCard(product) {
    let product_view = `
    <div class="col col-6 col-md-3 mt-3">
        <a href="${product.url}">

            <div class="product-container">
                                
                <div class="badge bg-dark rounded-0 mt-2 p-2 p-md-3 fs-6 persian-number ` + (product.discount === 0 ? "d-none" : "") + `">${product.discount}٪</div>
                    <img src="${product.image}" alt="...">
                </div>
                <div class="mt-3">
                    <h6 class="fs-6 fw-lighter text-wrap">
                        <span class="product-title text-muted">${product.name}</span>
                    </h6>
                    <div class="row justify-content-between justify-content-md-end mt-2">   
                        <div class="col col-md-auto ` + (product.discount === 0 || product.stock === 0 ? "d-none" : "") + `">
                            <span class="persian-number h6 text-decoration-line-through opacity-50">${formatNumber(product.old_price)}</span>
                        </div>
                                  
                        <div class="col col-12 text-start pe-0 ` + (product.stock === 0 ? "" : "d-none") + `">
                            <span>ناموجود</span>
                        </div>
                        <div class="col col-12 text-start pe-0 ` + (product.stock === 0 ? "d-none" : "") + `">
                            <span class="persian-number h4">${formatNumber(product.price)}</span>
                            <span class="small">تومان</span>
                        </div>
                    </div>
                </div>
        </a>
    </div>`
    return product_view
}


function formatNumber(num) {
    return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,')
}

async function filter_api() {
    showLoading();
    let csrfToken = document.querySelector('[name=csrfmiddlewaretoken]').value;
    let _data = "initial";
    try {
        const response = await fetch('/product/api/filter', {
            method: 'POST', headers: {
                'Content-Type': 'application/json', 'X-CSRFToken': csrfToken
                // Include other headers as needed
            }, body: JSON.stringify(FILTER_DATA),
        });
        // تبدیل پاسخ به JSON
        _data = await response.json();
        closeLoading();
    } catch (error) {
        let alert_text = "خطای مهلکی در ارتباط با مرکز رخ داده است، اینترنت خود را بررسی یا با توسعه دهنده تماس بگیرید.";
        // show_alert(alert_text, "alert-danger");
        console.log(alert_text);
        _data = "fail";
        closeLoading();
    }
    return _data;
}

function selectColor(self, color_code) {
    if (!FILTER_DATA.color.includes(color_code)) {
        FILTER_DATA["color"].push(color_code);
        self.classList.add("color-btn-active")
    } else {
        self.classList.remove("color-btn-active")
        const index = FILTER_DATA["color"].indexOf(color_code);
        if (index > -1) {
            FILTER_DATA["color"].splice(index, 1);
        }
    }
}

function selectSize(self, size) {

    if (!FILTER_DATA.size.includes(size)) {
        FILTER_DATA["size"].push(size);
    } else {
        const index = FILTER_DATA["size"].indexOf(size);
        if (index > -1) {
            FILTER_DATA["size"].splice(index, 1);
        }
    }

}

function selectBrand(self, brand) {
    if (!FILTER_DATA.brand.includes(brand)) {
        FILTER_DATA["brand"].push(brand);
    } else {
        const index = FILTER_DATA["brand"].indexOf(brand);
        if (index > -1) {
            FILTER_DATA["brand"].splice(index, 1);
        }
    }
}

async function filterBtn(self) {

    if (!self.classList.contains("disabled")) {
        self.classList.add("disabled")
        let res = await filter_api();
        if (res.status === "success") {
            document.getElementById("products_area").innerHTML = "";
            res.products.forEach(product => {
                document.getElementById("products_area").innerHTML += createProductViewCard(product);
            });
            if (res.more) {
                document.getElementById("products_area").innerHTML += "<botton onclick='moreProductBtn(this)' class='btn btn-secondary col-12 mt-2 py-1'>محصولات بیشتر</botton>";

            }

        }
        self.classList.remove("disabled")
        closeMenu();
    }

}

async function moreProductBtn(self) {
    FILTER_DATA["start"] += 24;
    FILTER_DATA["end"] += 24;
    if (!self.classList.contains("disabled")) {
        self.classList.add("disabled")
        self.innerText = "بارگذاری محصولات بیشتر...";
        let res = await filter_api();
        if (res.status === "success") {
            let product_area = document.getElementById("products_area");
            self.remove();
            res.products.forEach(product => {
                product_area.innerHTML += createProductViewCard(product);
            });
            if (res.more) {
                product_area.innerHTML += "<botton onclick='moreProductBtn(this)' class='more_btn btn btn-secondary col-12 py-1 mt-3'>محصولات بیشتر</botton>";

            }

        }
        self.classList.remove("disabled")
        closeMenu();
    }

}

async function selectSizeBtn(self, size) {
    FILTER_DATA["start"] = 0;
    FILTER_DATA["end"] = 24;
    if (!self.classList.contains("color-btn-active")) {
        self.classList.add("disabled")
        self.classList.add("color-btn-active")
        FILTER_DATA["size"].push(size);


    } else {
        self.classList.remove("color-btn-active")
        const index = FILTER_DATA["size"].indexOf(size);
        if (index > -1) {
            FILTER_DATA["size"].splice(index, 1);
        }
    }
    res = await filter_api();
    if (res.status === "success") {
        document.getElementById("products_area").innerHTML = "";
        res.products.forEach(product => {
            document.getElementById("products_area").innerHTML += createProductViewCard(product);
        });
        if (res.more) {
            document.getElementById("products_area").innerHTML += "<botton onclick='moreProductBtn(this)' class='btn btn-secondary col-12 mt-2 py-1'>محصولات بیشتر</botton>";

        }
        closeMenu();
        self.classList.remove("disabled")
    }
}