(function () {
  'use strict';

  const CART_KEY = 'sofaStoreCart';
  const peso = new Intl.NumberFormat('en-PH', {
    style: 'currency',
    currency: 'PHP'
  });

  function getCart() {
    try {
      const parsed = JSON.parse(localStorage.getItem(CART_KEY)) || {};
      return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
    } catch (error) {
      return {};
    }
  }

  function saveCart(cart) {
    localStorage.setItem(CART_KEY, JSON.stringify(cart));
    updateCartCount();
  }

  function cartItems() {
    return Object.values(getCart()).filter((item) => item && item.id && item.qty > 0);
  }

  function escapeHtml(value) {
    return String(value)
      .replaceAll('&', '&amp;')
      .replaceAll('<', '&lt;')
      .replaceAll('>', '&gt;')
      .replaceAll('"', '&quot;')
      .replaceAll("'", '&#039;');
  }

  function showToast(message) {
    const toastEl = document.getElementById('store-toast');
    if (!toastEl || !window.bootstrap) {
      return;
    }

    const body = toastEl.querySelector('.toast-body');
    if (body) {
      body.textContent = message;
    }
    window.bootstrap.Toast.getOrCreateInstance(toastEl).show();
  }

  function updateCartCount() {
    const countEl = document.getElementById('cart-count');
    if (!countEl) {
      return;
    }

    const count = cartItems().reduce((sum, item) => sum + Number(item.qty || 0), 0);
    countEl.textContent = String(count);
  }

  function addToCart(button) {
    const qtyInput = button.dataset.qtyInput ? document.getElementById(button.dataset.qtyInput) : null;
    const requestedQty = qtyInput ? Number(qtyInput.value) : 1;
    const qty = Number.isFinite(requestedQty) && requestedQty > 0 ? Math.min(Math.floor(requestedQty), 25) : 1;

    const product = {
      id: button.dataset.id,
      name: button.dataset.name,
      price: Number(button.dataset.price),
      image: button.dataset.image,
      dimensions: button.dataset.dimensions,
      qty
    };

    if (!product.id || !product.name || Number.isNaN(product.price)) {
      showToast('Product details are incomplete.');
      return;
    }

    const cart = getCart();
    const existingQty = cart[product.id] ? Number(cart[product.id].qty || 0) : 0;
    cart[product.id] = { ...product, qty: Math.min(existingQty + product.qty, 25) };

    saveCart(cart);
    showToast(`${product.name} added to cart.`);
  }

  function setQuantity(id, qty) {
    const cart = getCart();

    if (!cart[id]) {
      return;
    }

    if (qty <= 0) {
      delete cart[id];
    } else {
      cart[id].qty = Math.min(Math.floor(qty), 25);
    }

    saveCart(cart);
    renderCartPage();
    renderCheckoutPage();
  }

  function clearCart() {
    localStorage.removeItem(CART_KEY);
    updateCartCount();
    renderCartPage();
    renderCheckoutPage();
    showToast('Cart cleared.');
  }

  function totals(items) {
    return items.reduce((summary, item) => {
      const qty = Number(item.qty || 0);
      const price = Number(item.price || 0);
      summary.qty += qty;
      summary.total += qty * price;
      return summary;
    }, { qty: 0, total: 0 });
  }

  function renderCartPage() {
    const container = document.getElementById('cart-items');
    if (!container) {
      return;
    }

    const items = cartItems();
    const summary = totals(items);
    const emptyTemplate = document.getElementById('empty-cart-template');
    const checkoutLink = document.getElementById('checkout-link');

    const summaryItems = document.getElementById('summary-items');
    const summaryTotal = document.getElementById('summary-total');

    if (summaryItems) summaryItems.textContent = String(summary.qty);
    if (summaryTotal) summaryTotal.textContent = peso.format(summary.total);
    if (checkoutLink) {
      checkoutLink.classList.toggle('disabled', items.length === 0);
      checkoutLink.setAttribute('aria-disabled', String(items.length === 0));
    }

    if (!items.length) {
      container.innerHTML = emptyTemplate ? emptyTemplate.innerHTML : '';
      return;
    }

    container.innerHTML = items.map((item) => `
      <article class="cart-item">
        <img src="${escapeHtml(item.image)}" alt="${escapeHtml(item.name)}" loading="lazy">
        <div>
          <h2>${escapeHtml(item.name)}</h2>
          <p class="muted-copy mb-2">${escapeHtml(item.dimensions || '')}</p>
          <strong>${peso.format(Number(item.price || 0))}</strong>
        </div>
        <div class="cart-item-actions">
          <div class="quantity-controls" aria-label="Quantity controls for ${escapeHtml(item.name)}">
            <button type="button" data-qty="${escapeHtml(item.id)}" data-step="-1" aria-label="Decrease quantity">-</button>
            <span>${Number(item.qty || 0)}</span>
            <button type="button" data-qty="${escapeHtml(item.id)}" data-step="1" aria-label="Increase quantity">+</button>
          </div>
          <button type="button" class="btn btn-sm btn-outline-primary mt-2" data-remove="${escapeHtml(item.id)}">
            <i class="bi bi-trash" aria-hidden="true"></i>
            Remove
          </button>
        </div>
      </article>
    `).join('');
  }

  function serverPayload(items) {
    return items.map((item) => ({
      id: item.id,
      qty: Number(item.qty || 0)
    }));
  }

  function renderCheckoutPage() {
    const container = document.getElementById('checkout-items');
    const payload = document.getElementById('order-payload');
    if (!container || !payload) {
      return;
    }

    const items = cartItems();
    const summary = totals(items);
    const submit = document.querySelector('#checkout-form button[type="submit"]');

    payload.value = JSON.stringify(serverPayload(items));

    const checkoutTotal = document.getElementById('checkout-total');
    if (checkoutTotal) checkoutTotal.textContent = peso.format(summary.total);
    if (submit) submit.disabled = items.length === 0;

    if (!items.length) {
      container.innerHTML = '<p class="muted-copy">No sofas selected yet. Please add at least one item from the catalog.</p>';
      return;
    }

    container.innerHTML = items.map((item) => `
      <div class="checkout-line">
        <div>
          <strong>${escapeHtml(item.name)}</strong>
          <p>${Number(item.qty || 0)} x ${peso.format(Number(item.price || 0))}</p>
        </div>
        <strong>${peso.format(Number(item.qty || 0) * Number(item.price || 0))}</strong>
      </div>
    `).join('');
  }

  function initCatalogFilters() {
    const grid = document.querySelector('[data-product-grid]');
    if (!grid) {
      return;
    }

    const searchInput = document.querySelector('[data-catalog-search]');
    const categorySelect = document.querySelector('[data-catalog-category]');
    const sortSelect = document.querySelector('[data-catalog-sort]');
    const countEl = document.getElementById('catalog-count');
    const emptyEl = document.getElementById('catalog-empty');
    const cards = Array.from(document.querySelectorAll('[data-product-card]'));

    function applyFilters() {
      const keyword = (searchInput ? searchInput.value : '').trim().toLowerCase();
      const category = categorySelect ? categorySelect.value : 'all';
      const sort = sortSelect ? sortSelect.value : 'featured';

      let visibleCount = 0;

      cards.forEach((card) => {
        const matchesKeyword = !keyword || (card.dataset.search || '').includes(keyword);
        const matchesCategory = category === 'all' || card.dataset.category === category;
        const visible = matchesKeyword && matchesCategory;
        card.classList.toggle('d-none', !visible);
        if (visible) visibleCount += 1;
      });

      const sortedCards = [...cards].sort((a, b) => {
        if (sort === 'price-asc') return Number(a.dataset.price) - Number(b.dataset.price);
        if (sort === 'price-desc') return Number(b.dataset.price) - Number(a.dataset.price);
        if (sort === 'rating-desc') return Number(b.dataset.rating) - Number(a.dataset.rating);
        return Number(a.dataset.index) - Number(b.dataset.index);
      });

      sortedCards.forEach((card) => grid.appendChild(card));

      if (countEl) countEl.textContent = String(visibleCount);
      if (emptyEl) emptyEl.classList.toggle('d-none', visibleCount !== 0);
    }

    [searchInput, categorySelect, sortSelect].forEach((control) => {
      if (control) control.addEventListener('input', applyFilters);
    });

    document.querySelectorAll('[data-jump-category]').forEach((link) => {
      link.addEventListener('click', () => {
        if (categorySelect) {
          categorySelect.value = link.dataset.jumpCategory || 'all';
          applyFilters();
        }
      });
    });

    applyFilters();
  }

  function initRoomFitChecker() {
    document.querySelectorAll('[data-room-fit]').forEach((widget) => {
      const sofaWidth = Number(widget.dataset.sofaWidthCm || 0);
      const sofaDepth = Number(widget.dataset.sofaDepthCm || 0);
      const clearance = Number(widget.dataset.clearanceCm || 30);
      const widthInput = widget.querySelector('[data-room-width]');
      const depthInput = widget.querySelector('[data-room-depth]');
      const result = widget.querySelector('[data-fit-result]');

      if (!sofaWidth || !sofaDepth || !widthInput || !depthInput || !result) {
        return;
      }

      function setResult(type, message) {
        result.classList.remove('neutral', 'good', 'warn', 'danger');
        result.classList.add(type);
        result.textContent = message;
      }

      function calculateFit() {
        const roomWidth = Number(widthInput.value || 0);
        const roomDepth = Number(depthInput.value || 0);
        const comfortableWidth = sofaWidth + (clearance * 2);
        const comfortableDepth = sofaDepth + (clearance * 2);

        if (!roomWidth || !roomDepth) {
          setResult('neutral', 'Enter room size to check if this sofa will fit comfortably.');
          return;
        }

        const missingFootprintWidth = Math.max(0, sofaWidth - roomWidth);
        const missingFootprintDepth = Math.max(0, sofaDepth - roomDepth);
        const missingComfortWidth = Math.max(0, comfortableWidth - roomWidth);
        const missingComfortDepth = Math.max(0, comfortableDepth - roomDepth);

        if (missingFootprintWidth === 0 && missingFootprintDepth === 0 && missingComfortWidth === 0 && missingComfortDepth === 0) {
          setResult('good', `Comfortable fit. Recommended clear space: ${comfortableWidth}cm W x ${comfortableDepth}cm D.`);
          return;
        }

        if (missingFootprintWidth === 0 && missingFootprintDepth === 0) {
          const notes = [];
          if (missingComfortWidth > 0) notes.push(`${missingComfortWidth}cm more width for ideal clearance`);
          if (missingComfortDepth > 0) notes.push(`${missingComfortDepth}cm more depth for ideal clearance`);
          setResult('warn', `Kasya ang sofa footprint, pero tight ang clearance. Need ${notes.join(' and ')}.`);
          return;
        }

        const shortage = [];
        if (missingFootprintWidth > 0) shortage.push(`${missingFootprintWidth}cm width`);
        if (missingFootprintDepth > 0) shortage.push(`${missingFootprintDepth}cm depth`);
        setResult('danger', `Hindi kasya sa entered space. Kulang ng ${shortage.join(' and ')} for the actual sofa footprint.`);
      }

      [widthInput, depthInput].forEach((input) => {
        input.addEventListener('input', calculateFit);
      });

      calculateFit();
    });
  }


  function initLiveChatWidget() {
    const widget = document.querySelector('[data-chat-widget]');
    if (!widget) {
      return;
    }

    const toggle = widget.querySelector('[data-chat-toggle]');
    const close = widget.querySelector('[data-chat-close]');

    function setOpen(isOpen) {
      widget.classList.toggle('open', isOpen);
      if (toggle) {
        toggle.setAttribute('aria-expanded', String(isOpen));
      }
    }

    if (toggle) {
      toggle.addEventListener('click', () => {
        setOpen(!widget.classList.contains('open'));
      });
    }

    if (close) {
      close.addEventListener('click', () => setOpen(false));
    }

    document.addEventListener('keydown', (event) => {
      if (event.key === 'Escape') {
        setOpen(false);
      }
    });
  }


  function initPaymentFields() {
    const paymentSelect = document.querySelector('[data-payment-method]');
    const infoCard = document.querySelector('[data-payment-info]');
    const proofPanel = document.querySelector('[data-payment-proof-panel]');

    if (!paymentSelect || !infoCard) {
      return;
    }

    const defaultInfo = infoCard.querySelector('.payment-info-default');
    const methodBlocks = Array.from(infoCard.querySelectorAll('[data-payment-copy]'));

    function updatePaymentUI() {
      const value = paymentSelect.value;
      let matched = false;

      methodBlocks.forEach((block) => {
        const isMatch = block.dataset.paymentCopy === value;
        block.classList.toggle('d-none', !isMatch);
        if (isMatch) matched = true;
      });

      if (defaultInfo) {
        defaultInfo.classList.toggle('d-none', matched);
      }

      if (proofPanel) {
        const shouldShowProof = value === 'GCash Manual' || value === 'Bank Transfer' || value === 'Downpayment Inquiry';
        proofPanel.classList.toggle('d-none', !shouldShowProof);
      }
    }

    paymentSelect.addEventListener('change', updatePaymentUI);
    updatePaymentUI();
  }

  function initInstallPrompt() {
    const widget = document.querySelector('[data-install-widget]');
    const action = document.querySelector('[data-install-action]');
    if (!widget || !action) {
      return;
    }

    let deferredPrompt = null;
    const isStandalone = () => window.matchMedia('(display-mode: standalone)').matches || window.navigator.standalone === true;

    function showWidget() {
      if (isStandalone()) {
        hideWidget();
        return;
      }
      widget.hidden = false;
      widget.classList.add('show');
    }

    function hideWidget() {
      widget.classList.remove('show');
      widget.hidden = true;
    }

    window.addEventListener('beforeinstallprompt', (event) => {
      event.preventDefault();
      deferredPrompt = event;
      showWidget();
    });

    window.addEventListener('appinstalled', () => {
      deferredPrompt = null;
      hideWidget();
      showToast('Furnify app installed.');
    });

    action.addEventListener('click', async () => {
      if (deferredPrompt) {
        deferredPrompt.prompt();
        await deferredPrompt.userChoice.catch(() => null);
        deferredPrompt = null;
        hideWidget();
        return;
      }

      const modalEl = document.getElementById('installHelpModal');
      if (modalEl && window.bootstrap) {
        window.bootstrap.Modal.getOrCreateInstance(modalEl).show();
      }
    });

    window.addEventListener('load', () => {
      if (!isStandalone()) {
        window.setTimeout(showWidget, 1400);
      }
    });
  }

  function initCheckoutValidation() {
    const checkoutForm = document.getElementById('checkout-form');
    if (!checkoutForm) {
      return;
    }

    checkoutForm.addEventListener('submit', (event) => {
      renderCheckoutPage();

      if (!cartItems().length) {
        event.preventDefault();
        showToast('Add at least one sofa before sending an inquiry.');
        return;
      }

      if (!checkoutForm.checkValidity()) {
        event.preventDefault();
        checkoutForm.classList.add('was-validated');
        showToast('Please complete the required checkout fields.');
      }
    });
  }

  document.addEventListener('click', (event) => {
    const addButton = event.target.closest('[data-add-to-cart]');
    if (addButton) {
      addToCart(addButton);
      return;
    }

    const quantityButton = event.target.closest('[data-qty]');
    if (quantityButton) {
      const id = quantityButton.dataset.qty;
      const step = Number(quantityButton.dataset.step);
      const item = getCart()[id];
      if (item) {
        setQuantity(id, Number(item.qty || 0) + step);
      }
      return;
    }

    const removeButton = event.target.closest('[data-remove]');
    if (removeButton) {
      setQuantity(removeButton.dataset.remove, 0);
      return;
    }

    if (event.target.closest('#clear-cart')) {
      clearCart();
    }
  });

  if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
      navigator.serviceWorker.register('service-worker.js').catch(() => {});
    });
  }

  updateCartCount();
  renderCartPage();
  renderCheckoutPage();
  initCatalogFilters();
  initRoomFitChecker();
  initLiveChatWidget();
  initPaymentFields();
  initInstallPrompt();
  initCheckoutValidation();
})();
