document.addEventListener('DOMContentLoaded', function () {

  // فقط صفحة مكيفات سبليت
  if (!window.location.pathname.includes('c860967106')) return;

  const capacities = [
    { size: '12', ton: '1 طن',   category: '2025230044' },
    { size: '18', ton: '1.5 طن', category: '1984293855' },
    { size: '24', ton: '2 طن',   category: '1075972824' },
    { size: '30', ton: '2.5 طن', category: '302983641' },
    { size: '36', ton: '3 طن',   category: '1876183258' }
  ];

  const productsList = document.querySelector('salla-products-list');

  if (!productsList) {
    console.log('RESON8: Products list not found');
    return;
  }

  let currentCapacityProducts = [];
  let selectedCategory = null;

  const capacityCache = new Map();

  const originalFetch = window.fetch.bind(window);


  /* =====================================================
     السعات
  ===================================================== */

  const capacitySection = document.createElement('section');
  capacitySection.className = 'reson8-capacity-selector';

  capacitySection.innerHTML = `
    <div class="reson8-capacity-title">
      اختر سعة المكيف
    </div>

    <div class="reson8-capacity-options">
      ${capacities.map(item => `
        <button
          type="button"
          class="reson8-capacity"
          data-category="${item.category}"
        >
          <span class="capacity-number">${item.size}K</span>
          <span class="capacity-ton">${item.ton}</span>
        </button>
      `).join('')}
    </div>
  `;


  /* =====================================================
     الماركات
  ===================================================== */

  const brandSection = document.createElement('section');
  brandSection.className = 'reson8-brand-selector';
  brandSection.style.display = 'none';

  brandSection.innerHTML = `
    <div class="reson8-brand-title">
      اختر الماركة
    </div>

    <div class="reson8-brand-options"></div>
  `;


  productsList.parentNode.insertBefore(
    capacitySection,
    productsList
  );

  productsList.parentNode.insertBefore(
    brandSection,
    productsList
  );


  const brandOptions =
    brandSection.querySelector('.reson8-brand-options');


  /* =====================================================
     قراءة JSON بأمان
  ===================================================== */

  async function readJSON(response) {

    try {
      return await response.clone().json();
    } catch (e) {
      return null;
    }

  }


  /* =====================================================
     استخراج next
  ===================================================== */

  function getNextUrl(result) {

    if (!result) return null;

    if (result.cursor?.next) {
      return result.cursor.next;
    }

    if (result.pagination?.links?.next) {
      return result.pagination.links.next;
    }

    if (result.links?.next) {
      return result.links.next;
    }

    return null;
  }


  /* =====================================================
     إزالة التكرار
  ===================================================== */

  function uniqueProducts(products) {

    return Array.from(
      new Map(
        products
          .filter(product => product && product.id)
          .map(product => [
            String(product.id),
            product
          ])
      ).values()
    );

  }


  /* =====================================================
     جلب باقي الصفحات بنفس Request حق سلة
  ===================================================== */

  async function loadRemainingPages(
    firstResponse,
    originalRequest,
    categoryId
  ) {

    const firstData =
      await readJSON(firstResponse);


    if (
      !firstData ||
      !Array.isArray(firstData.data)
    ) {
      return;
    }


    let allProducts = [
      ...firstData.data
    ];


    let nextUrl =
      getNextUrl(firstData);


    let pageCounter = 1;


    console.log(
      `RESON8 PAGE 1: ${firstData.data.length} products`
    );


    /*
     * نستخدم نفس Headers الخاصة بطلب سلة
     */

    let templateRequest;

    try {

      templateRequest =
        originalRequest instanceof Request
          ? originalRequest
          : new Request(originalRequest);

    } catch (e) {

      console.error(
        'RESON8 REQUEST TEMPLATE ERROR:',
        e
      );

      return;
    }


    while (
      nextUrl &&
      pageCounter < 50 &&
      selectedCategory === categoryId
    ) {

      pageCounter++;


      try {

        /*
         * نفس طلب سلة بالضبط
         * لكن نغيّر الرابط إلى cursor.next
         */

        const nextRequest =
          new Request(
            nextUrl,
            {
              method: 'GET',

              headers:
                new Headers(
                  templateRequest.headers
                ),

              credentials:
                templateRequest.credentials ||
                'same-origin',

              mode:
                templateRequest.mode ||
                'cors',

              cache:
                templateRequest.cache ||
                'default',

              redirect:
                templateRequest.redirect ||
                'follow',

              referrer:
                templateRequest.referrer,

              referrerPolicy:
                templateRequest.referrerPolicy
            }
          );


        const nextResponse =
          await originalFetch(nextRequest);


        if (!nextResponse.ok) {

          console.log(
            `RESON8 PAGE ${pageCounter}: HTTP ${nextResponse.status}`
          );

          break;
        }


        const nextData =
          await readJSON(nextResponse);


        if (
          !nextData ||
          !Array.isArray(nextData.data)
        ) {

          console.log(
            `RESON8 PAGE ${pageCounter}: invalid data`
          );

          break;
        }


        console.log(
          `RESON8 PAGE ${pageCounter}: ${nextData.data.length} products`
        );


        allProducts.push(
          ...nextData.data
        );


        nextUrl =
          getNextUrl(nextData);


      } catch (error) {

        console.error(
          `RESON8 PAGE ${pageCounter} ERROR:`,
          error
        );

        break;
      }

    }


    /*
     * لو العميل غير السعة أثناء التحميل
     * ما نعرض نتيجة السعة القديمة
     */

    if (selectedCategory !== categoryId) {
      return;
    }


    currentCapacityProducts =
      uniqueProducts(allProducts);


    capacityCache.set(
      categoryId,
      currentCapacityProducts
    );


    console.log(
      `RESON8 COMPLETE: ${categoryId} → ${currentCapacityProducts.length} products`
    );


    renderBrands(
      currentCapacityProducts
    );

  }


  /* =====================================================
     اعتراض طلب سلة الناجح
  ===================================================== */

  window.fetch = async function(input, init) {

    /*
     * نبني Request قبل إرسال الطلب
     * حتى نحتفظ بنفس Headers سلة
     */

    let request;

    try {

      request =
        input instanceof Request
          ? input.clone()
          : new Request(input, init);

    } catch (e) {

      return originalFetch(input, init);
    }


    const response =
      await originalFetch(input, init);


    try {

      const url =
        request.url || '';


      /*
       * فقط طلبات المنتجات الخاصة بالتصنيفات
       */

      if (
        selectedCategory &&
        response.ok &&
        url.includes('/store/v1/products') &&
        url.includes('source=categories')
      ) {

        const decodedURL =
          decodeURIComponent(url);


        /*
         * نتأكد أنه طلب السعة الحالية
         */

        if (
          decodedURL.includes(
            selectedCategory
          )
        ) {

          /*
           * فقط الصفحة الأولى
           * حتى ما ندخل Loop
           */

          const parsedURL =
            new URL(url);


          const page =
            parsedURL.searchParams.get('page');


          if (
            !page ||
            page === '1'
          ) {

            const categoryId =
              selectedCategory;


            /*
             * نترك طلب سلة يكمل طبيعي
             * ونشتغل على Clone بالخلفية
             */

            loadRemainingPages(
              response.clone(),
              request,
              categoryId
            );

          }

        }

      }

    } catch (error) {

      console.error(
        'RESON8 INTERCEPT ERROR:',
        error
      );

    }


    return response;

  };


  /* =====================================================
     بناء الماركات
  ===================================================== */

  function renderBrands(products) {

    brandOptions.innerHTML = '';


    const brandsMap =
      new Map();


    products.forEach(product => {

      if (
        product.brand &&
        product.brand.id &&
        product.brand.name
      ) {

        const id =
          String(product.brand.id);


        if (!brandsMap.has(id)) {

          brandsMap.set(
            id,
            {
              id: id,
              name: product.brand.name
            }
          );

        }

      }

    });


    const brands =
      Array.from(
        brandsMap.values()
      );


    brands.sort((a, b) =>
      a.name.localeCompare(
        b.name,
        'ar'
      )
    );


    console.log(
      `RESON8 BRANDS: ${brands.length}`,
      brands
    );


    if (!brands.length) {

      brandSection.style.display =
        'none';

      return;
    }


    brandOptions.innerHTML =
      brands.map(brand => `

        <button
          type="button"
          class="reson8-brand"
          data-brand="${brand.id}"
        >
          ${brand.name}
        </button>

      `).join('');


    brandSection.style.display =
      'block';


    /* =================================================
       الضغط على الماركة
    ================================================= */

    brandOptions
      .querySelectorAll(
        '.reson8-brand'
      )
      .forEach(button => {

        button.addEventListener(
          'click',
          async function () {

            const brandId =
              String(
                this.dataset.brand
              );


            brandOptions
              .querySelectorAll(
                '.reson8-brand'
              )
              .forEach(btn => {

                btn.classList.remove(
                  'active'
                );

              });


            this.classList.add(
              'active'
            );


            /*
             * فلترة كل منتجات السعة
             */

            const brandProducts =
              currentCapacityProducts
                .filter(product => {

                  return (
                    product.brand &&
                    String(
                      product.brand.id
                    ) === brandId
                  );

                });


            const productIds =
              brandProducts
                .map(product =>
                  String(product.id)
                )
                .filter(Boolean);


            console.log(
              `RESON8 BRAND ${brandId}: ${productIds.length} products`
            );


            if (!productIds.length) {
              return;
            }


            /*
             * عرض المنتجات
             */

            productsList.setAttribute(
              'source',
              'selected'
            );


            productsList.setAttribute(
              'source-value',
              JSON.stringify(
                productIds
              )
            );


            if (
              typeof productsList.reload ===
              'function'
            ) {

              await productsList.reload();

            }


            productsList.scrollIntoView({
              behavior: 'smooth',
              block: 'start'
            });

          }

        );

      });

  }


  /* =====================================================
     الضغط على السعة
  ===================================================== */

  capacitySection
    .querySelectorAll(
      '.reson8-capacity'
    )
    .forEach(button => {

      button.addEventListener(
        'click',
        async function () {

          const categoryId =
            String(
              this.dataset.category
            );


          selectedCategory =
            categoryId;


          /*
           * Active
           */

          capacitySection
            .querySelectorAll(
              '.reson8-capacity'
            )
            .forEach(btn => {

              btn.classList.remove(
                'active'
              );

            });


          this.classList.add(
            'active'
          );


          /*
           * تنظيف الماركات القديمة
           */

          brandSection.style.display =
            'none';

          brandOptions.innerHTML =
            '';


          /*
           * إذا سبق وحملنا السعة
           */

          if (
            capacityCache.has(
              categoryId
            )
          ) {

            currentCapacityProducts =
              capacityCache.get(
                categoryId
              );


            renderBrands(
              currentCapacityProducts
            );

          }


          /*
           * نطلب السعة من مكوّن سلة نفسه
           */

          productsList.setAttribute(
            'source',
            'categories'
          );


          productsList.setAttribute(
            'source-value',
            JSON.stringify([
              categoryId
            ])
          );


          try {

            if (
              typeof productsList.reload ===
              'function'
            ) {

              await productsList.reload();

            }

          } catch (error) {

            console.error(
              'RESON8 CAPACITY ERROR:',
              error
            );

          }

        }

      );

    });

});