(() => {
  const ignoredMessages = [
    'Did not receive CSRF token',
    "Cannot read properties of undefined (reading 'f_sku_values_3dr')",
  ];

  window.addEventListener('unhandledrejection', event => {
    const message = event.reason && (event.reason.message || String(event.reason));
    if (ignoredMessages.some(text => message && message.includes(text))) {
      event.preventDefault();
    }
  });

  async function getBoxes() {
    try {
      const response = await fetch('/api/boxes');
      const data = await response.json();
      return data && data.success && Array.isArray(data.boxes) ? data.boxes : [];
    } catch (error) {
      console.error('Could not load box data:', error);
      return [];
    }
  }

  function cleanPublicNavigation() {
    document.querySelectorAll('a[href="admin.html"], a[href="login.html"]').forEach(link => link.remove());
    document.querySelectorAll('.auth-link, .w-commerce-commercecartwrapper').forEach(element => element.remove());
  }

  function updatePublicCopy(isOrderPage) {
    const header = document.querySelector('.header-h1');
    if (header && isOrderPage) {
      header.innerHTML = 'Browse our <span class="brand-span">box catalog</span> and request the right packaging for your products.';
    }

    const titleWrap = document.querySelector('.content-section .title-wrap-centre');
    if (titleWrap) {
      const title = titleWrap.querySelector('h2');
      const text = titleWrap.querySelector('p');
      if (title) {
        title.textContent = isOrderPage ? 'Available Boxes' : 'Featured Boxes';
      }
      if (text) {
        text.textContent = isOrderPage
          ? 'All box cards below are loaded from backend/data/boxes.json, so prices, pictures, and descriptions can be updated in one place.'
          : 'Your featured box cards on this page are also loaded from the backend box data file.';
      }
    }
  }

  function applyBoxDataToItems(items, boxes) {
    items.forEach((item, index) => {
      const box = boxes[index] || {};
      const title = item.querySelector('h6');
      const price = item.querySelector('.price');
      const description = item.querySelector('.paragraph');
      const imageWrap = item.querySelector('.food-image-square');
      const image = item.querySelector('.food-image');
      const addToCart = item.querySelector('.add-to-cart');

      if (title) title.textContent = box.name || `Box ${index + 1}`;
      if (price) price.textContent = `$${Number(box.price || 0).toFixed(2)}`;
      if (description) description.textContent = box.description || 'Update this description in backend/data/boxes.json.';

      if (imageWrap && image && box.image) {
        image.src = box.image;
        image.alt = box.name || `Box ${index + 1}`;
        imageWrap.removeAttribute('href');
      }

      item.querySelectorAll('a[href]').forEach(link => link.removeAttribute('href'));
      item.querySelectorAll('.quantity, .w-commerce-commerceaddtocarterror, .w-commerce-commerceaddtocartoutofstock').forEach(el => el.remove());

      if (addToCart) {
        addToCart.innerHTML = '<div class="button button-space" style="display:inline-block;">Update in Box Editor</div>';
      }
    });
  }

  async function simplifyMenuBoxes() {
    const path = window.location.pathname;
    const isMainPage = path === '/' || path.endsWith('/index.html');
    const isOrderPage = path.endsWith('/order.html');
    if (!isMainPage && !isOrderPage) return;

    const boxes = await getBoxes();
    if (!boxes.length) return;

    cleanPublicNavigation();
    updatePublicCopy(isOrderPage);

    const tabs = document.querySelector('.w-tabs');
    if (!tabs) return;

    const tabMenu = tabs.querySelector('.tab-menu-round');
    if (tabMenu) tabMenu.remove();

    const firstPane = tabs.querySelector('.w-tab-pane');
    const firstList = firstPane && firstPane.querySelector('.w-dyn-items');
    if (!firstPane || !firstList) return;

    tabs.querySelectorAll('.w-tab-pane').forEach((pane, index) => {
      if (index === 0) {
        pane.classList.add('w--tab-active');
        pane.style.display = 'block';
      } else {
        pane.remove();
      }
    });

    const itemTemplate = Array.from(firstList.querySelectorAll('.menu-item'));
    const limit = isOrderPage ? 8 : 4;
    const selectedBoxes = boxes.slice(0, limit);
    const template = itemTemplate[0];
    if (!template) return;

    firstList.innerHTML = '';
    selectedBoxes.forEach((box, index) => {
      const clone = template.cloneNode(true);
      applyBoxDataToItems([clone], [box]);
      firstList.appendChild(clone);
    });

    firstPane.querySelectorAll('.pagination').forEach(element => element.remove());
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
      cleanPublicNavigation();
      simplifyMenuBoxes();
    });
  } else {
    cleanPublicNavigation();
    simplifyMenuBoxes();
  }
})();
