  <?php
  $cart_label = get_theme_mod('fjord_cart_label', 'Cart');
  $footer_bg = get_theme_mod('fjord_footer_background_color', '#f6f6f6');
  $footer_text_color = get_theme_mod('fjord_footer_text_color', '#ffffff');
  $footer_logo_image_enabled = get_theme_mod('fjord_footer_logo_image_enabled', 0);
  $footer_logo_image = get_theme_mod('fjord_footer_logo_image');
  $footer_logo_image_width = (int) get_theme_mod('fjord_footer_logo_image_width', 150);
  $footer_logo_image_style = $footer_logo_image_width > 0
    ? ' style="width: ' . esc_attr($footer_logo_image_width) . 'px;"'
    : '';
  $footer_brand_description = get_theme_mod('fjord_footer_brand_description', 'Scandinavian furniture, meticulously handcrafted to bring warmth and elegance into your home.');
  $footer_brand_background = get_theme_mod('fjord_footer_brand_background_color', '#0f1012');
  $footer_brand_text_color = get_theme_mod('fjord_footer_brand_text_color', '#ffffff');
  $footer_newsletter_background = get_theme_mod('fjord_footer_newsletter_background_color', '#121314');
  $footer_newsletter_text_color = get_theme_mod('fjord_footer_newsletter_text_color', '#ffffff');
  $footer_newsletter_button_bg = get_theme_mod('fjord_footer_newsletter_button_background', '#ffffff');
  $footer_newsletter_button_text_color = get_theme_mod('fjord_footer_newsletter_button_text_color', '#0e1011');
  $footer_pages_title = get_theme_mod('fjord_footer_pages_section_title', 'Pages');
  $footer_shop_title = get_theme_mod('fjord_footer_shop_section_title', 'Shop');
  $footer_customer_title = get_theme_mod('fjord_footer_customer_section_title', 'Customer Service');
  $footer_meta_text = get_theme_mod('fjord_footer_meta_text', 'Web diseñada por Estudio Páchel');
  $footer_meta_link = get_theme_mod('fjord_footer_meta_link', 'https://estudiopachel.com');
  $footer_pages_menu = get_theme_mod('fjord_footer_pages_menu');
  $footer_shop_menu = get_theme_mod('fjord_footer_shop_menu');
  $footer_customer_menu = get_theme_mod('fjord_footer_customer_menu');
  $footer_newsletter_enabled = (bool) get_theme_mod('fjord_footer_newsletter_enabled', 1);
  $footer_legacy_menu = get_theme_mod('fjord_footer_menu');
  $menu_locations = get_nav_menu_locations();
  $newsletter_form_style = ' style="--fjord-footer-newsletter-button-bg:' . esc_attr($footer_newsletter_button_bg) . ';--fjord-footer-newsletter-button-color:' . esc_attr($footer_newsletter_button_text_color) . ';"';
  $footer_style_attr = ' style="background: ' . esc_attr($footer_bg) . '; color: ' . esc_attr($footer_text_color) . ';"';
  $brand_panel_style = ' style="background: ' . esc_attr($footer_brand_background) . '; color: ' . esc_attr($footer_brand_text_color) . ';"';
  $newsletter_panel_style = ' style="background: ' . esc_attr($footer_newsletter_background) . '; color: ' . esc_attr($footer_newsletter_text_color) . ';"';

  $resolve_footer_menu = static function ($manual_menu, $location_key) use ($menu_locations, $footer_legacy_menu) {
    $manual_menu = (int) $manual_menu;
    if ($manual_menu > 0) {
      return ['menu' => $manual_menu];
    }

    $location_menu = isset($menu_locations[$location_key]) ? (int) $menu_locations[$location_key] : 0;
    if ($location_menu > 0) {
      return ['menu' => $location_menu];
    }

    $legacy_menu = (int) $footer_legacy_menu;
    if ($legacy_menu > 0) {
      return ['menu' => $legacy_menu];
    }

    return [];
  };

  $footer_pages_menu_location = $resolve_footer_menu($footer_pages_menu, 'footer_pages');
  $footer_shop_menu_location = $resolve_footer_menu($footer_shop_menu, 'footer_shop');
  $footer_customer_menu_location = $resolve_footer_menu($footer_customer_menu, 'footer_customer');
  $footer_has_link_columns = $footer_pages_menu_location || $footer_shop_menu_location || $footer_customer_menu_location;
  ?>
  <footer class="fjord-footer fjord-reveal<?php echo $footer_newsletter_enabled ? '' : ' fjord-footer--newsletter-hidden'; ?>"<?php echo $footer_style_attr; ?>>
    <div class="fjord-footer__grid">
      <div class="fjord-footer__panel fjord-footer__panel--left"<?php echo $brand_panel_style; ?>>
        <div class="fjord-footer__brand">
          <div class="fjord-footer__logo">
            <?php if ($footer_logo_image_enabled && $footer_logo_image) : ?>
              <img src="<?php echo esc_url($footer_logo_image); ?>" alt="<?php echo esc_attr(get_bloginfo('name')); ?> logo" class="fjord-footer__logo-image"<?php echo $footer_logo_image_style; ?>>
            <?php else : ?>
              <?php echo esc_html(get_theme_mod('fjord_footer_logo_text', 'Estudio Páchel')); ?>
            <?php endif; ?>
          </div>
          <p><?php echo esc_html($footer_brand_description); ?></p>
        </div>
        <?php if ($footer_has_link_columns) : ?>
          <div class="fjord-footer__links-grid">
            <?php if ($footer_pages_menu_location) : ?>
              <div class="fjord-footer__links">
                <h4><?php echo esc_html($footer_pages_title); ?></h4>
                <?php
                wp_nav_menu(array_merge([
                  'container' => false,
                  'items_wrap' => '<ul class="fjord-footer__menu">%3$s</ul>',
                  'depth' => 1,
                  'fallback_cb' => false,
                ], $footer_pages_menu_location));
                ?>
              </div>
            <?php endif; ?>
            <?php if ($footer_shop_menu_location) : ?>
              <div class="fjord-footer__links">
                <h4><?php echo esc_html($footer_shop_title); ?></h4>
                <?php
                wp_nav_menu(array_merge([
                  'container' => false,
                  'items_wrap' => '<ul class="fjord-footer__menu">%3$s</ul>',
                  'depth' => 1,
                  'fallback_cb' => false,
                ], $footer_shop_menu_location));
                ?>
              </div>
            <?php endif; ?>
            <?php if ($footer_customer_menu_location) : ?>
              <div class="fjord-footer__links">
                <h4><?php echo esc_html($footer_customer_title); ?></h4>
                <?php
                wp_nav_menu(array_merge([
                  'container' => false,
                  'items_wrap' => '<ul class="fjord-footer__menu">%3$s</ul>',
                  'depth' => 1,
                  'fallback_cb' => false,
                ], $footer_customer_menu_location));
                ?>
              </div>
            <?php endif; ?>
          </div>
        <?php endif; ?>
        <div class="fjord-footer__meta">
          <?php if ($footer_meta_link) : ?>
            <a href="<?php echo esc_url($footer_meta_link); ?>" target="_blank" rel="noopener noreferrer"><?php echo esc_html($footer_meta_text); ?></a>
          <?php else : ?>
            <?php echo esc_html($footer_meta_text); ?>
          <?php endif; ?>
        </div>
      </div>
      <?php if ($footer_newsletter_enabled) : ?>
        <div class="fjord-footer__panel fjord-footer__panel--right"<?php echo $newsletter_panel_style; ?>>
          <h3><?php echo esc_html(get_theme_mod('fjord_footer_newsletter_title', 'Join our newsletter and get 20% off your first purchase')); ?></h3>
          <?php if (get_theme_mod('fjord_footer_newsletter_form_enabled', 1)) : ?>
            <div class="fjord-footer__form"<?php echo $newsletter_form_style; ?>>
              <?php
              $newsletter_shortcode = get_theme_mod('fjord_footer_newsletter_shortcode', '[contact-form-7 id="3b78303" title="Newsletter"]');
              if (!empty($newsletter_shortcode)) {
                echo do_shortcode($newsletter_shortcode);
              }
              ?>
            </div>
          <?php endif; ?>
        </div>
      <?php endif; ?>
    </div>
  </footer>

  <?php
  $fjord_cart_count = function_exists('WC') && WC()->cart ? WC()->cart->get_cart_contents_count() : 0;
  $fjord_cart_nonce = wp_create_nonce('fjord-cart');
  ?>
  <div class="fjord-cart-drawer" data-cart-drawer aria-hidden="true">
    <div class="fjord-cart-drawer__overlay" data-cart-drawer-close></div>
    <aside class="fjord-cart-drawer__panel" role="dialog" aria-modal="true" aria-label="<?php echo esc_attr($cart_label); ?>">
      <div class="fjord-cart-drawer__header">
        <span class="fjord-cart-drawer__title"><?php echo esc_html($cart_label); ?> <span data-cart-count>(<?php echo esc_html($fjord_cart_count); ?>)</span></span>
        <button class="fjord-cart-drawer__close" type="button" data-cart-drawer-close aria-label="Cerrar">×</button>
      </div>
      <div class="fjord-cart-drawer__content">
        <?php if (function_exists('woocommerce_mini_cart')) : ?>
          <?php woocommerce_mini_cart(); ?>
        <?php endif; ?>
      </div>
    </aside>
  </div>

<?php wp_footer(); ?>
  <script>
    (() => {
      const cartAjaxUrl = <?php echo wp_json_encode(admin_url('admin-ajax.php')); ?>;
      const cartNonce = <?php echo wp_json_encode($fjord_cart_nonce); ?>;
      const collapseEmptyNewsletterPanel = () => {
        const footer = document.querySelector(".fjord-footer");
        const newsletterPanel = footer?.querySelector(".fjord-footer__panel--right");
        if (!footer || !newsletterPanel) return;
        if (newsletterPanel.textContent.trim() !== "") return;
        newsletterPanel.remove();
        footer.classList.add("fjord-footer--newsletter-hidden");
      };
      const setHeaderHeightVar = () => {
        const header = document.querySelector(".fjord-header");
        const topbar = document.querySelector(".fjord-topbar");
        if (!header) return;
        document.documentElement.style.setProperty(
          "--fjord-header-height",
          `${header.offsetHeight}px`
        );
        document.documentElement.style.setProperty(
          "--fjord-topbar-height",
          `${topbar ? topbar.offsetHeight : 0}px`
        );
      };

      const setViewportHeightVar = () => {
        document.documentElement.style.setProperty(
          "--fjord-viewport-height",
          `${window.innerHeight}px`
        );
      };

      collapseEmptyNewsletterPanel();
      setHeaderHeightVar();
      setViewportHeightVar();
      window.addEventListener("resize", () => {
        requestAnimationFrame(setHeaderHeightVar);
        requestAnimationFrame(setViewportHeightVar);
      });

      requestAnimationFrame(() => {
        document.body.classList.add("fjord-page-enter");
      });

      const drawer = document.querySelector("[data-cart-drawer]");
      const drawerContent = drawer?.querySelector(".fjord-cart-drawer__content");
      const filterDrawer = document.querySelector("[data-filter-drawer]");
      const updateCartCount = () => {
        const count = drawer?.querySelectorAll(".woocommerce-mini-cart-item").length || 0;
        document.querySelectorAll("[data-cart-count]").forEach((el) => {
          el.textContent = `(${count})`;
        });
      };
      const openDrawer = () => {
        if (!drawer) return;
        drawer.classList.add("is-open");
        drawer.setAttribute("aria-hidden", "false");
        document.body.classList.add("cart-drawer-open");
        updateCartCount();
      };
      const closeDrawer = () => {
        if (!drawer) return;
        drawer.classList.remove("is-open");
        drawer.setAttribute("aria-hidden", "true");
        document.body.classList.remove("cart-drawer-open");
      };
      const openFilter = () => {
        if (!filterDrawer) return;
        filterDrawer.classList.add("is-open");
        filterDrawer.setAttribute("aria-hidden", "false");
        document.body.classList.add("filter-drawer-open");
      };
      const closeFilter = () => {
        if (!filterDrawer) return;
        filterDrawer.classList.remove("is-open");
        filterDrawer.setAttribute("aria-hidden", "true");
        document.body.classList.remove("filter-drawer-open");
      };

      document.querySelectorAll("[data-cart-drawer-open]").forEach((trigger) => {
        trigger.addEventListener("click", (event) => {
          event.preventDefault();
          openDrawer();
        });
      });

      drawer?.querySelectorAll("[data-cart-drawer-close]").forEach((trigger) => {
        trigger.addEventListener("click", closeDrawer);
      });

      document.querySelectorAll("[data-filter-drawer-open]").forEach((trigger) => {
        trigger.addEventListener("click", (event) => {
          event.preventDefault();
          openFilter();
        });
      });

      filterDrawer?.querySelectorAll("[data-filter-drawer-close]").forEach((trigger) => {
        trigger.addEventListener("click", closeFilter);
      });

      const formatPriceRange = (value, currency, decimals) => {
        const amount = Number(value || 0);
        try {
          const formatter = new Intl.NumberFormat(document.documentElement.lang || "es-ES", {
            minimumFractionDigits: decimals,
            maximumFractionDigits: decimals,
          });
          return `${currency} ${formatter.format(amount)}`;
        } catch (error) {
          return `${currency} ${amount}`;
        }
      };

      const syncPriceRange = (wrapper) => {
        const ranges = wrapper.querySelectorAll('input[type="range"]');
        const minRange = ranges[0];
        const maxRange = ranges[1];
        if (!minRange || !maxRange) return;
        const minInput = wrapper.closest("form")?.querySelector('input[name="min_price"]');
        const maxInput = wrapper.closest("form")?.querySelector('input[name="max_price"]');
        const output = wrapper.querySelector("[data-price-output]");
        const currency = wrapper.dataset.currency || "$";
        const decimals = Number(wrapper.dataset.decimals || 0);

        const applyValues = () => {
          let minValue = Number(minRange.value || 0);
          let maxValue = Number(maxRange.value || 0);
          if (minValue > maxValue) {
            [minValue, maxValue] = [maxValue, minValue];
          }
          if (minInput) minInput.value = minValue || "";
          if (maxInput) maxInput.value = maxValue || "";
          if (output) {
            output.textContent = `${formatPriceRange(minValue, currency, decimals)} — ${formatPriceRange(maxValue, currency, decimals)}`;
          }
        };

        minRange.addEventListener("input", applyValues);
        maxRange.addEventListener("input", applyValues);

        if (minInput) {
          minInput.addEventListener("change", () => {
            const value = Number(minInput.value || 0);
            minRange.value = value;
            applyValues();
          });
        }
        if (maxInput) {
          maxInput.addEventListener("change", () => {
            const value = Number(maxInput.value || 0);
            maxRange.value = value;
            applyValues();
          });
        }

        applyValues();
      };

      document.querySelectorAll("[data-price-range]").forEach(syncPriceRange);

      document.addEventListener("keydown", (event) => {
        if (event.key === "Escape") {
          closeDrawer();
          closeFilter();
        }
      });

      document.addEventListener("click", (event) => {
        const target = event.target;
        if (!(target instanceof Element)) return;
        if (target.closest(".single_add_to_cart_button") || target.closest(".add_to_cart_button")) {
          openDrawer();
        }
      });

      if (window.jQuery) {
        window.jQuery(document.body).on("added_to_cart wc_fragments_refreshed", (event, fragments) => {
          if (drawerContent && fragments && fragments["div.widget_shopping_cart_content"]) {
            drawerContent.innerHTML = fragments["div.widget_shopping_cart_content"];
          }
          updateCartCount();
          openDrawer();
        });
      }

      document.querySelectorAll("[data-shop-filters]").forEach((filters) => {
        const button = filters.querySelector("[data-shop-filters-next]");
        if (!button) return;
        button.addEventListener("click", () => {
          const items = Array.from(filters.querySelectorAll(".fjord-shop__filter"));
          const current = items.find((item) => item.getBoundingClientRect().left >= filters.getBoundingClientRect().left - 4);
          const next = current ? items[items.indexOf(current) + 1] : items[1];
          if (next) {
            next.scrollIntoView({ behavior: "smooth", inline: "start", block: "nearest" });
          } else {
            filters.scrollTo({ left: 0, behavior: "smooth" });
          }
        });
      });

      const shopGrid = document.querySelector("[data-shop-grid]");
      const loadButton = document.querySelector("[data-shop-load]");
      if (shopGrid && loadButton) {
        const queryVars = shopGrid.dataset.shopQuery || "{}";
        let currentPage = parseInt(shopGrid.dataset.shopPage || "1", 10);
        let maxPages = parseInt(shopGrid.dataset.shopMax || "1", 10);
        let isLoading = false;

        const updateButton = () => {
          if (currentPage >= maxPages) {
            loadButton.classList.add("is-hidden");
          } else {
            loadButton.classList.remove("is-hidden");
          }
        };

        const loadMore = () => {
          if (isLoading || currentPage >= maxPages) return;
          isLoading = true;
          loadButton.classList.add("is-loading");
          const nextPage = currentPage + 1;

          fetch(cartAjaxUrl, {
            method: "POST",
            headers: { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" },
            body: new URLSearchParams({
              action: "fjord_load_more_products",
              page: String(nextPage),
              query_vars: queryVars,
            }),
          })
            .then((response) => response.json())
            .then((data) => {
              if (data && data.success && data.data && data.data.html) {
                shopGrid.insertAdjacentHTML("beforeend", data.data.html);
                currentPage = nextPage;
                maxPages = parseInt(data.data.max || maxPages, 10);
              }
            })
            .finally(() => {
              isLoading = false;
              loadButton.classList.remove("is-loading");
              updateButton();
            });
        };

        loadButton.addEventListener("click", loadMore);

        if ("IntersectionObserver" in window) {
          const observer = new IntersectionObserver(
            (entries) => {
              entries.forEach((entry) => {
                if (entry.isIntersecting) {
                  loadMore();
                }
              });
            },
            { rootMargin: "120px" }
          );
          observer.observe(loadButton);
        }

        updateButton();
      }

      const updateMiniCart = (payload) => {
        if (!payload) return;
        const html = payload.fragments?.["div.widget_shopping_cart_content"];
        if (drawerContent && html) {
          drawerContent.innerHTML = html;
        }
        if (typeof payload.count === "number") {
          document.querySelectorAll("[data-cart-count]").forEach((el) => {
            el.textContent = `(${payload.count})`;
          });
        } else {
          updateCartCount();
        }
      };

      document.addEventListener("click", (event) => {
        const target = event.target;
        if (!(target instanceof Element)) return;

        const removeButton = target.closest(".fjord-cart-drawer .remove_from_cart_button");
        if (removeButton) {
          event.preventDefault();
          const key = removeButton.getAttribute("data-cart_item_key");
          if (!key) return;
          fetch(cartAjaxUrl, {
            method: "POST",
            headers: { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" },
            body: new URLSearchParams({
              action: "fjord_update_cart_item",
              cart_item_key: key,
              quantity: "0",
              nonce: cartNonce,
            }),
          })
            .then((response) => response.json())
            .then((data) => {
              if (data && data.success) {
                updateMiniCart(data.data);
                openDrawer();
              }
            });
          return;
        }

        const qtyButton = target.closest("[data-cart-qty-change]");
        if (!qtyButton) return;
        const qtyWrap = qtyButton.closest("[data-cart-qty]");
        if (!qtyWrap) return;
        event.preventDefault();
        const key = qtyWrap.getAttribute("data-cart-key");
        const valueEl = qtyWrap.querySelector("[data-cart-qty-value]");
        const current = valueEl ? parseInt(valueEl.textContent || "0", 10) : 0;
        const delta = parseInt(qtyButton.getAttribute("data-cart-qty-change") || "0", 10);
        if (!key || !delta) return;
        const next = Math.max(0, current + delta);

        fetch(cartAjaxUrl, {
          method: "POST",
          headers: { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" },
          body: new URLSearchParams({
            action: "fjord_update_cart_item",
            cart_item_key: key,
            quantity: String(next),
            nonce: cartNonce,
          }),
        })
          .then((response) => response.json())
          .then((data) => {
            if (data && data.success) {
              updateMiniCart(data.data);
              openDrawer();
            }
          });
      });

      const params = new URLSearchParams(window.location.search);
      const hasAddParam = params.has("add-to-cart") || params.has("added-to-cart");
      const hasDrawerParam = params.has("fjord-cart");
      if (hasAddParam || hasDrawerParam) {
        openDrawer();
      }
      if (hasAddParam || hasDrawerParam) {
        params.delete("add-to-cart");
        params.delete("added-to-cart");
        params.delete("fjord-cart");
        const cleanUrl =
          window.location.pathname + (params.toString() ? `?${params}` : "");
        window.history.replaceState({}, "", cleanUrl);
      }

      const hotspots = document.querySelectorAll(".fjord-hotspot");
      if (hotspots.length) {
        const closeAll = () => hotspots.forEach((spot) => spot.classList.remove("is-active"));
        hotspots.forEach((spot) => {
          spot.addEventListener("click", (event) => {
            event.stopPropagation();
            const isActive = spot.classList.contains("is-active");
            closeAll();
            if (!isActive) spot.classList.add("is-active");
          });
        });
        document.addEventListener("click", closeAll);
      }

        const slider = document.querySelector("[data-hero-slider]");
        if (slider) {
          const slides = Array.from(slider.querySelectorAll(".fjord-hero__slide"));
          const prev = slider.querySelector(".fjord-hero__control--prev");
          const next = slider.querySelector(".fjord-hero__control--next");
          const dotsContainer = slider.querySelector("[data-hero-dots]");
          const dots = dotsContainer ? Array.from(dotsContainer.querySelectorAll("[data-hero-dot-index]")) : [];
          let index = 0;
          let timer;
          const autoplay = slider.dataset.autoplay !== "false";
          const autoplaySpeed = Math.max(2000, parseInt(slider.dataset.autoplaySpeed, 10) || 7000);
        const media = window.matchMedia("(max-width: 768px)");
        let touchStartX = 0;
        let touchStartY = 0;

        const goTo = (newIndex) => {
          slides[index].classList.remove("is-active");
          if (dots[index]) {
            dots[index].classList.remove("is-active");
          }
          index = (newIndex + slides.length) % slides.length;
          slides[index].classList.add("is-active");
          if (dots[index]) {
            dots[index].classList.add("is-active");
          }
        };

        const start = () => {
          if (!autoplay || media.matches || slides.length < 2) return;
          timer = setInterval(() => goTo(index + 1), autoplaySpeed);
        };

        const reset = () => {
          clearInterval(timer);
          start();
        };

        prev?.addEventListener("click", () => {
          goTo(index - 1);
          reset();
        });

        next?.addEventListener("click", () => {
          goTo(index + 1);
          reset();
        });

        if (dots.length) {
          dots.forEach((dot, dotIndex) => {
            dot.addEventListener("click", () => {
              goTo(dotIndex);
              reset();
            });
          });
        }

        slider.addEventListener(
          "touchstart",
          (event) => {
            const touch = event.touches[0];
            touchStartX = touch.clientX;
            touchStartY = touch.clientY;
          },
          { passive: true }
        );

        slider.addEventListener(
          "touchend",
          (event) => {
            const touch = event.changedTouches[0];
            const deltaX = touch.clientX - touchStartX;
            const deltaY = touch.clientY - touchStartY;
            if (Math.abs(deltaX) < 40 || Math.abs(deltaX) < Math.abs(deltaY)) return;
            if (deltaX > 0) {
              goTo(index - 1);
            } else {
              goTo(index + 1);
            }
          },
          { passive: true }
        );

        media.addEventListener("change", () => {
          clearInterval(timer);
          start();
        });

        start();
      }

      const carousels = document.querySelectorAll("[data-carousel]");
      carousels.forEach((carousel) => {
        const track = carousel.querySelector(".fjord-carousel__track");
        const prev = carousel.querySelector(".fjord-carousel__control--prev");
        const next = carousel.querySelector(".fjord-carousel__control--next");
        if (!track) return;
        const cards = Array.from(track.querySelectorAll(".fjord-product"));

        const getStep = () => {
          const card = track.querySelector(".fjord-product");
          if (!card) return 300;
          const gap = parseFloat(getComputedStyle(track).columnGap || getComputedStyle(track).gap || 0);
          return card.getBoundingClientRect().width + gap;
        };

        const updateButtons = () => {
          if (!prev || !next) return;
          const maxScroll = track.scrollWidth - track.clientWidth - 1;
          prev.classList.toggle("is-hidden", track.scrollLeft <= 0);
          next.classList.toggle("is-hidden", track.scrollLeft >= maxScroll);
        };

        const dots = document.createElement("div");
        dots.className = "fjord-carousel__dots";
        const dotButtons = cards.map((_, index) => {
          const dot = document.createElement("button");
          dot.type = "button";
          dot.className = "fjord-carousel__dot";
          dot.addEventListener("click", () => {
            track.scrollTo({ left: index * getStep(), behavior: "smooth" });
            updateDots();
          });
          dots.appendChild(dot);
          return dot;
        });

        const updateDots = () => {
          if (!dotButtons.length) return;
          const step = getStep();
          const index = step ? Math.round(track.scrollLeft / step) : 0;
          dotButtons.forEach((dot, i) => dot.classList.toggle("is-active", i === index));
        };

        if (cards.length > 1) {
          carousel.appendChild(dots);
        }

        prev?.addEventListener("click", () => {
          track.scrollBy({ left: -getStep(), behavior: "smooth" });
          requestAnimationFrame(updateButtons);
        });

        next?.addEventListener("click", () => {
          track.scrollBy({ left: getStep(), behavior: "smooth" });
          requestAnimationFrame(updateButtons);
        });

        track.addEventListener("scroll", () => {
          requestAnimationFrame(updateButtons);
          requestAnimationFrame(updateDots);
        });

        updateButtons();
        updateDots();
      });

      const productThumbGroups = document.querySelectorAll("[data-product-thumbs]");
      productThumbGroups.forEach((group) => {
        const thumbs = Array.from(group.querySelectorAll("[data-product-thumb-target]"));
        if (!thumbs.length) return;
        const targets = thumbs
          .map((thumb) => document.getElementById(thumb.dataset.productThumbTarget || ""))
          .filter(Boolean);

        const setActiveThumb = (targetId) => {
          thumbs.forEach((thumb) => {
            thumb.classList.toggle("is-active", thumb.dataset.productThumbTarget === targetId);
          });
        };

        thumbs.forEach((thumb) => {
          thumb.addEventListener("click", () => {
            const targetId = thumb.dataset.productThumbTarget;
            const target = targetId ? document.getElementById(targetId) : null;
            if (target) {
              target.scrollIntoView({ behavior: "smooth", block: "start" });
              setActiveThumb(targetId);
            }
          });
        });

        if (targets.length && "IntersectionObserver" in window) {
          const observer = new IntersectionObserver(
            (entries) => {
              entries.forEach((entry) => {
                if (entry.isIntersecting) {
                  setActiveThumb(entry.target.id);
                }
              });
            },
            { threshold: 0.6 }
          );
          targets.forEach((target) => observer.observe(target));
        }

        setActiveThumb(thumbs[0].dataset.productThumbTarget);
      });

      const variationGroups = document.querySelectorAll("[data-variation-group]");
      variationGroups.forEach((group) => {
        const attributeName = group.getAttribute("data-attribute-name");
        const scope = group.closest("[data-variation-scope]") || document;
        const form = scope.querySelector("form.variations_form");
        if (!attributeName || !form) return;
        const select = form.querySelector(`select[name='${attributeName}']`);
        if (!select) return;
        const chips = Array.from(group.querySelectorAll("[data-variation-value]"));
        if (!chips.length) return;

        const setActive = (value) => {
          chips.forEach((chip) => {
            chip.classList.toggle("is-active", chip.dataset.variationValue === value);
          });
        };

        chips.forEach((chip) => {
          chip.addEventListener("click", (event) => {
            event.preventDefault();
            const value = chip.dataset.variationValue || "";
            select.value = value;
            select.dispatchEvent(new Event("change", { bubbles: true }));
            setActive(value);
          });
        });

        select.addEventListener("change", () => {
          setActive(select.value);
        });

        setActive(select.value);
      });

      const enhanceVariableQty = () => {
        document.querySelectorAll(".fjord-product-page__form form.variations_form").forEach((form) => {
          const addToCart = form.querySelector(".woocommerce-variation-add-to-cart, .variations_button");
          if (!addToCart) return;
          if (addToCart.querySelector("[data-product-qty]")) return;
          const qty = addToCart.querySelector(".quantity");
          if (!qty) return;
          const input = qty.querySelector("input.qty");
          if (!input) return;

          const wrapper = document.createElement("div");
          wrapper.className = "fjord-product-page__qty";
          wrapper.setAttribute("data-product-qty", "");

          const minus = document.createElement("button");
          minus.type = "button";
          minus.className = "fjord-product-page__qty-btn";
          minus.dataset.qtyChange = "-1";
          minus.setAttribute("aria-label", "Decrease quantity");
          minus.textContent = "-";

          const plus = document.createElement("button");
          plus.type = "button";
          plus.className = "fjord-product-page__qty-btn";
          plus.dataset.qtyChange = "1";
          plus.setAttribute("aria-label", "Increase quantity");
          plus.textContent = "+";

          wrapper.append(minus, input, plus);
          qty.replaceWith(wrapper);
        });
      };

      enhanceVariableQty();

      if (window.jQuery) {
        window.jQuery(document.body).on("found_variation reset_data woocommerce_variation_has_changed", () => {
          enhanceVariableQty();
        });
      }

      const qtyGroups = document.querySelectorAll("[data-product-qty]");
      qtyGroups.forEach((group) => {
        const input = group.querySelector("input.qty");
        if (!input) return;
        const getValue = () => parseFloat(input.value || "0") || 0;
        const getStep = () => {
          const step = parseFloat(input.step || "1");
          return Number.isNaN(step) ? 1 : step;
        };
        const getMin = () => {
          const min = parseFloat(input.min || "1");
          return Number.isNaN(min) ? 1 : min;
        };
        const getMax = () => {
          const max = parseFloat(input.max || "");
          return Number.isNaN(max) ? Infinity : max;
        };

        group.querySelectorAll("[data-qty-change]").forEach((button) => {
          button.addEventListener("click", () => {
            const direction = Number(button.dataset.qtyChange || 0);
            if (!direction) return;
            const nextValue = Math.min(getMax(), Math.max(getMin(), getValue() + getStep() * direction));
            input.value = nextValue;
            input.dispatchEvent(new Event("change", { bubbles: true }));
          });
        });
      });

      const cartQtyGroups = document.querySelectorAll("[data-cart-qty-control]");
      cartQtyGroups.forEach((group) => {
        const input = group.querySelector("input.qty");
        if (!input) return;
        const getValue = () => parseFloat(input.value || "0") || 0;
        const getStep = () => {
          const step = parseFloat(input.step || "1");
          return Number.isNaN(step) ? 1 : step;
        };
        const getMin = () => {
          const min = parseFloat(input.min || "0");
          return Number.isNaN(min) ? 0 : min;
        };
        const getMax = () => {
          const max = parseFloat(input.max || "");
          return Number.isNaN(max) ? Infinity : max;
        };

        group.querySelectorAll("[data-cart-qty-change]").forEach((button) => {
          button.addEventListener("click", () => {
            const direction = Number(button.dataset.cartQtyChange || 0);
            if (!direction) return;
            const nextValue = Math.min(getMax(), Math.max(getMin(), getValue() + getStep() * direction));
            input.value = nextValue;
            input.dispatchEvent(new Event("change", { bubbles: true }));
          });
        });
      });

      const syncCollectionCardHeights = () => {
        const media = window.matchMedia("(max-width: 768px)");
        const woodContent = document.querySelector(".fjord-collection-card--wood .fjord-collection-card__content");
        const darkCard = document.querySelector(".fjord-collection-card--dark");
        if (!woodContent || !darkCard) return;
        if (!media.matches) {
          darkCard.style.removeProperty("height");
          darkCard.style.removeProperty("min-height");
          darkCard.style.removeProperty("max-height");
          return;
        }
        const woodHeight = woodContent.getBoundingClientRect().height;
        darkCard.style.setProperty("height", `${woodHeight}px`, "important");
        darkCard.style.setProperty("min-height", `${woodHeight}px`, "important");
        darkCard.style.setProperty("max-height", `${woodHeight}px`, "important");
      };

      window.addEventListener("load", syncCollectionCardHeights);
      window.addEventListener("resize", () => {
        window.requestAnimationFrame(syncCollectionCardHeights);
      });

      const revealBlocks = document.querySelectorAll(".fjord-reveal");
      if (revealBlocks.length) {
        if ("IntersectionObserver" in window) {
          const observer = new IntersectionObserver(
            (entries, obs) => {
              entries.forEach((entry) => {
                if (entry.isIntersecting) {
                  entry.target.classList.add("is-visible");
                  obs.unobserve(entry.target);
                }
              });
            },
            { threshold: 0.2 }
          );
          revealBlocks.forEach((block) => observer.observe(block));
        } else {
          revealBlocks.forEach((block) => block.classList.add("is-visible"));
        }
      }

      const mobileMenu = document.querySelector("[data-mobile-menu]");
      const openMenu = document.querySelector("[data-mobile-menu-open]");
      const closeMenuButtons = document.querySelectorAll("[data-mobile-menu-close]");
      if (mobileMenu && openMenu) {
        const toggleMenu = (isOpen) => {
          mobileMenu.classList.toggle("is-open", isOpen);
          document.body.classList.toggle("fjord-menu-open", isOpen);
          mobileMenu.setAttribute("aria-hidden", String(!isOpen));
        };

        openMenu.addEventListener("click", () => toggleMenu(true));
        closeMenuButtons.forEach((btn) => {
          btn.addEventListener("click", () => toggleMenu(false));
        });

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

      const searchModal = document.querySelector("[data-search-modal]");
      const openSearch = document.querySelector("[data-search-modal-open]");
      const closeSearchButtons = document.querySelectorAll("[data-search-modal-close]");
      if (searchModal && openSearch) {
        const input = searchModal.querySelector(".fjord-search-modal__input");
        const toggleSearch = (isOpen) => {
          searchModal.classList.toggle("is-open", isOpen);
          searchModal.setAttribute("aria-hidden", String(!isOpen));
          if (isOpen && input) {
            input.focus();
            requestAnimationFrame(() => {
              input.focus();
              if (typeof input.setSelectionRange === "function") {
                const length = input.value.length;
                input.setSelectionRange(length, length);
              }
            });
          }
        };

        openSearch.addEventListener("click", () => toggleSearch(true));
        closeSearchButtons.forEach((btn) => {
          btn.addEventListener("click", () => toggleSearch(false));
        });

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

      const setupMobileProductSlider = () => {
        const media = window.matchMedia("(max-width: 992px)");
        document.querySelectorAll(".fjord-product-page__media").forEach((mediaWrap) => {
          const stack = mediaWrap.querySelector(".fjord-product-page__media-stack");
          if (!stack) return;
          const existing = mediaWrap.querySelector(".fjord-product-page__slider-controls");
          if (!media.matches) {
            if (existing) existing.remove();
            return;
          }
          if (existing) return;

          const items = Array.from(stack.querySelectorAll(".fjord-product-page__media-item"));
          if (items.length < 2) return;

          const controls = document.createElement("div");
          controls.className = "fjord-product-page__slider-controls";

          const prev = document.createElement("button");
          prev.type = "button";
          prev.className = "fjord-product-page__slider-btn fjord-product-page__slider-btn--prev";
          prev.setAttribute("aria-label", "Previous image");
          prev.textContent = "<";

          const next = document.createElement("button");
          next.type = "button";
          next.className = "fjord-product-page__slider-btn fjord-product-page__slider-btn--next";
          next.setAttribute("aria-label", "Next image");
          next.textContent = ">";

          const dotsWrap = document.createElement("div");
          dotsWrap.className = "fjord-product-page__slider-dots";

          const dots = items.map((item, index) => {
            const dot = document.createElement("button");
            dot.type = "button";
            dot.className = "fjord-product-page__slider-dot";
            dot.setAttribute("aria-label", `Go to slide ${index + 1}`);
            dot.addEventListener("click", () => {
              item.scrollIntoView({ behavior: "smooth", inline: "center", block: "nearest" });
            });
            dotsWrap.appendChild(dot);
            return dot;
          });

          const setActive = (index) => {
            dots.forEach((dot, dotIndex) => {
              dot.classList.toggle("is-active", dotIndex === index);
            });
          };

          if ("IntersectionObserver" in window) {
            const observer = new IntersectionObserver(
              (entries) => {
                entries.forEach((entry) => {
                  if (entry.isIntersecting) {
                    const index = items.indexOf(entry.target);
                    if (index >= 0) setActive(index);
                  }
                });
              },
              { root: stack, threshold: 0.6 }
            );
            items.forEach((item) => observer.observe(item));
          } else {
            stack.addEventListener("scroll", () => {
              const left = stack.scrollLeft;
              const width = stack.clientWidth || 1;
              const index = Math.round(left / width);
              setActive(Math.max(0, Math.min(items.length - 1, index)));
            });
          }

          prev.addEventListener("click", () => {
            stack.scrollBy({ left: -stack.clientWidth, behavior: "smooth" });
          });

          next.addEventListener("click", () => {
            stack.scrollBy({ left: stack.clientWidth, behavior: "smooth" });
          });

          controls.append(prev, dotsWrap, next);
          mediaWrap.appendChild(controls);
          setActive(0);
        });
      };

      setupMobileProductSlider();
      window.addEventListener("resize", () => {
        window.requestAnimationFrame(setupMobileProductSlider);
      });

      const accordionDetails = document.querySelectorAll(".fjord-product-page__accordion");
      accordionDetails.forEach((detail) => {
        const summary = detail.querySelector("summary");
        const body = detail.querySelector(".fjord-product-page__accordion-body");
        if (!summary || !body) return;

        body.style.overflow = "hidden";
        body.style.transition = "opacity 0.3s ease";
        body.style.maxHeight = "none";
        body.style.transform = "none";
        body.style.opacity = detail.open ? "1" : "0";
        body.style.display = detail.open ? "block" : "none";

        summary.addEventListener("click", (event) => {
          event.preventDefault();
          summary.classList.add("is-pressed");
          window.setTimeout(() => summary.classList.remove("is-pressed"), 180);
          if (summary.animate) {
            summary.animate(
              [
                { opacity: 1 },
                { opacity: 0.55 },
                { opacity: 1 },
              ],
              { duration: 240, easing: "ease-in-out" }
            );
          }
          const isOpen = detail.open;
          if (isOpen) {
            body.style.opacity = "0";
            window.setTimeout(() => {
              body.style.display = "none";
              detail.open = false;
            }, 240);
            return;
          }

          detail.open = true;
          body.style.display = "block";
          body.style.opacity = "0";
          requestAnimationFrame(() => {
            body.style.opacity = "1";
          });
        });
      });
    })();
  </script>
</body>
</html>
