(function () {
  'use strict';

  var galleryLightbox = null;
  var galleryLightboxImage = null;
  var galleryLightboxPrev = null;
  var galleryLightboxNext = null;
  var galleryLightboxZoom = null;
  var galleryLightboxViewport = null;
  var galleryLightboxState = {
    items: [],
    index: 0,
    zoomed: false,
    originX: 50,
    originY: 50
  };

  function ensureGalleryLightbox() {
    if (galleryLightbox) {
      return;
    }

    var overlay = document.createElement('div');
    overlay.className = 'wcmv-gallery-lightbox';
    overlay.setAttribute('aria-hidden', 'true');

    var dialog = document.createElement('div');
    dialog.className = 'wcmv-gallery-lightbox__dialog';
    dialog.setAttribute('role', 'dialog');
    dialog.setAttribute('aria-modal', 'true');
    dialog.setAttribute('aria-label', 'Image viewer');

    var close = document.createElement('button');
    close.type = 'button';
    close.className = 'wcmv-gallery-lightbox__close';
    close.setAttribute('aria-label', 'Close image viewer');
    close.textContent = '×';

    var prev = document.createElement('button');
    prev.type = 'button';
    prev.className = 'wcmv-gallery-lightbox__nav wcmv-gallery-lightbox__nav--prev';
    prev.setAttribute('aria-label', 'Previous image');
    prev.textContent = '‹';

    var next = document.createElement('button');
    next.type = 'button';
    next.className = 'wcmv-gallery-lightbox__nav wcmv-gallery-lightbox__nav--next';
    next.setAttribute('aria-label', 'Next image');
    next.textContent = '›';

    var viewport = document.createElement('div');
    viewport.className = 'wcmv-gallery-lightbox__viewport';

    var image = document.createElement('img');
    image.className = 'wcmv-gallery-lightbox__image';
    image.alt = '';
    viewport.appendChild(image);

    var zoom = document.createElement('button');
    zoom.type = 'button';
    zoom.className = 'wcmv-gallery-lightbox__zoom';
    zoom.setAttribute('aria-label', 'Toggle zoom');
    zoom.textContent = 'Zoom';

    dialog.appendChild(close);
    dialog.appendChild(prev);
    dialog.appendChild(viewport);
    dialog.appendChild(next);
    dialog.appendChild(zoom);
    overlay.appendChild(dialog);
    document.body.appendChild(overlay);

    close.addEventListener('click', function () {
      closeGalleryLightbox();
    });

    overlay.addEventListener('click', function (event) {
      if (event.target === overlay) {
        closeGalleryLightbox();
      }
    });

    prev.addEventListener('click', function () {
      if (!galleryLightboxState.items.length) {
        return;
      }
      galleryLightboxState.index =
        (galleryLightboxState.index - 1 + galleryLightboxState.items.length) %
        galleryLightboxState.items.length;
      galleryLightboxState.zoomed = false;
      renderGalleryLightbox();
    });

    next.addEventListener('click', function () {
      if (!galleryLightboxState.items.length) {
        return;
      }
      galleryLightboxState.index =
        (galleryLightboxState.index + 1) % galleryLightboxState.items.length;
      galleryLightboxState.zoomed = false;
      renderGalleryLightbox();
    });

    zoom.addEventListener('click', function () {
      galleryLightboxState.zoomed = !galleryLightboxState.zoomed;
      renderGalleryLightbox();
    });

    image.addEventListener('dblclick', function () {
      galleryLightboxState.zoomed = !galleryLightboxState.zoomed;
      renderGalleryLightbox();
    });

    viewport.addEventListener('mousemove', function (event) {
      if (!galleryLightboxState.zoomed || !galleryLightboxImage) {
        return;
      }
      var rect = galleryLightboxImage.getBoundingClientRect();
      if (!rect.width || !rect.height) {
        return;
      }
      var x = ((event.clientX - rect.left) / rect.width) * 100;
      var y = ((event.clientY - rect.top) / rect.height) * 100;
      if (x < 0) x = 0;
      if (x > 100) x = 100;
      if (y < 0) y = 0;
      if (y > 100) y = 100;
      galleryLightboxState.originX = x;
      galleryLightboxState.originY = y;
      galleryLightboxImage.style.transformOrigin = x + '% ' + y + '%';
    });

    viewport.addEventListener('mouseleave', function () {
      if (!galleryLightboxState.zoomed || !galleryLightboxImage) {
        return;
      }
      galleryLightboxState.originX = 50;
      galleryLightboxState.originY = 50;
      galleryLightboxImage.style.transformOrigin = '50% 50%';
    });

    galleryLightbox = overlay;
    galleryLightboxImage = image;
    galleryLightboxPrev = prev;
    galleryLightboxNext = next;
    galleryLightboxZoom = zoom;
    galleryLightboxViewport = viewport;
  }

  function renderGalleryLightbox() {
    if (!galleryLightbox || !galleryLightboxImage || !galleryLightboxState.items.length) {
      return;
    }

    var item = galleryLightboxState.items[galleryLightboxState.index] || galleryLightboxState.items[0];
    galleryLightboxImage.setAttribute('src', item.src || '');
    galleryLightboxImage.setAttribute('alt', item.alt || '');

    if (galleryLightboxState.zoomed) {
      galleryLightboxImage.classList.add('is-zoomed');
      galleryLightboxImage.style.transformOrigin =
        galleryLightboxState.originX + '% ' + galleryLightboxState.originY + '%';
      galleryLightboxZoom.textContent = 'Unzoom';
      galleryLightboxViewport.scrollTop = 0;
      galleryLightboxViewport.scrollLeft = 0;
    } else {
      galleryLightboxImage.classList.remove('is-zoomed');
      galleryLightboxImage.style.transformOrigin = '50% 50%';
      galleryLightboxZoom.textContent = 'Zoom';
      galleryLightboxViewport.scrollTop = 0;
      galleryLightboxViewport.scrollLeft = 0;
    }

    var hasMultiple = galleryLightboxState.items.length > 1;
    galleryLightboxPrev.style.display = hasMultiple ? '' : 'none';
    galleryLightboxNext.style.display = hasMultiple ? '' : 'none';
  }

  function openGalleryLightbox(items, startIndex) {
    ensureGalleryLightbox();
    if (!galleryLightbox) {
      return;
    }

    galleryLightboxState.items = Array.isArray(items) ? items.slice() : [];
    galleryLightboxState.index = Math.max(0, parseInt(startIndex || 0, 10) || 0);
    galleryLightboxState.zoomed = false;
    galleryLightboxState.originX = 50;
    galleryLightboxState.originY = 50;

    if (!galleryLightboxState.items.length) {
      return;
    }

    renderGalleryLightbox();
    galleryLightbox.classList.add('is-open');
    galleryLightbox.setAttribute('aria-hidden', 'false');
    document.body.classList.add('mv-modal-open');
  }

  function closeGalleryLightbox() {
    if (!galleryLightbox) {
      return;
    }
    galleryLightbox.classList.remove('is-open');
    galleryLightbox.setAttribute('aria-hidden', 'true');
    galleryLightboxState.zoomed = false;
    document.body.classList.remove('mv-modal-open');
  }

  function initGallery(gallery) {
    var main = gallery.querySelector('.wcmv-auction-gallery-main-image');
    if (!main) {
      return;
    }

    var thumbs = gallery.querySelectorAll('.wcmv-auction-gallery-thumb');
    var items = [];
    var activeIndex = 0;

    if (thumbs.length) {
      thumbs.forEach(function (thumb, idx) {
        var src = thumb.getAttribute('data-large-src');
        var alt = thumb.getAttribute('data-large-alt') || '';
        if (!src) {
          return;
        }
        items.push({ src: src, alt: alt });
        if (thumb.classList.contains('is-active')) {
          activeIndex = idx;
        }
      });
    }

    if (!items.length) {
      items.push({
        src: main.getAttribute('src') || '',
        alt: main.getAttribute('alt') || ''
      });
    }

    thumbs.forEach(function (thumb) {
      thumb.addEventListener('click', function () {
        var src = thumb.getAttribute('data-large-src');
        var alt = thumb.getAttribute('data-large-alt') || '';

        if (src) {
          main.setAttribute('src', src);
          main.setAttribute('alt', alt);
        }

        thumbs.forEach(function (btn) {
          btn.classList.remove('is-active');
        });
        thumb.classList.add('is-active');

        for (var i = 0; i < items.length; i++) {
          if (items[i].src === src) {
            activeIndex = i;
            break;
          }
        }
      });
    });

    main.setAttribute('role', 'button');
    main.setAttribute('tabindex', '0');
    main.setAttribute('aria-label', 'Open image viewer');

    main.addEventListener('click', function () {
      openGalleryLightbox(items, activeIndex);
    });

    main.addEventListener('keydown', function (event) {
      if (event.key === 'Enter' || event.key === ' ') {
        event.preventDefault();
        openGalleryLightbox(items, activeIndex);
      }
    });
  }

  function formatRemaining(targetDate) {
    var diffMs = targetDate.getTime() - Date.now();
    if (diffMs <= 0) {
      return 'Ended';
    }
    var totalMinutes = Math.floor(diffMs / 60000);
    var days = Math.floor(totalMinutes / 1440);
    var hours = Math.floor((totalMinutes % 1440) / 60);
    var minutes = totalMinutes % 60;
    var parts = [];
    if (days > 0) parts.push(days + 'd');
    if (hours > 0 || days > 0) parts.push(hours + 'h');
    parts.push(minutes + 'm');
    return 'Ends in ' + parts.join(' ');
  }

  function formatAbsoluteLocal(targetDate) {
    try {
      return targetDate.toLocaleString(undefined, {
        weekday: 'short',
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      });
    } catch (e) {
      return targetDate.toString();
    }
  }

  function initAuctionTiming() {
    var rows = document.querySelectorAll('.mv-auction-timing[data-end-ts]');
    if (!rows.length) {
      return;
    }

    function renderAll() {
      rows.forEach(function (row) {
        var ts = parseInt(row.getAttribute('data-end-ts') || '0', 10);
        if (!ts) {
          return;
        }
        var endDate = new Date(ts * 1000);
        var endsNode = row.querySelector('.mv-auction-timing-ends');
        if (!endsNode) {
          return;
        }
        var remaining = formatRemaining(endDate);
        if (remaining === 'Ended') {
          endsNode.textContent = 'Ended';
        } else {
          endsNode.textContent = remaining + ' · ' + formatAbsoluteLocal(endDate);
        }
      });
    }

    renderAll();
    window.setInterval(renderAll, 30000);
  }

  document.addEventListener('DOMContentLoaded', function () {
    var galleries = document.querySelectorAll('.wcmv-auction-gallery');
    if (!galleries.length) {
      // continue: page can still use toggle forms without gallery
    } else {
      galleries.forEach(initGallery);
    }

    var toggles = document.querySelectorAll('.mv-toggle-form');
    toggles.forEach(function (toggle) {
      toggle.addEventListener('click', function () {
        var selector = toggle.getAttribute('data-target');
        if (!selector) {
          return;
        }
        var form = document.querySelector(selector);
        if (!form) {
          return;
        }
        form.classList.toggle('is-open');
      });
    });

    var detailSections = document.querySelectorAll('.wcmv-t1-details-section');
    detailSections.forEach(function (section) {
      var tabs = section.querySelectorAll('.wcmv-t1-tab');
      var panels = section.querySelectorAll('.wcmv-t1-panel');
      if (!tabs.length || !panels.length) {
        return;
      }

      tabs.forEach(function (tab) {
        tab.addEventListener('click', function () {
          var target = tab.getAttribute('data-panel');
          if (!target) {
            return;
          }

          tabs.forEach(function (item) {
            item.classList.remove('is-active');
          });
          panels.forEach(function (panel) {
            panel.classList.remove('is-active');
          });

          tab.classList.add('is-active');
          var panel = section.querySelector('#' + target);
          if (panel) {
            panel.classList.add('is-active');
          }
        });
      });
    });

    var conditionInfoButtons = document.querySelectorAll('.mv-condition-info[data-target]');
    conditionInfoButtons.forEach(function (button) {
      button.addEventListener('click', function (event) {
        event.preventDefault();
        event.stopPropagation();
        var target = button.getAttribute('data-target');
        if (!target) return;
        var popover = document.querySelector(target);
        if (!popover) return;

        var isOpen = popover.classList.contains('is-open');
        document.querySelectorAll('.mv-condition-popover.is-open').forEach(function (openPopover) {
          openPopover.classList.remove('is-open');
        });
        if (!isOpen) {
          popover.classList.add('is-open');
        }
      });
    });

    document.addEventListener('click', function () {
      document.querySelectorAll('.mv-condition-popover.is-open').forEach(function (openPopover) {
        openPopover.classList.remove('is-open');
      });
    });

    var shippingDetailTriggers = document.querySelectorAll('.mv-shipping-details-trigger[data-target]');
    shippingDetailTriggers.forEach(function (trigger) {
      trigger.addEventListener('click', function (event) {
        event.preventDefault();
        var target = trigger.getAttribute('data-target');
        if (!target) return;
        var modal = document.querySelector(target);
        if (!modal) return;
        modal.classList.add('is-open');
        modal.setAttribute('aria-hidden', 'false');
        document.body.classList.add('mv-modal-open');
      });
    });

    var shippingDetailModals = document.querySelectorAll('.mv-shipping-details-modal');
    shippingDetailModals.forEach(function (modal) {
      var closeBtn = modal.querySelector('.mv-shipping-details-modal__close');
      if (closeBtn) {
        closeBtn.addEventListener('click', function () {
          modal.classList.remove('is-open');
          modal.setAttribute('aria-hidden', 'true');
          document.body.classList.remove('mv-modal-open');
        });
      }

      modal.addEventListener('click', function (event) {
        if (event.target === modal) {
          modal.classList.remove('is-open');
          modal.setAttribute('aria-hidden', 'true');
          document.body.classList.remove('mv-modal-open');
        }
      });
    });

    document.addEventListener('keydown', function (event) {
      if (event.key !== 'Escape') return;
      var openImageLightbox = document.querySelector('.wcmv-gallery-lightbox.is-open');
      if (openImageLightbox) {
        closeGalleryLightbox();
        return;
      }
      var openModal = document.querySelector('.mv-shipping-details-modal.is-open');
      if (!openModal) return;
      openModal.classList.remove('is-open');
      openModal.setAttribute('aria-hidden', 'true');
      document.body.classList.remove('mv-modal-open');
    });

    initAuctionTiming();
  });
})();
