//=========================
// i18n Helper - get translated strings from wp_localize_script
//=========================
function pawfect_i18n(key, fallback) {
  if (typeof pawfect_ajax !== 'undefined' && pawfect_ajax.i18n && pawfect_ajax.i18n[key]) {
    return pawfect_ajax.i18n[key];
  }
  return fallback || key;
}

//=========================
// Cart Dropdown Functionality
//=========================

// Function to initialize cart dropdowns (can be called multiple times)
function initializeCartDropdowns() {
  const cartContainers = document.querySelectorAll('.pawfect-cart-dropdown-container');

  cartContainers.forEach(container => {
    const trigger = container.querySelector('.pawfect-cart-trigger');
    const dropdown = container.querySelector('.pawfect-cart-dropdown');
    let hideTimeout;

    if (trigger && dropdown) {
      // Show dropdown on hover/click
      function showDropdown() {
        clearTimeout(hideTimeout);
        dropdown.classList.remove('pawfect-opacity-0', 'pawfect-invisible', 'pawfect-translate-y-2');
        dropdown.classList.add('pawfect-opacity-100', 'pawfect-visible', 'pawfect-translate-y-0');
      }

      // Hide dropdown with delay
      function hideDropdown() {
        hideTimeout = setTimeout(() => {
          dropdown.classList.add('pawfect-opacity-0', 'pawfect-invisible', 'pawfect-translate-y-2');
          dropdown.classList.remove('pawfect-opacity-100', 'pawfect-visible', 'pawfect-translate-y-0');
        }, 150);
      }

      // Event listeners
      trigger.addEventListener('mouseenter', showDropdown);
      trigger.addEventListener('click', (e) => {
        e.preventDefault();
        showDropdown();
      });

      container.addEventListener('mouseleave', hideDropdown);
      dropdown.addEventListener('mouseenter', () => clearTimeout(hideTimeout));
      dropdown.addEventListener('mouseleave', hideDropdown);

      // Handle remove cart item
      dropdown.addEventListener('click', function (e) {
        if (e.target.closest('.pawfect-remove-cart-item')) {
          e.preventDefault();
          const button = e.target.closest('.pawfect-remove-cart-item');
          const cartItemKey = button.dataset.cartItemKey;

          if (cartItemKey && typeof pawfect_ajax !== 'undefined') {
            // Show loading state
            button.innerHTML = '<svg class="pawfect-w-3 pawfect-h-3 pawfect-animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path></svg>';

            // AJAX request to remove item
            fetch(pawfect_ajax.ajax_url, {
              method: 'POST',
              headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
              },
              body: new URLSearchParams({
                action: 'pawfect_remove_cart_item',
                cart_item_key: cartItemKey,
                nonce: pawfect_ajax.cart_nonce
              })
            })
              .then(response => response.json())
              .then(data => {
                if (data.success) {
                  // Update cart fragments if provided
                  if (data.data && data.data.fragments) {
                    Object.keys(data.data.fragments).forEach(key => {
                      const elements = document.querySelectorAll(key);
                      elements.forEach(element => {
                        element.outerHTML = data.data.fragments[key];
                      });
                    });
                  }

                  // Trigger WooCommerce events
                  jQuery(document.body).trigger('removed_from_cart', [data.data.fragments, data.data.cart_hash]);
                  jQuery(document.body).trigger('wc_fragment_refresh');
                } else {
                  // Restore button
                  button.innerHTML = '<svg class="pawfect-w-3 pawfect-h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>';
                }
              })
              .catch(error => {
                console.error('Error removing cart item:', error);
                // Restore button
                button.innerHTML = '<svg class="pawfect-w-3 pawfect-h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path></svg>';
              });
          }
        }
      });
    }
  });

  // Wishlist functionality
  document.addEventListener('click', function (e) {
    if (e.target.closest('.pawfect-wishlist-btn')) {
      e.preventDefault();
      const button = e.target.closest('.pawfect-wishlist-btn');
      const productId = button.dataset.productId;
      const isActive = button.classList.contains('pawfect-wishlist-active');
      const action = isActive ? 'remove' : 'add';

      if (typeof pawfect_wishlist !== 'undefined') {
        // Show loading state
        const originalContent = button.innerHTML;
        button.innerHTML = '<svg class="pawfect-w-5 pawfect-h-5 pawfect-animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path></svg>';
        button.disabled = true;

        // AJAX request
        fetch(pawfect_wishlist.ajax_url, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
          },
          body: new URLSearchParams({
            action: 'pawfect_toggle_wishlist',
            product_id: productId,
            wishlist_action: action,
            nonce: pawfect_wishlist.nonce
          })
        })
          .then(response => response.json())
          .then(data => {
            if (data.success) {
              // Update button state
              if (action === 'add') {
                button.classList.add('pawfect-wishlist-active');
                button.title = pawfect_wishlist.remove_text;
                button.querySelector('svg').setAttribute('fill', 'currentColor');
              } else {
                button.classList.remove('pawfect-wishlist-active');
                button.title = pawfect_wishlist.add_text;
                button.querySelector('svg').setAttribute('fill', 'none');
              }

              // Update wishlist count in header if exists
              const wishlistCounts = document.querySelectorAll('.pawfect-wishlist-count');
              wishlistCounts.forEach(count => {
                count.textContent = data.data.wishlist_count;
                // Use CSS classes instead of inline styles for visibility
                if (data.data.wishlist_count > 0) {
                  count.classList.remove('pawfect-scale-0');
                  count.classList.add('pawfect-scale-100');
                } else {
                  count.classList.remove('pawfect-scale-100');
                  count.classList.add('pawfect-scale-0');
                }
              });

              // If on wishlist page and removing item, remove the item from view
              if (action === 'remove' && window.location.pathname.includes('wishlist')) {
                const wishlistItem = button.closest('.pawfect-wishlist-item');
                if (wishlistItem) {
                  wishlistItem.style.transform = 'scale(0.8)';
                  wishlistItem.style.opacity = '0';
                  setTimeout(() => {
                    wishlistItem.remove();
                    // Check if wishlist is now empty
                    const remainingItems = document.querySelectorAll('.pawfect-wishlist-item');
                    if (remainingItems.length === 0) {
                      location.reload(); // Reload to show empty state
                    }
                  }, 300);
                }
              }
            } else {
              console.error('Wishlist error:', data.data);
            }
          })
          .catch(error => {
            console.error('Wishlist request failed:', error);
          })
          .finally(() => {
            // Restore button
            button.innerHTML = originalContent;
            button.disabled = false;
          });
      }
    }
  });

  // Notification system for wishlist feedback
  function pawfect_show_notification(message, type = 'success') {
    // Remove existing notifications
    const existingNotifications = document.querySelectorAll('.pawfect-notification');
    existingNotifications.forEach(notification => notification.remove());

    // Create notification
    const notification = document.createElement('div');
    notification.className = `pawfect-notification pawfect-fixed pawfect-top-4 pawfect-right-4 pawfect-z-50 pawfect-px-6 pawfect-py-3 pawfect-rounded-lg pawfect-shadow-lg pawfect-transform pawfect-translate-x-full pawfect-transition-transform pawfect-duration-300 ${type === 'success' ? 'pawfect-bg-green-500 pawfect-text-white' : 'pawfect-bg-red-500 pawfect-text-white'}`;
    notification.textContent = message;

    document.body.appendChild(notification);

    // Show notification
    setTimeout(() => {
      notification.classList.remove('pawfect-translate-x-full');
    }, 100);

    // Hide notification after 3 seconds
    setTimeout(() => {
      notification.classList.add('pawfect-translate-x-full');
      setTimeout(() => {
        notification.remove();
      }, 300);
    }, 3000);
  }

  // Quick View Modal functionality
  const quickViewModal = document.getElementById('pawfect-quick-view-modal');
  const quickViewContent = document.getElementById('pawfect-quick-view-content');
  const quickViewClose = document.getElementById('pawfect-quick-view-close');

  // Open quick view modal
  document.addEventListener('click', function (e) {
    if (e.target.closest('.pawfect-quick-view-btn')) {
      e.preventDefault();
      const button = e.target.closest('.pawfect-quick-view-btn');
      const productId = button.dataset.productId;

      // Debug logging
      if (quickViewModal && quickViewContent) {
        // Fallback if localization fails
        const quickViewData = typeof pawfect_quick_view !== 'undefined' ? pawfect_quick_view : {
          ajax_url: window.location.origin + '/wp-admin/admin-ajax.php',
          nonce: '',
          loading_text: pawfect_i18n('adding', 'Loading...'),
          error_text: pawfect_i18n('error_adding', 'Error loading product')
        };

        // If no nonce available, show error
        if (!quickViewData.nonce) {
          quickViewContent.innerHTML = `
            <div class="pawfect-text-center pawfect-py-12">
              <svg class="pawfect-w-16 pawfect-h-16 pawfect-mx-auto pawfect-mb-4 pawfect-text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
              </svg>
              <p class="pawfect-text-gray-600">${pawfect_i18n('security_missing', 'Security token missing. Please refresh the page.')}</p>
            </div>
          `;
          return;
        }

        // Show modal with search modal style animation
        quickViewModal.style.display = 'block';
        quickViewModal.classList.remove('pawfect-pointer-events-none');

        // Force reflow
        quickViewModal.offsetHeight;

        // Animate in
        quickViewModal.classList.remove('pawfect-opacity-0', 'pawfect-invisible');
        const modalContent = quickViewModal.querySelector('#pawfect-quick-view-modal-content');
        if (modalContent) {
          modalContent.classList.remove('pawfect-scale-95');
          modalContent.classList.add('pawfect-scale-100');
        }

        document.body.style.overflow = 'hidden';

        // Reset content to loading state
        quickViewContent.innerHTML = `
          <div class="pawfect-text-center pawfect-py-12">
            <svg class="pawfect-w-8 pawfect-h-8 pawfect-mx-auto pawfect-mb-4 pawfect-text-gray-400 pawfect-animate-spin" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path>
            </svg>
            <p class="pawfect-text-gray-600">${quickViewData.loading_text}</p>
          </div>
        `;

        // AJAX request to load product
        fetch(quickViewData.ajax_url, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
          },
          body: new URLSearchParams({
            action: 'pawfect_quick_view',
            product_id: productId,
            nonce: quickViewData.nonce
          })
        })
          .then(response => {
            return response.json();
          })
          .then(data => {
            if (data.success) {
              quickViewContent.innerHTML = data.data.content;

              // Initialize quick view functionality
              initializeQuickViewFeatures();
            } else {
              quickViewContent.innerHTML = `
              <div class="pawfect-text-center pawfect-py-12">
                <svg class="pawfect-w-16 pawfect-h-16 pawfect-mx-auto pawfect-mb-4 pawfect-text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
                </svg>
                <p class="pawfect-text-gray-600">${quickViewData.error_text}</p>
              </div>
            `;
            }
          })
          .catch(error => {
            console.error('Quick view error:', error);
            quickViewContent.innerHTML = `
            <div class="pawfect-text-center pawfect-py-12">
              <svg class="pawfect-w-16 pawfect-h-16 pawfect-mx-auto pawfect-mb-4 pawfect-text-red-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path>
              </svg>
              <p class="pawfect-text-gray-600">${quickViewData.error_text}</p>
            </div>
          `;
          });
      } else {
        console.error('Quick View: Modal elements not found', {
          modal: quickViewModal,
          content: quickViewContent
        });
        return;
      }
    }
  });

  // Close quick view modal with search modal style animation
  function closeQuickViewModal() {
    if (quickViewModal) {
      // Animate out
      quickViewModal.classList.add('pawfect-opacity-0', 'pawfect-invisible');
      quickViewModal.classList.add('pawfect-pointer-events-none');
      const modalContent = quickViewModal.querySelector('#pawfect-quick-view-modal-content');
      if (modalContent) {
        modalContent.classList.add('pawfect-scale-95');
        modalContent.classList.remove('pawfect-scale-100');
      }

      document.body.style.overflow = '';

      // Hide after animation
      setTimeout(() => {
        quickViewModal.style.display = 'none';
      }, 300);
    }
  }

  if (quickViewClose) {
    quickViewClose.addEventListener('click', closeQuickViewModal);
  }

  // Close on backdrop click
  if (quickViewModal) {
    quickViewModal.addEventListener('click', function (e) {
      if (!e.target.closest('#pawfect-quick-view-modal-content')) {
        closeQuickViewModal();
      }
    });
  }

  // Close on escape key
  document.addEventListener('keydown', function (e) {
    if (e.key === 'Escape' && quickViewModal && quickViewModal.style.display !== 'none') {
      closeQuickViewModal();
    }
  });

    // Quick View features initialized separately

  // Initialize quick view features after content is loaded
  function initializeQuickViewFeatures() {
    // Image gallery functionality
    const thumbButtons = quickViewContent.querySelectorAll('.pawfect-thumb-btn');
    const mainImage = quickViewContent.querySelector('.pawfect-main-image img');

    thumbButtons.forEach(button => {
      button.addEventListener('click', function () {
        const fullImageUrl = this.dataset.fullImage;
        if (mainImage && fullImageUrl) {
          // Add loading state
          mainImage.style.opacity = '0.5';

          // Create new image to preload
          const newImg = new Image();
          newImg.onload = function () {
            mainImage.src = fullImageUrl;
            mainImage.style.opacity = '1';
          };
          newImg.src = fullImageUrl;

          // Update active state
          thumbButtons.forEach(btn => {
            btn.classList.remove('pawfect-border-pawfect-primary');
            btn.classList.add('pawfect-border-transparent');
          });
          this.classList.remove('pawfect-border-transparent');
          this.classList.add('pawfect-border-pawfect-primary');
        }
      });
    });

    // Add smooth transitions to main image
    if (mainImage) {
      mainImage.style.transition = 'opacity 0.3s ease-in-out';
    }

    // Quantity controls
    const qtyMinus = quickViewContent.querySelector('.pawfect-qty-minus');
    const qtyPlus = quickViewContent.querySelector('.pawfect-qty-plus');
    const qtyInput = quickViewContent.querySelector('.pawfect-qty-input');

    if (qtyMinus && qtyPlus && qtyInput) {
      qtyMinus.addEventListener('click', function () {
        const currentValue = parseInt(qtyInput.value) || 1;
        if (currentValue > 1) {
          qtyInput.value = currentValue - 1;
        }
      });

      qtyPlus.addEventListener('click', function () {
        const currentValue = parseInt(qtyInput.value) || 1;
        qtyInput.value = currentValue + 1;
      });
    }

    // Add to cart form handling
    const cartForm = quickViewContent.querySelector('.pawfect-quick-view-cart');
    if (cartForm) {
      cartForm.addEventListener('submit', function (e) {
        e.preventDefault();

        const formData = new FormData(this);
        const submitButton = this.querySelector('button[type="submit"]');
        const originalText = submitButton.textContent;

        // Show loading state
        submitButton.textContent = pawfect_i18n('adding', 'Adding...');
        submitButton.disabled = true;

        // Use WooCommerce AJAX add to cart
        fetch(wc_add_to_cart_params.wc_ajax_url.toString().replace('%%endpoint%%', 'add_to_cart'), {
          method: 'POST',
          body: formData
        })
          .then(response => response.json())
          .then(data => {
            if (data.error) {
              pawfect_show_notification(data.error_message || pawfect_i18n('error_adding', 'Error adding to cart'), 'error');
            } else {
              pawfect_show_notification(pawfect_i18n('product_added', 'Product added to cart!'), 'success');
              // Trigger cart fragments update
              jQuery(document.body).trigger('wc_fragment_refresh');
              // Close modal after successful add
              setTimeout(closeQuickViewModal, 1000);
            }
          })
          .catch(error => {
            console.error('Add to cart error:', error);
            pawfect_show_notification(pawfect_i18n('error_adding', 'Error adding to cart'), 'error');
          })
          .finally(() => {
            submitButton.textContent = originalText;
            submitButton.disabled = false;
          });
      });
    }
  }

  // Language Dropdown functionality - Initialize immediately
  function initLanguageDropdown() {
    const languageDropdowns = document.querySelectorAll('.pawfect-language-dropdown');

    languageDropdowns.forEach((dropdown, index) => {
      const trigger = dropdown.querySelector('.pawfect-language-trigger');
      const menu = dropdown.querySelector('.pawfect-language-menu');
      const arrow = trigger ? trigger.querySelector('svg') : null;
      const currentLang = trigger ? trigger.querySelector('span') : null;

      if (!trigger || !menu) {
        return;
      }

      // Toggle dropdown
      trigger.addEventListener('click', function (e) {
        e.preventDefault();
        e.stopPropagation();

        // Use inline styles for more reliable control
        const isOpen = menu.style.opacity === '1';

        // Close all other dropdowns
        document.querySelectorAll('.pawfect-language-menu').forEach(otherMenu => {
          if (otherMenu !== menu) {
            otherMenu.style.opacity = '0';
            otherMenu.style.visibility = 'hidden';
            otherMenu.style.transform = 'scale(0.95)';
            const otherArrow = otherMenu.parentElement.querySelector('svg');
            if (otherArrow) otherArrow.style.transform = 'rotate(0deg)';
          }
        });

        if (isOpen) {
          // Close dropdown
          menu.style.opacity = '0';
          menu.style.visibility = 'hidden';
          menu.style.transform = 'scale(0.95)';
          if (arrow) arrow.style.transform = 'rotate(0deg)';
        } else {
          // Open dropdown
          menu.style.opacity = '1';
          menu.style.visibility = 'visible';
          menu.style.transform = 'scale(1)';
          if (arrow) arrow.style.transform = 'rotate(180deg)';
        }
      });

      // Handle language selection
      menu.addEventListener('click', function (e) {
        if (e.target.closest('.pawfect-language-option')) {
          e.preventDefault();
          const option = e.target.closest('.pawfect-language-option');
          const langCode = option.dataset.lang;
          const langText = option.querySelector('span').textContent;
          const langFlag = option.querySelector('img').cloneNode(true);

          // Update current language display
          if (currentLang) {
            currentLang.innerHTML = '';
            currentLang.appendChild(document.createTextNode(langText.toUpperCase() + ' '));
            currentLang.appendChild(langFlag);
          }

          // Update all language triggers
          document.querySelectorAll('.pawfect-language-trigger span').forEach(span => {
            span.innerHTML = '';
            span.appendChild(document.createTextNode(langText.toUpperCase() + ' '));
            span.appendChild(langFlag.cloneNode(true));
          });

          // Close dropdown
          menu.style.opacity = '0';
          menu.style.visibility = 'hidden';
          menu.style.transform = 'scale(0.95)';
          if (arrow) arrow.style.transform = 'rotate(0deg)';

          // Store selected language
          localStorage.setItem('pawfect_selected_language', langCode);

          // Trigger custom event
          document.dispatchEvent(new CustomEvent('pawfect_language_changed', {
            detail: { language: langCode, text: langText }
          }));
        }
      });
    });

    // Close dropdown when clicking outside
    document.addEventListener('click', function (e) {
      if (!e.target.closest('.pawfect-language-dropdown')) {
        document.querySelectorAll('.pawfect-language-menu').forEach(menu => {
          menu.style.opacity = '0';
          menu.style.visibility = 'hidden';
          menu.style.transform = 'scale(0.95)';
          const arrow = menu.parentElement.querySelector('svg');
          if (arrow) arrow.style.transform = 'rotate(0deg)';
        });
      }
    });

    // Load saved language preference
    const savedLang = localStorage.getItem('pawfect_selected_language');
    if (savedLang) {
      const option = document.querySelector(`[data-lang="${savedLang}"]`);
      if (option) {
        const langText = option.querySelector('span').textContent;
        const langFlag = option.querySelector('img').cloneNode(true);

        document.querySelectorAll('.pawfect-language-trigger span').forEach(currentLang => {
          currentLang.innerHTML = '';
          currentLang.appendChild(document.createTextNode(langText.toUpperCase() + ' '));
          currentLang.appendChild(langFlag.cloneNode(true));
        });
      }
    }
  }

  // Initialize language dropdown when DOM is ready
  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initLanguageDropdown);
  } else {
    initLanguageDropdown();
  }

  // Enhanced AJAX Add to Cart functionality
  document.addEventListener('click', function (e) {
    if (e.target.closest('.pawfect-ajax-add-to-cart')) {
      e.preventDefault();
      const button = e.target.closest('.pawfect-ajax-add-to-cart');
      const productId = button.dataset.productId;
      const quantity = button.dataset.quantity || 1;
      const buttonText = button.querySelector('.pawfect-btn-text');
      const originalText = buttonText ? buttonText.textContent : button.textContent;

      // Show loading state
      if (buttonText) {
        buttonText.textContent = pawfect_i18n('adding', 'Adding...');
      } else {
        button.textContent = pawfect_i18n('adding', 'Adding...');
      }
      button.disabled = true;
      button.classList.add('pawfect-loading');

      // AJAX request
      const formData = new FormData();
      formData.append('product_id', productId);
      formData.append('quantity', quantity);

      fetch(wc_add_to_cart_params.wc_ajax_url.toString().replace('%%endpoint%%', 'add_to_cart'), {
        method: 'POST',
        body: formData
      })
        .then(response => response.json())
        .then(data => {
          if (data.error) {
            pawfect_show_notification(data.error_message || pawfect_i18n('error_adding', 'Error adding to cart'), 'error');
            // Restore button
            if (buttonText) {
              buttonText.textContent = originalText;
            } else {
              button.textContent = originalText;
            }
          } else {
            // Success feedback
            pawfect_show_notification(pawfect_i18n('product_added', 'Product added to cart!'), 'success');

            // Update button state
            button.classList.add('pawfect-added-to-cart');
            if (buttonText) {
              buttonText.textContent = pawfect_i18n('added_to_cart', 'Added to Cart');
            } else {
              button.textContent = pawfect_i18n('added_to_cart', 'Added to Cart');
            }

            // Trigger cart fragments update
            jQuery(document.body).trigger('wc_fragment_refresh');

            // Reset button after 3 seconds
            setTimeout(() => {
              button.classList.remove('pawfect-added-to-cart');
              if (buttonText) {
                buttonText.textContent = originalText;
              } else {
                button.textContent = originalText;
              }
            }, 3000);
          }
        })
        .catch(error => {
          console.error('Add to cart error:', error);
          pawfect_show_notification(pawfect_i18n('error_adding', 'Error adding to cart'), 'error');
          // Restore button
          if (buttonText) {
            buttonText.textContent = originalText;
          } else {
            button.textContent = originalText;
          }
        })
        .finally(() => {
          button.disabled = false;
          button.classList.remove('pawfect-loading');
        });
    }
  });
}

// Initialize cart dropdowns on page load
document.addEventListener("DOMContentLoaded", function () {
  initializeCartDropdowns();
  initializeNavigationDropdowns();
});

//=========================
// Navigation Dropdown Functionality
//=========================
function initializeNavigationDropdowns() {
  const dropdownItems = document.querySelectorAll('.pawfect-has-dropdown');

  dropdownItems.forEach(item => {
    const dropdownMenu = item.querySelector(':scope > .pawfect-dropdown-menu'); // Only direct child dropdown
    let hideTimeout;

    if (dropdownMenu) {
      // Determine if this is a 3rd level or deeper menu
      const isDeepLevel = item.closest('.pawfect-dropdown-menu') !== null;

      // Show dropdown on hover
      function showDropdown() {
        clearTimeout(hideTimeout);

        // Hide all sibling dropdowns at the same level first
        const parentContainer = item.parentElement;
        if (parentContainer) {
          const siblingDropdowns = parentContainer.querySelectorAll(':scope > .pawfect-has-dropdown > .pawfect-dropdown-menu');
          siblingDropdowns.forEach(siblingMenu => {
            if (siblingMenu !== dropdownMenu) {
              hideDropdownMenu(siblingMenu);
            }
          });
        }

        // Show this dropdown
        if (isDeepLevel) {
          // For 3rd level and beyond - horizontal slide
          dropdownMenu.classList.remove('pawfect-opacity-0', 'pawfect-translate-x-2', 'pawfect-pointer-events-none');
          dropdownMenu.classList.add('pawfect-opacity-100', 'pawfect-translate-x-0', 'pawfect-pointer-events-auto');

          // Viewport-edge detection: flip to left if menu overflows right side
          requestAnimationFrame(function () {
            var rect = dropdownMenu.getBoundingClientRect();
            var viewportWidth = window.innerWidth || document.documentElement.clientWidth;
            if (rect.right > viewportWidth) {
              dropdownMenu.classList.add('pawfect-flip-left');
            } else {
              dropdownMenu.classList.remove('pawfect-flip-left');
            }
          });
        } else {
          // For 2nd level - vertical slide
          dropdownMenu.classList.remove('pawfect-opacity-0', 'pawfect-translate-y-3', 'pawfect-pointer-events-none');
          dropdownMenu.classList.add('pawfect-opacity-100', 'pawfect-translate-y-0', 'pawfect-pointer-events-auto');
        }

        // Rotate arrow if this is a main menu item (depth 0)
        if (!isDeepLevel) {
          const arrow = item.querySelector('svg');
          if (arrow) {
            arrow.classList.add('pawfect-rotate-180');
          }
        }
      }

      // Hide dropdown with delay
      function hideDropdown() {
        hideTimeout = setTimeout(() => {
          hideDropdownMenu(dropdownMenu);
        }, 150);
      }

      // Helper function to hide a dropdown menu
      function hideDropdownMenu(menu) {
        const menuIsDeepLevel = menu.closest('.pawfect-dropdown-menu') !== null;
        const menuParentItem = menu.parentElement;

        if (menuIsDeepLevel) {
          // For 3rd level and beyond - horizontal slide
          menu.classList.add('pawfect-opacity-0', 'pawfect-translate-x-2', 'pawfect-pointer-events-none');
          menu.classList.remove('pawfect-opacity-100', 'pawfect-translate-x-0', 'pawfect-pointer-events-auto', 'pawfect-flip-left');
        } else {
          // For 2nd level - vertical slide
          menu.classList.add('pawfect-opacity-0', 'pawfect-translate-y-3', 'pawfect-pointer-events-none');
          menu.classList.remove('pawfect-opacity-100', 'pawfect-translate-y-0', 'pawfect-pointer-events-auto');

          // Reset arrow rotation for main menu items
          if (menuParentItem) {
            const arrow = menuParentItem.querySelector('svg');
            if (arrow) {
              arrow.classList.remove('pawfect-rotate-180');
            }
          }
        }

        // Also hide any nested dropdowns
        const nestedDropdowns = menu.querySelectorAll('.pawfect-dropdown-menu');
        nestedDropdowns.forEach(nestedMenu => {
          hideDropdownMenu(nestedMenu);
        });
      }

      // Event listeners for hover - only on the direct link, not the entire item
      const mainLink = item.querySelector(':scope > a, :scope > .pawfect-nav-link, :scope > .pawfect-dropdown-link');
      if (mainLink) {
        mainLink.addEventListener('mouseenter', showDropdown);

        // Hide dropdown when leaving the entire item (including dropdown)
        item.addEventListener('mouseleave', (e) => {
          // Only hide if we're actually leaving the entire dropdown area
          if (!item.contains(e.relatedTarget)) {
            hideDropdown();
          }
        });

        // Keep dropdown open when hovering over it
        dropdownMenu.addEventListener('mouseenter', () => clearTimeout(hideTimeout));
      }

      // Handle keyboard navigation – use focusin/focusout on parent <li>
      // so that Shift+Tab through submenu items works correctly.
      item.addEventListener('focusin', () => {
        showDropdown();
      });

      item.addEventListener('focusout', (e) => {
        // relatedTarget is the element receiving focus next.
        // If it is still inside this menu item, keep the dropdown open.
        if (e.relatedTarget && item.contains(e.relatedTarget)) {
          return;
        }
        // Small delay as a fallback for browsers that set relatedTarget late.
        setTimeout(() => {
          if (!item.contains(document.activeElement)) {
            hideDropdown();
          }
        }, 50);
      });

      // Handle dropdown item arrow-key / escape navigation
      const dropdownLinks = dropdownMenu.querySelectorAll('.pawfect-dropdown-link');
      dropdownLinks.forEach((link, index) => {
        link.addEventListener('keydown', (e) => {
          if (e.key === 'ArrowDown') {
            e.preventDefault();
            const nextLink = dropdownLinks[index + 1];
            if (nextLink) nextLink.focus();
          } else if (e.key === 'ArrowUp') {
            e.preventDefault();
            const prevLink = dropdownLinks[index - 1];
            if (prevLink) {
              prevLink.focus();
            } else if (mainLink) {
              mainLink.focus();
            }
          } else if (e.key === 'Escape') {
            hideDropdown();
            if (mainLink) mainLink.focus();
          }
        });
      });

      // Handle main link keyboard navigation
      if (mainLink) {
        mainLink.addEventListener('keydown', (e) => {
          if (e.key === 'ArrowDown' && dropdownLinks.length > 0) {
            e.preventDefault();
            showDropdown();
            dropdownLinks[0].focus();
          } else if (e.key === 'Escape') {
            hideDropdown();
          }
        });
      }
    }
  });
}

//=========================
// Mobile Drawer Toggle with Enhanced Transitions
//=========================
document.addEventListener("DOMContentLoaded", function () {
  const drawer = document.getElementById("pawfect-mobile-drawer");
  const closeBtn = document.getElementById("pawfect-menu-close");

  // Get all mobile menu open buttons (both normal and sticky header)
  const openBtns = document.querySelectorAll("#pawfect-menu-open");

  // Create backdrop element
  let backdrop = document.querySelector('.pawfect-mobile-backdrop');
  if (!backdrop) {
    backdrop = document.createElement('div');
    backdrop.className = 'pawfect-mobile-backdrop';
    document.body.appendChild(backdrop);
  }

  function openMobileMenu() {
    if (drawer) {
      // Prevent body scroll
      document.body.style.overflow = 'hidden';

      // Show backdrop
      backdrop.classList.add('active');

      // Show drawer with smooth animation
      drawer.classList.remove("pawfect--translate-x-full");
      drawer.classList.add("pawfect-translate-x-0");

      // Focus management for accessibility
      closeBtn?.focus();
    }
  }

  function closeMobileMenu() {
    if (drawer) {
      // Restore body scroll
      document.body.style.overflow = '';

      // Hide backdrop
      backdrop.classList.remove('active');

      // Hide drawer with smooth animation
      drawer.classList.add("pawfect--translate-x-full");
      drawer.classList.remove("pawfect-translate-x-0");
    }
  }

  if (drawer && openBtns.length > 0 && closeBtn) {
    // Open menu - attach to all open buttons (normal and sticky)
    openBtns.forEach(openBtn => {
      openBtn.addEventListener("click", openMobileMenu);
    });

    // Close menu
    closeBtn.addEventListener("click", closeMobileMenu);

    // Close menu when clicking backdrop
    backdrop.addEventListener("click", closeMobileMenu);

    // Close menu with Escape key
    document.addEventListener("keydown", function (e) {
      if (e.key === "Escape" && drawer.classList.contains("pawfect-translate-x-0")) {
        closeMobileMenu();
      }
    });

    // Mobile submenu toggles - Fixed to allow nested submenus
    const mobileSubmenuToggles = drawer.querySelectorAll('.pawfect-mobile-submenu-toggle');

    // Helper: set tabindex on all focusable elements inside a submenu
    function setSubmenuFocusability(submenu, focusable) {
      const focusableEls = submenu.querySelectorAll('a, button, input, select, textarea, [tabindex]');
      focusableEls.forEach(el => {
        if (focusable) {
          el.removeAttribute('tabindex');
        } else {
          el.setAttribute('tabindex', '-1');
        }
      });
    }

    // On init: make all closed submenu items unfocusable
    drawer.querySelectorAll('.pawfect-mobile-submenu').forEach(submenu => {
      if (!submenu.classList.contains('active')) {
        setSubmenuFocusability(submenu, false);
      }
    });

    mobileSubmenuToggles.forEach(toggle => {
      toggle.addEventListener('click', function (e) {
        e.preventDefault();
        e.stopPropagation();

        const menuItem = this.closest('.pawfect-mobile-menu-item');
        const submenu = menuItem.querySelector('.pawfect-mobile-submenu');

        if (submenu) {
          // Toggle current submenu
          const isExpanding = !submenu.classList.contains('active');
          submenu.classList.toggle('active');
          this.classList.toggle('rotated');

          // Update aria-expanded for accessibility
          this.setAttribute('aria-expanded', isExpanding ? 'true' : 'false');

          // Update tabindex on submenu children
          setSubmenuFocusability(submenu, isExpanding);

          // Only close sibling submenus at the same level, not parent/child submenus
          const parentSubmenu = menuItem.closest('.pawfect-mobile-submenu');
          let siblingContainer;

          if (parentSubmenu) {
            // This is a nested submenu - only close siblings within the same parent
            siblingContainer = parentSubmenu;
          } else {
            // This is a top-level submenu - only close other top-level submenus
            siblingContainer = drawer;
          }

          // Find sibling menu items at the same level
          const siblingMenuItems = siblingContainer.querySelectorAll(':scope > .pawfect-mobile-menu-list > .pawfect-mobile-menu-item, :scope > .pawfect-mobile-submenu-list > .pawfect-mobile-menu-item');

          siblingMenuItems.forEach(siblingItem => {
            if (siblingItem !== menuItem) {
              const siblingToggle = siblingItem.querySelector('.pawfect-mobile-submenu-toggle');
              const siblingSubmenu = siblingItem.querySelector('.pawfect-mobile-submenu');

              if (siblingToggle && siblingSubmenu) {
                siblingSubmenu.classList.remove('active');
                siblingToggle.classList.remove('rotated');
                siblingToggle.setAttribute('aria-expanded', 'false');
                // Make closed sibling submenu items unfocusable
                setSubmenuFocusability(siblingSubmenu, false);
              }
            }
          });
        }
      });
    });
  }

  //=========================
  // Featured Image + Scroll-Fade Animation
  //=========================
  const featureImgs = document.querySelectorAll(".feature-img");
  if (featureImgs.length > 0) {
    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            if (entry.target.classList.contains("feature-img")) {
              entry.target.classList.remove(
                "pawfect-opacity-0",
                "pawfect-translate-y-4"
              );
            }
            if (entry.target.classList.contains("pawfect-scroll-fade")) {
              entry.target.classList.add("pawfect-animate-fade-up");
            }
            observer.unobserve(entry.target);
          }
        });
      },
      { threshold: 0.3 }
    );

    featureImgs.forEach((el) => {
      el.classList.add(
        "pawfect-opacity-0",
        "pawfect-translate-y-4",
        "pawfect-transition-all"
      );
      observer.observe(el);
    });
  }

  //=========================
  // Section Scroll Fade
  //=========================
  const scrollFades = document.querySelectorAll(".pawfect-scroll-fade");
  if (scrollFades.length > 0) {
    const fadeObserver = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            entry.target.classList.add(
              "pawfect-opacity-100",
              "pawfect-translate-y-0"
            );
            entry.target.classList.remove(
              "pawfect-opacity-0",
              "pawfect-translate-y-6"
            );
            fadeObserver.unobserve(entry.target);
          }
        });
      },
      { threshold: 0.2 }
    );

    scrollFades.forEach((el) => {
      el.classList.add(
        "pawfect-opacity-0",
        "pawfect-translate-y-6",
        "pawfect-transition-all"
      );
      fadeObserver.observe(el);
    });
  }

  //=========================
  // Fade-Up Items (appear class)
  //=========================
  const fadeUps = document.querySelectorAll(".pawfect-fade-up");
  if (fadeUps.length > 0) {
    fadeUps.forEach((el) => {
      const fadeUpObserver = new IntersectionObserver(
        (entries) => {
          entries.forEach((entry) => {
            if (entry.isIntersecting) {
              entry.target.classList.add("appear");
              fadeUpObserver.unobserve(entry.target);
            }
          });
        },
        { threshold: 0.2 }
      );
      fadeUpObserver.observe(el);
    });
  }
});

//=========================
// Countdown Timer
//=========================
// Smooth Countdown Timer with transitions
document.addEventListener('DOMContentLoaded', function () {
  const countdownElements = {
    days: document.getElementById("cd-days"),
    hours: document.getElementById("cd-hours"),
    minutes: document.getElementById("cd-minutes"),
    seconds: document.getElementById("cd-seconds")
  };

  // Check if countdown elements exist
  if (!countdownElements.days || !countdownElements.hours ||
    !countdownElements.minutes || !countdownElements.seconds) {
    return;
  }

  // Get target date from customizer or use default
  const targetDateElement = document.querySelector('[data-countdown-date]');
  let endTime;

  if (targetDateElement && targetDateElement.dataset.countdownDate) {
    endTime = new Date(targetDateElement.dataset.countdownDate).getTime();
  } else {
    // Default fallback date (30 days from now)
    endTime = new Date().getTime() + (30 * 24 * 60 * 60 * 1000);
  }

  function smoothUpdateValue(element, newValue) {
    const currentValue = element.textContent;
    if (currentValue !== newValue) {
      element.textContent = newValue;
    }
  }

  function updateCountdown() {
    const now = new Date().getTime();
    const timeLeft = endTime - now;

    if (timeLeft <= 0) {
      smoothUpdateValue(countdownElements.days, "00");
      smoothUpdateValue(countdownElements.hours, "00");
      smoothUpdateValue(countdownElements.minutes, "00");
      smoothUpdateValue(countdownElements.seconds, "00");
      return;
    }

    const days = Math.floor(timeLeft / (1000 * 60 * 60 * 24));
    const hours = Math.floor((timeLeft % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((timeLeft % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((timeLeft % (1000 * 60)) / 1000);

    smoothUpdateValue(countdownElements.days, days.toString().padStart(2, '0'));
    smoothUpdateValue(countdownElements.hours, hours.toString().padStart(2, '0'));
    smoothUpdateValue(countdownElements.minutes, minutes.toString().padStart(2, '0'));
    smoothUpdateValue(countdownElements.seconds, seconds.toString().padStart(2, '0'));
  }

  // Start the countdown
  updateCountdown();
  setInterval(updateCountdown, 1000);
});

//=========================
// FAQ Toggle
//=========================
const faqToggles = document.querySelectorAll(".faq-toggle");
if (faqToggles.length > 0) {
  faqToggles.forEach((btn) => {
    btn.addEventListener("click", () => {
      const content = btn.nextElementSibling;
      const expanded = !content.classList.contains("pawfect-hidden");
      document
        .querySelectorAll(".faq-content")
        .forEach((el) => el.classList.add("pawfect-hidden"));
      if (!expanded) content.classList.remove("pawfect-hidden");
    });
  });
}

//=========================
// AOS Initialization with Enhanced Settings
//=========================
document.addEventListener("DOMContentLoaded", function () {
  if (typeof AOS !== "undefined") {
    AOS.init({
      duration: 800,
      once: true,
      offset: 100,
      easing: 'ease-out-cubic',
      delay: 0,
    });
  }

  // Refresh AOS on customizer selective refresh
  if (typeof wp !== 'undefined' && wp.customize && wp.customize.selectiveRefresh) {
    wp.customize.selectiveRefresh.bind('partial-content-rendered', function(placement) {
      if (typeof AOS !== 'undefined') {
        setTimeout(function() {
          AOS.refreshHard();
        }, 100);
      }
    });
  }
});


//=========================
// Testimonial Cards Randomized Layout
//=========================
document.addEventListener("DOMContentLoaded", () => {
  const isMobile = window.innerWidth < 640;
  if (isMobile) return;

  const cards = document.querySelectorAll(".testimonial-card");
  const container = document.getElementById("testimonial-cards");
  if (!cards.length || !container) return;

  const placed = [];
  const containerWidth = container.offsetWidth;
  const averageCardWidth = 260;

  function isOverlapping(newTop, newLeft) {
    return placed.some((pos) => {
      const dx = newLeft - pos.left;
      const dy = newTop - pos.top;
      const distance = Math.sqrt(dx * dx + dy * dy);
      return distance < 20;
    });
  }

  cards.forEach((card, index) => {
    let top,
      left,
      attempts = 0;

    do {
      top = index % 4 === 0 ? 0 : 5 + Math.random() * 75;
      const cardPercentWidth = (averageCardWidth / containerWidth) * 100;
      const maxLeft = 100 - cardPercentWidth - 2;
      left = index % 5 === 0 ? 0 : 5 + Math.random() * (maxLeft - 5);
      attempts++;
    } while (isOverlapping(top, left) && attempts < 30);

    placed.push({ top, left });

    const rotate = -4 + Math.random() * 8;
    card.style.top = `${top.toFixed(1)}%`;
    card.style.left = `${left.toFixed(1)}%`;
    card.style.transform = `rotate(${rotate.toFixed(1)}deg)`;
  });
});

// ===============================
// Enhanced Header Functionality
//=========================
document.addEventListener("DOMContentLoaded", () => {
  const header = document.querySelector(".pawfect-header");
  const cartBadge = document.querySelector(".pawfect-cart-badge");
  const searchModal = document.getElementById("pawfect-search-modal");
  const searchToggle = document.getElementById("pawfect-search-toggle");
  const searchClose = document.getElementById("pawfect-search-close");
  const searchInput = document.getElementById("pawfect-search-input");
  const searchResults = document.getElementById("pawfect-search-results");

  // Header scroll effect - ONLY for sticky-enabled headers
  let lastScrollY = 0;
  let ticking = false;

  function handleScroll() {
    // Only apply scroll effects to sticky-enabled headers
    if (header && header.classList.contains('pawfect-sticky-enabled')) {
      lastScrollY = window.scrollY;

      if (!ticking) {
        requestAnimationFrame(updateHeader);
        ticking = true;
      }
    }
  }

  function updateHeader() {
    const normalLayout = header.querySelector('.pawfect-sticky-normal-layout');
    const navRow = header.querySelector('.pawfect-sticky-nav-row');
    const scrolledLayout = header.querySelector('.pawfect-sticky-scrolled-layout');

    if (lastScrollY > 100) {
      // Add sticky class and scrolled class on scroll
      if (!header.classList.contains("pawfect-sticky-header")) {
        header.classList.add("pawfect-sticky-header");
        header.classList.add("pawfect-scrolled");

        // Hide original layout and show scrolled layout
        if (normalLayout) normalLayout.style.display = 'none';
        if (navRow) navRow.style.display = 'none';
        if (scrolledLayout) scrolledLayout.style.display = 'flex';
      }
    } else {
      // Remove sticky class and scrolled class when at top
      if (header.classList.contains("pawfect-sticky-header")) {
        header.classList.remove("pawfect-sticky-header");
        header.classList.remove("pawfect-scrolled");

        // Show original layout and hide scrolled layout
        if (normalLayout) normalLayout.style.display = 'grid';
        if (navRow) navRow.style.display = 'block';
        if (scrolledLayout) scrolledLayout.style.display = 'none';
      }
    }

    ticking = false;
  }

  // Add scroll listener
  window.addEventListener("scroll", handleScroll);

  // Professional Search Modal
  let lastFocusedElement = null;

  function openSearchModal() {
    if (searchModal) {
      // Show the modal
      searchModal.style.display = "block";
      searchModal.classList.remove("pawfect-pointer-events-none");

      // Force reflow
      searchModal.offsetHeight;

      // Animate in
      searchModal.classList.remove("pawfect-opacity-0", "pawfect-invisible");
      const modalContent = searchModal.querySelector("#pawfect-search-modal-content");
      if (modalContent) {
        modalContent.classList.remove("pawfect-scale-95");
        modalContent.classList.add("pawfect-scale-100");
      }

      document.body.style.overflow = "hidden";
      setTimeout(() => {
        if (searchInput) searchInput.focus();
      }, 300);
    }
  }

  function closeSearchModal() {
    if (searchModal) {
      // Animate out
      searchModal.classList.add("pawfect-opacity-0", "pawfect-invisible");
      searchModal.classList.add("pawfect-pointer-events-none");
      const modalContent = searchModal.querySelector("#pawfect-search-modal-content");
      if (modalContent) {
        modalContent.classList.add("pawfect-scale-95");
        modalContent.classList.remove("pawfect-scale-100");
      }

      document.body.style.overflow = "";

      // Hide after animation
      setTimeout(() => {
        searchModal.style.display = "none";
      }, 300);

      if (searchInput) {
        searchInput.value = "";
      }
      showDefaultSearchState();

      // Return focus to the element that triggered the modal
      if (lastFocusedElement) {
        lastFocusedElement.focus();
      }
    }
  }

  function showDefaultSearchState() {
    searchResults.innerHTML = `
      <div class="pawfect-p-6 pawfect-text-center pawfect-text-gray-500">

        <svg class="pawfect-w-12 pawfect-h-12 pawfect-mx-auto pawfect-mb-4 pawfect-text-gray-300" xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor" viewBox="0 0 256 256">
            <path d="M226.83,221.17l-52.7-52.7a84.1,84.1,0,1,0-5.66,5.66l52.7,52.7a4,4,0,0,0,5.66-5.66ZM36,112a76,76,0,1,1,76,76A76.08,76.08,0,0,1,36,112Z"></path>
        </svg>
        <p>${pawfect_i18n('search_placeholder', 'Start typing to search for products...')}</p>
      </div>
    `;
  }

  // Professional Search functionality
  let searchTimeout;
  function performSearch(query) {
    if (query.length < 2) {
      showDefaultSearchState();
      return;
    }

    // Show loading state
    searchResults.innerHTML = `
      <div class="pawfect-p-6 pawfect-text-center">
        <div class="pawfect-animate-spin pawfect-rounded-full pawfect-h-8 pawfect-w-8 pawfect-border-b-2 pawfect-border-pawfect-primary pawfect-mx-auto"></div>
        <p class="pawfect-mt-2 pawfect-text-gray-500">${pawfect_i18n('searching', 'Searching...')}</p>
      </div>
    `;

    // Real AJAX search
    if (typeof pawfect_ajax !== 'undefined') {
      const formData = new FormData();
      formData.append('action', 'pawfect_product_search');
      formData.append('search_term', query);
      formData.append('nonce', pawfect_ajax.search_nonce);

      fetch(pawfect_ajax.ajax_url, {
        method: 'POST',
        body: formData
      })
        .then(response => response.text())
        .then(data => {
          searchResults.innerHTML = data;
        })
        .catch(error => {
          console.error('Search error:', error);
          searchResults.innerHTML = `
          <div class="pawfect-p-6 pawfect-text-center pawfect-text-gray-500">
            <p>${pawfect_i18n('search_unavailable', 'Search temporarily unavailable. Please try again.')}</p>
          </div>
        `;
        });
    } else {
      // Fallback for when AJAX is not available
      searchResults.innerHTML = `
        <div class="pawfect-p-6 pawfect-text-center pawfect-text-gray-500">
          <p>${pawfect_i18n('search_requires_woo', 'Search functionality requires WooCommerce to be active.')}</p>
        </div>
      `;
    }
  }

  // Event listeners - handle multiple search toggles
  const searchToggles = document.querySelectorAll(".pawfect-search-toggle");
  searchToggles.forEach(toggle => {
    toggle.addEventListener("click", (e) => {
      e.preventDefault();
      e.stopPropagation();
      lastFocusedElement = toggle;
      openSearchModal();
    });
  });

  if (searchClose) {
    searchClose.addEventListener("click", (e) => {
      e.preventDefault();
      e.stopPropagation();
      closeSearchModal();
    });
  }

  if (searchModal) {
    searchModal.addEventListener("click", (e) => {
      // Close if clicking on the backdrop (not the modal content)
      if (e.target === searchModal) {
        closeSearchModal();
      }
    });
  }

  if (searchInput) {
    searchInput.addEventListener("input", (e) => {
      clearTimeout(searchTimeout);
      searchTimeout = setTimeout(() => performSearch(e.target.value), 300);
    });

    searchInput.addEventListener("keydown", (e) => {
      if (e.key === "Escape") {
        closeSearchModal();
      }
    });
  }

  // Global escape key listener and keyboard focus trapping for search modal

  document.addEventListener("keydown", (e) => {
    // Handle Escape key
    if (e.key === "Escape" && searchModal && !searchModal.classList.contains("pawfect-invisible")) {
      closeSearchModal();
      return;
    }

    // Handle Tab key for focus trapping within modal
    if (e.key === "Tab" && searchModal && !searchModal.classList.contains("pawfect-invisible")) {
      // Get all focusable elements within the modal
      const focusableElements = searchModal.querySelectorAll(
        'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
      );
      const focusableArray = Array.from(focusableElements).filter(el => {
        return el.offsetParent !== null && !el.disabled;
      });

      if (focusableArray.length === 0) return;

      const firstElement = focusableArray[0];
      const lastElement = focusableArray[focusableArray.length - 1];

      // If shift+tab on first element, move to last element
      if (e.shiftKey && document.activeElement === firstElement) {
        e.preventDefault();
        lastElement.focus();
      }
      // If tab on last element, move to first element
      else if (!e.shiftKey && document.activeElement === lastElement) {
        e.preventDefault();
        firstElement.focus();
      }
      // If focus is outside modal, bring it back to first element
      else if (!searchModal.contains(document.activeElement)) {
        e.preventDefault();
        firstElement.focus();
      }
    }
  });

  // Cart functionality
  function updateCartCount(count = 0) {
    if (cartBadge) {
      cartBadge.textContent = count;
      if (count > 0) {
        cartBadge.parentElement.classList.add("pawfect-cart-has-items");
        cartBadge.classList.remove("pawfect-scale-0");
        cartBadge.classList.add("pawfect-scale-100");
      } else {
        cartBadge.parentElement.classList.remove("pawfect-cart-has-items");
        cartBadge.classList.add("pawfect-scale-0");
        cartBadge.classList.remove("pawfect-scale-100");
      }
    }
  }

  // Initialize cart count
  if (typeof wc_cart_fragments_params !== 'undefined') {
    // WooCommerce is active, cart count will be handled by WooCommerce

    // Handle add to cart button updates
    document.addEventListener('added_to_cart', function (e) {
      // Update button text for the specific product
      const productId = e.detail.productId;
      const buttons = document.querySelectorAll(`[data-product-id="${productId}"] .pawfect-btn-text`);
      buttons.forEach(button => {
        button.textContent = pawfect_i18n('added_to_cart', 'Added to Cart');
        button.closest('.pawfect-add-to-cart-btn').classList.add('pawfect-added-to-cart');
      });
    });

    // Style WooCommerce View Cart buttons
    document.body.addEventListener('wc_cart_button_updated', function (e) {
      // Find and style any new "View Cart" buttons
      const viewCartButtons = document.querySelectorAll('.added_to_cart.wc-forward');
      viewCartButtons.forEach(button => {
        if (!button.classList.contains('pawfect-btn')) {
          button.classList.add('pawfect-btn');
          button.style.marginTop = '0.5rem';
          button.style.display = 'block';
          button.style.width = '100%';
        }
      });
    });

    // Handle cart fragments update
    document.body.addEventListener('wc_fragments_refreshed', function () {
      // Cart fragments have been updated, cart count should be current
      // Re-initialize cart dropdown functionality for new elements
      initializeCartDropdowns();
    });

    // Listen for WooCommerce add to cart events
    jQuery(document.body).on('added_to_cart', function (event, fragments, cart_hash) {
      // Fragments are automatically updated by WooCommerce
    });

    // Listen for remove from cart events
    jQuery(document.body).on('removed_from_cart', function (event, fragments, cart_hash) {
      // Fragments are automatically updated by WooCommerce
    });
  } else {
    updateCartCount(0);
  }

  // AJAX Add to Cart functionality
  document.addEventListener('click', function (e) {
    if (e.target.closest('.pawfect-ajax-add-to-cart')) {
      e.preventDefault();

      const button = e.target.closest('.pawfect-ajax-add-to-cart');
      const buttonText = button.querySelector('.pawfect-btn-text');
      const productId = button.getAttribute('data-product-id');
      const quantity = button.getAttribute('data-quantity') || 1;

      // Don't add if already added
      if (buttonText && buttonText.textContent === pawfect_i18n('added_to_cart', 'Added to Cart')) {
        return;
      }

      // Show loading state
      if (buttonText) {
        buttonText.textContent = pawfect_i18n('adding', 'Adding...');
      }
      button.disabled = true;
      button.classList.add('pawfect-loading');

      // AJAX Add to Cart
      const formData = new FormData();
      formData.append('action', 'woocommerce_add_to_cart');
      formData.append('product_id', productId);
      formData.append('quantity', quantity);

      fetch(wc_add_to_cart_params.ajax_url, {
        method: 'POST',
        body: formData
      })
        .then(response => response.json())
        .then(data => {
          if (data.error) {
            // Handle error
            if (buttonText) {
              buttonText.textContent = pawfect_i18n('error_try_again', 'Error - Try Again');
            }
            setTimeout(() => {
              if (buttonText) {
                buttonText.textContent = pawfect_i18n('add_to_cart', 'Add to Cart');
              }
              button.disabled = false;
              button.classList.remove('pawfect-loading');
            }, 2000);
          } else {
            // Success
            if (buttonText) {
              buttonText.textContent = pawfect_i18n('added_to_cart', 'Added to Cart');
            }
            button.classList.remove('pawfect-loading');
            button.classList.add('pawfect-added-to-cart');

            // Update cart fragments
            if (data.fragments) {
              Object.keys(data.fragments).forEach(key => {
                const elements = document.querySelectorAll(key);
                elements.forEach(element => {
                  element.outerHTML = data.fragments[key];
                });
              });
            }

            // Trigger custom event
            const event = new CustomEvent('added_to_cart', {
              detail: { productId: productId, button: button }
            });
            document.dispatchEvent(event);
          }
        })
        .catch(error => {
          console.error('Add to cart error:', error);
          if (buttonText) {
            buttonText.textContent = pawfect_i18n('error_try_again', 'Error - Try Again');
          }
          setTimeout(() => {
            if (buttonText) {
              buttonText.textContent = pawfect_i18n('add_to_cart', 'Add to Cart');
            }
            button.disabled = false;
            button.classList.remove('pawfect-loading');
          }, 2000);
        });
    }
  });

  // Header background toggle on dropdown menu hover (homepage only)
  if (document.body.classList.contains("home")) {
    const dropdownItems = document.querySelectorAll(".pawfect-header .pawfect-has-dropdown");

    // Add hover effect only to dropdown menu items on homepage
    if (dropdownItems.length > 0 && header) {
      dropdownItems.forEach(item => {
        item.addEventListener("mouseenter", () => {
          header.classList.add("pawfect-menu-hovered");
        });

        item.addEventListener("mouseleave", () => {
          header.classList.remove("pawfect-menu-hovered");
        });
      });
    }
  }
});

// ===============================
// Enhanced Hero Slider with Smooth Transitions
// ===============================
document.addEventListener("DOMContentLoaded", function () {
  const heroEl = document.querySelector(".pawfect-hero-swiper");

  if (heroEl && typeof Swiper !== "undefined") {
    // Get options from PHP
    const options =
      typeof pawfectHeroSliderOptions !== "undefined"
        ? pawfectHeroSliderOptions
        : {
          autoplay: true,
          autoplayDelay: 5000,
          pauseOnHover: true,
          infiniteLoop: true,
          speed: 1000,
          effect: "fade",
        };

    // Count slides to determine if loop should be enabled
    const slideCount = heroEl.querySelectorAll('.swiper-slide').length;
    const enableLoop = options.infiniteLoop !== false && slideCount > 2;

    // Initialize Swiper
    const heroSwiper = new Swiper(heroEl, {
      loop: enableLoop,
      effect: options.effect,
      fadeEffect: { crossFade: true },
      autoplay: options.autoplay
        ? {
          delay: options.autoplayDelay,
          disableOnInteraction: false,
          pauseOnMouseEnter: options.pauseOnHover !== false,
        }
        : false,
      speed: options.speed,
      pagination: {
        el: ".swiper-pagination",
        type: "bullets",
        clickable: true,
        renderBullet: function (index, className) {
          return `<span class="${className} pawfect-pagination-bullet"><span class="pawfect-bullet-fill"></span></span>`;
        },
      },
      navigation: {
        nextEl: ".swiper-button-next",
        prevEl: ".swiper-button-prev",
      },
      keyboard: {
        enabled: true,
        onlyInViewport: true,
      },
      on: {
        init: function () {
          setTimeout(() => {
            startSlideAnimations();
            startKenBurnsEffect();
          }, 100);
        },
        slideChangeTransitionStart: function () {
          // Reset all slide content immediately
          resetAllSlideAnimations();
        },
        slideChangeTransitionEnd: function () {
          // Start animations for new slide
          resetBulletAnimations();
          setTimeout(() => {
            startSlideAnimations();
            startKenBurnsEffect();
          }, 100);
        },
      },
    });

    // Reset all slide animations
    function resetAllSlideAnimations() {
      document.querySelectorAll(".pawfect-slide-content").forEach((content) => {
        content.style.opacity = "0";
        content.style.transform = "translateY(30px)";
        content.style.transition = "none";
      });

      // Reset titles and CTAs
      document
        .querySelectorAll(".pawfect-slide-title, .pawfect-slide-cta")
        .forEach((element) => {
          element.style.opacity = "0";
          element.style.transform = "translateY(30px)";
          element.style.transition = "none";
        });

      // Reset hero text animations - remove from all slides
      document.querySelectorAll(".swiper-slide .pawfect-hero-animate").forEach((element) => {
        // Add a class to temporarily disable animations
        element.classList.add("pawfect-hero-reset");
      });
    }

    // Subtle bullet transitions (no annoying animations)
    function resetBulletAnimations() {
      // Remove all animations - just use CSS transitions
      document.querySelectorAll(".pawfect-bullet-fill").forEach((el) => {
        el.style.animation = "none";
      });
    }

    // Start slide content animations
    function startSlideAnimations() {
      const activeSlide = heroEl.querySelector(".swiper-slide-active");
      if (activeSlide) {
        const content = activeSlide.querySelector(".pawfect-slide-content");
        const title = activeSlide.querySelector(".pawfect-slide-title");
        const cta = activeSlide.querySelector(".pawfect-slide-cta");

        if (content) {
          // Animate content container
          setTimeout(() => {
            content.style.transition = "all 1s cubic-bezier(0.4, 0, 0.2, 1)";
            content.style.opacity = "1";
            content.style.transform = "translateY(0)";
          }, 300);

          // Animate title with delay
          if (title) {
            setTimeout(() => {
              title.style.transition = "all 1.2s cubic-bezier(0.4, 0, 0.2, 1)";
              title.style.transform = "translateY(0) scale(1)";
            }, 500);
          }

          // Animate CTA with delay
          if (cta) {
            setTimeout(() => {
              cta.style.transition = "all 0.8s cubic-bezier(0.4, 0, 0.2, 1)";
              cta.style.opacity = "1";
              cta.style.transform = "translateY(0)";
            }, 800);
          }
        }

        // Trigger hero text animations - only for active slide
        const heroAnimateElements = activeSlide.querySelectorAll(
          ".pawfect-hero-animate"
        );
        if (heroAnimateElements.length > 0) {
          heroAnimateElements.forEach((element) => {
            // Remove reset class to let CSS animations work
            element.classList.remove("pawfect-hero-reset");
          });
        }
      }
    }

    // Ken Burns effect for background images
    function startKenBurnsEffect() {
      const activeSlide = heroEl.querySelector(".swiper-slide-active");
      if (activeSlide) {
        const bgImage = activeSlide.querySelector(".pawfect-bg-cover");
        if (bgImage) {
          // Reset scale
          bgImage.style.transform = "scale(1.05)";

          // Start Ken Burns effect
          setTimeout(() => {
            bgImage.style.transform = "scale(1.1)";
          }, 100);
        }
      }
    }

    // Pause autoplay on hover (only if autoplay is enabled and pauseOnHover is true)
    if (options.autoplay && options.pauseOnHover !== false) {
      heroEl.addEventListener("mouseenter", () => {
        if (heroSwiper.autoplay && heroSwiper.autoplay.running) {
          heroSwiper.autoplay.stop();
        }
      });

      heroEl.addEventListener("mouseleave", () => {
        if (heroSwiper.autoplay && options.autoplay) {
          heroSwiper.autoplay.start();
        }
      });
    }
  }
});

// ===============================
// Go to Top Button
// ===============================
document.addEventListener("DOMContentLoaded", function () {
  // Create go to top button
  const goToTopBtn = document.createElement("button");
  goToTopBtn.innerHTML = `
       
        <svg class="pawfect-w-6 pawfect-h-6"  viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg"><g id="SVGRepo_bgCarrier" stroke-width="0"></g><g id="SVGRepo_tracerCarrier" stroke-linecap="round" stroke-linejoin="round"></g><g id="SVGRepo_iconCarrier"> <path d="M17 15L12 10L7 15" stroke="#ffffff" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"></path> </g></svg>
    `;
  goToTopBtn.className =
    "pawfect-go-to-top pawfect-fixed pawfect-bottom-8 pawfect-right-8 pawfect-w-12 pawfect-h-12 pawfect-bg-pawfect-primary pawfect-text-white pawfect-rounded-full pawfect-shadow-lg pawfect-flex pawfect-items-center pawfect-justify-center pawfect-transition-all pawfect-duration-300 pawfect-opacity-0 pawfect-pointer-events-none pawfect-z-50 hover:pawfect-bg-pawfect-primary hover:pawfect-scale-110 hover:pawfect-shadow-xl";
  goToTopBtn.setAttribute("aria-label", pawfect_i18n('go_to_top', 'Go to top'));

  document.body.appendChild(goToTopBtn);

  // Show/hide button based on scroll position
  function toggleGoToTopButton() {
    if (window.scrollY > 300) {
      goToTopBtn.classList.remove(
        "pawfect-opacity-0",
        "pawfect-pointer-events-none"
      );
      goToTopBtn.classList.add("pawfect-opacity-100");
    } else {
      goToTopBtn.classList.add(
        "pawfect-opacity-0",
        "pawfect-pointer-events-none"
      );
      goToTopBtn.classList.remove("pawfect-opacity-100");
    }
  }

  // Smooth scroll to top
  function scrollToTop() {
    window.scrollTo({
      top: 0,
      behavior: "smooth",
    });
  }

  // Event listeners
  window.addEventListener("scroll", toggleGoToTopButton);
  goToTopBtn.addEventListener("click", scrollToTop);

  // Initial check
  toggleGoToTopButton();


  const productEl = document.querySelector(".pawfect-product-swiper");

  if (productEl && typeof Swiper !== "undefined") {
    // Count slides to determine if loop should be enabled
    const productSlideCount = productEl.querySelectorAll('.swiper-slide').length;
    const enableProductLoop = productSlideCount > 4; // Need more than slidesPerView for loop

    const productSwiper = new Swiper(productEl, {
      loop: enableProductLoop,
      spaceBetween: 20,
      slidesPerView: 1, // Default for mobile
      autoplay: pawfectWooOptions?.autoplay || false,
      breakpoints: {
        // Mobile phones (up to 480px)
        320: {
          slidesPerView: 1,
          spaceBetween: 15
        },
        // Small tablets (481px to 640px)
        481: {
          slidesPerView: 2,
          spaceBetween: 20
        },
        // Tablets (641px to 1023px)
        641: {
          slidesPerView: 2,
          spaceBetween: 25
        },
        // Small desktop (1024px to 1199px)
        1024: {
          slidesPerView: 3,
          spaceBetween: 30
        },
        // Large desktop (1200px and up)
        1200: {
          slidesPerView: pawfectWooOptions?.slidesPerView || 4,
          spaceBetween: 30
        },
      },
      pagination: {
        el: ".swiper-pagination",
        type: "bullets",
        clickable: true,
        renderBullet: function (index, className) {
          return `<span class="${className} pawfect-pagination-bullet"><span class="pawfect-bullet-fill"></span></span>`;
        },
      },
      navigation: {
        nextEl: ".swiper-button-next",
        prevEl: ".swiper-button-prev",
      },
    });

    productSwiper.on("slideChange", () => {
      // Remove annoying animations - just use CSS transitions
      document.querySelectorAll(".pawfect-bullet-fill").forEach((el) => {
        el.style.animation = "none";
      });
    });
  }
});

document.addEventListener("DOMContentLoaded", function () {
  const container = document.querySelector(".pawfect-happy-customers-swiper");
  if (
    !container ||
    typeof Swiper === "undefined" ||
    typeof pawfectTestimonialOptions === "undefined"
  )
    return;

  // Count slides to determine if loop should be enabled
  const testimonialSlideCount = container.querySelectorAll('.swiper-slide').length;
  const enableTestimonialLoop = testimonialSlideCount > 2;

  new Swiper(container, {
    loop: enableTestimonialLoop,
    ...pawfectTestimonialOptions,
    pagination: {
      el: ".pawfect-testimonial-pagination",
      type: "fraction",
    },
    navigation: {
      nextEl: ".pawfect-testimonial-next",
      prevEl: ".pawfect-testimonial-prev",
    },
  });

});
