if (window.history && 'scrollRestoration' in window.history) {
  window.history.scrollRestoration = 'manual';
}

const CART_STORAGE_KEY = 'petcare-cart';
const AUTH_MODAL_STORAGE_KEY = 'petcare-auth-modal-seen';
const PAYMENT_THEME_CLASS_MAP = {
  'tarjeta-credito': 'pay-credit',
  'tarjeta-debito': 'pay-debit',
  transferencia: 'pay-transfer',
  'mercado-pago': 'pay-mercado',
  paypal: 'pay-paypal'
};
const PRODUCT_CATALOG = {
  alimento: {
    title: 'Alimento premium',
    price: 129,
    description: 'Fórmula completa para perros con proteínas esenciales.',
    delivery: '24 horas'
  },
  cuidados: {
    title: 'Cuidados diarios',
    price: 89,
    description: 'Shampoos y cepillos especialmente pensados para el pelaje de perros.',
    delivery: '24 horas'
  },
  juguetes: {
    title: 'Juguetes interactivos',
    price: 69,
    description: 'Material resistente ideal para perros activos.',
    delivery: '48 horas'
  },
  accesorios: {
    title: 'Accesorios para pasear',
    price: 99,
    description: 'Collares, correas y arneses para paseos cómodos y seguros con perros.',
    delivery: '24 horas'
  },
  actividad: {
    title: 'Actividad y ejercicio',
    price: 75,
    description: 'Accesorios para que tu perro pueda jugar y entrenar diario.',
    delivery: '48 horas'
  },
  descanso: {
    title: 'Descanso y comodidad',
    price: 249,
    description: 'Cama ortopédica + manta térmica + snack relajante.',
    delivery: '24 horas'
  },
  'snacks-perros': {
    title: 'Snacks para perros',
    price: 35,
    description: 'Snacks para reforzar el día a día.',
    delivery: '24 horas'
  },
  'premios-entrenamiento': {
    title: 'Premios de entrenamiento',
    price: 28,
    description: 'Premios pequeños para reforzar comportamientos.',
    delivery: '24 horas'
  },
  'comedero-antideslizante': {
    title: 'Comedero antideslizante',
    price: 45,
    description: 'Comedero estable para una comida tranquila.',
    delivery: '24 horas'
  },
  'cepillos-suaves': {
    title: 'Cepillos suaves',
    price: 19,
    description: 'Cepillos suaves para un cuidado diario.',
    delivery: '24 horas'
  },
  'toallitas-humedas': {
    title: 'Toallitas húmedas',
    price: 15,
    description: 'Toallitas prácticas para limpieza rápida.',
    delivery: '24 horas'
  },
  'acondicionador-pet': {
    title: 'Acondicionador pet',
    price: 22,
    description: 'Acondicionador para un pelaje más suave.',
    delivery: '24 horas'
  },
  'pelotas-goma': {
    title: 'Pelotas de goma',
    price: 17,
    description: 'Pelotas resistentes y seguras.',
    delivery: '24 horas'
  },
  'juguetes-morder': {
    title: 'Juguetes para morder',
    price: 24,
    description: 'Juguetes para masticar y entretener.',
    delivery: '24 horas'
  },
  'lazos-juego': {
    title: 'Lazos de juego',
    price: 14,
    description: 'Juegos simples para práctica y diversión.',
    delivery: '24 horas'
  },
  'cinturon-paseo': {
    title: 'Cinturón de paseo',
    price: 29,
    description: 'Accesorio cómodo para paseos diarios.',
    delivery: '24 horas'
  },
  'mochila-paseos': {
    title: 'Mochila para paseos',
    price: 34,
    description: 'Mochila práctica para llevar tus essentials.',
    delivery: '24 horas'
  },
  'bolsas-reciclables': {
    title: 'Bolsas reciclables',
    price: 12,
    description: 'Bolsas simples para limpiar después del paseo.',
    delivery: '24 horas'
  },
  'set-correr': {
    title: 'Set para correr',
    price: 39,
    description: 'Kit básico para ejercicio y movimiento.',
    delivery: '24 horas'
  },
  'pelotas-sonido': {
    title: 'Pelotas con sonido',
    price: 21,
    description: 'Pelotas interactivas con sonido.',
    delivery: '24 horas'
  },
  'entrenadores-obediencia': {
    title: 'Entrenadores de obediencia',
    price: 31,
    description: 'Accesorios para adiestramiento guiado.',
    delivery: '24 horas'
  },
  'camas-pequenas': {
    title: 'Camas pequeñas',
    price: 60,
    description: 'Camas compactas para espacio reducido.',
    delivery: '24 horas'
  },
  'almohadas-descanso': {
    title: 'Almohadas de descanso',
    price: 25,
    description: 'Almohadas suaves para mayor relax.',
    delivery: '24 horas'
  },
  'mantas-antiestres': {
    title: 'Mantas antiestrés',
    price: 18,
    description: 'Mantas suaves para calmar y relajar.',
    delivery: '24 horas'
  }
};

function readCart() {
  try {
    const parsed = JSON.parse(localStorage.getItem(CART_STORAGE_KEY) || '[]');
    return Array.isArray(parsed) ? parsed : [];
  } catch {
    return [];
  }
}

function writeCart(cart) {
  try {
    localStorage.setItem(CART_STORAGE_KEY, JSON.stringify(cart));
  } catch {
    // Ignore storage issues silently
  }
}

function formatMoney(value) {
  return new Intl.NumberFormat('es-PE', {
    style: 'currency',
    currency: 'PEN'
  }).format(value || 0);
}

function showCartToast() {
  let toast = document.getElementById('cart-toast');

  if (!toast) {
    toast = document.createElement('div');
    toast.id = 'cart-toast';
    toast.className = 'cart-toast';
    document.body.appendChild(toast);
  }

  toast.textContent = 'Producto añadido correctamente';
  toast.classList.add('visible');

  window.clearTimeout(showCartToast.timeoutId);
  showCartToast.timeoutId = window.setTimeout(function () {
    toast.classList.remove('visible');
  }, 1800);
}

function lockButtonForAdd(button, label) {
  if (!button || button.dataset.processing === 'true') {
    return false;
  }

  const previousLabel = button.textContent;
  button.dataset.processing = 'true';
  button.disabled = true;
  button.textContent = label || 'Añadido';

  window.setTimeout(function () {
    button.dataset.processing = 'false';
    button.disabled = false;
    button.textContent = previousLabel;
  }, 900);

  return true;
}

function getCartSummary() {
  const cart = readCart();
  const totalItems = cart.reduce(function (sum, item) {
    return sum + (Number(item.quantity) || 0);
  }, 0);
  const totalPrice = cart.reduce(function (sum, item) {
    const product = PRODUCT_CATALOG[item.key];
    return sum + ((product?.price || 0) * (Number(item.quantity) || 0));
  }, 0);

  return { cart, totalItems, totalPrice };
}

function syncCartSummary() {
  const summaryPanel = document.querySelector('.order-summary-panel');
  if (!summaryPanel) {
    return;
  }

  const { cart, totalItems, totalPrice } = getCartSummary();
  const quantityNode = summaryPanel.querySelector('strong');
  const totalNode = summaryPanel.querySelectorAll('strong')[1];
  const paymentNode = summaryPanel.querySelectorAll('strong')[2];

  if (quantityNode) {
    quantityNode.textContent = String(totalItems || 0).padStart(2, '0');
  }

  if (totalNode) {
    totalNode.textContent = formatMoney(totalPrice || 0);
  }

  if (paymentNode) {
    paymentNode.textContent = cart.length ? 'Online' : 'Online';
  }
}

function renderCartOrders() {
  const grid = document.querySelector('.orders-grid');
  if (!grid) {
    return;
  }

  const { cart } = getCartSummary();
  if (!cart.length) {
    grid.innerHTML = '';
    return;
  }

  const cards = cart.map(function (item, index) {
    const product = PRODUCT_CATALOG[item.key];
    const statusClass = index % 3 === 0 ? 'preparing' : index % 3 === 1 ? 'shipping' : 'delivered';
    const quantityText = (Number(item.quantity) || 1) + ' unidad' + ((Number(item.quantity) || 1) === 1 ? '' : 'es');

    return `
      <article class="order-card">
        <div class="order-card-top">
          <h3>${product?.title || 'Producto'}</h3>
          <span class="status-pill ${statusClass}">${quantityText}</span>
        </div>
        <p>${product?.description || 'Producto añadido desde el catálogo.'}</p>
        <ul class="order-meta">
          <li><strong>Precio:</strong> ${formatMoney(product?.price || 0)}</li>
          <li><strong>Entrega:</strong> ${product?.delivery || '24 horas'}</li>
        </ul>
        <button type="button" class="btn btn-secondary remove-cart-btn" data-key="${item.key}">Quitar del carrito</button>
      </article>
    `;
  });

  grid.innerHTML = cards.join('');

  const removeButtons = grid.querySelectorAll('.remove-cart-btn');
  removeButtons.forEach(function (button) {
    button.addEventListener('click', function () {
      const key = button.dataset.key;
      const cart = readCart();
      const filteredCart = cart.filter(function (item) {
        return item.key !== key;
      });

      writeCart(filteredCart);
      syncCartSummary();
      renderCartOrders();
    });
  });
}

function addCartItem(productKey) {
  const product = PRODUCT_CATALOG[productKey];
  if (!product) {
    return;
  }

  const cart = readCart();
  const existingProduct = cart.find(function (item) {
    return item.key === productKey;
  });

  if (existingProduct) {
    existingProduct.quantity += 1;
  } else {
    cart.push({
      key: productKey,
      quantity: 1
    });
  }

  writeCart(cart);
  syncCartSummary();
  renderCartOrders();
  showCartToast();
}

window.addEventListener('load', function () {
  window.scrollTo({ top: 0, left: 0, behavior: 'auto' });
});

document.addEventListener('DOMContentLoaded', function () {
  syncCartSummary();
  renderCartOrders();

  document.addEventListener('click', function (event) {
    const offerButton = event.target.closest('.offer-add-cart');
    if (offerButton) {
      event.preventDefault();
      event.stopPropagation();

      if (!lockButtonForAdd(offerButton, 'Añadido')) {
        return;
      }

      addCartItem(offerButton.dataset.offer);
      return;
    }

    const button = event.target.closest('.add-cart-btn, .detail-add-cart');
    if (!button) {
      return;
    }

    event.preventDefault();
    event.stopPropagation();

    if (!lockButtonForAdd(button, 'Añadido')) {
      return;
    }

    const card = button.closest('.product-card') || button.closest('.detail-product-card');
    const productKey = button.dataset.product || card?.dataset.product;
    if (!productKey) {
      return;
    }

    addCartItem(productKey);
  });

  const checkoutForm = document.querySelector('.checkout-form');
  if (checkoutForm) {
    const existingHidden = checkoutForm.querySelector('input[name="productos"]');
    if (!existingHidden) {
      const hiddenProducts = document.createElement('input');
      hiddenProducts.type = 'hidden';
      hiddenProducts.name = 'productos';
      checkoutForm.appendChild(hiddenProducts);
    }

    const totalInput = checkoutForm.querySelector('input[name="total"]');
    const productsInput = checkoutForm.querySelector('input[name="productos"]');
    const paymentSelect = checkoutForm.querySelector('select[name="metodo_pago"]');
    const checkoutCard = checkoutForm.closest('.checkout-card');
    const paymentSummary = document.querySelector('.order-summary-panel strong:nth-of-type(3)');
    const paymentPanels = checkoutForm.querySelectorAll('.payment-panel');

    const applyPaymentTheme = function () {
      if (!checkoutCard || !paymentSelect) {
        return;
      }

      const selectedMethod = paymentSelect.value;
      const themeClass = PAYMENT_THEME_CLASS_MAP[selectedMethod];

      checkoutCard.classList.remove('pay-credit', 'pay-debit', 'pay-transfer', 'pay-mercado', 'pay-paypal');
      if (themeClass) {
        checkoutCard.classList.add(themeClass);
      }

      if (paymentSummary) {
        paymentSummary.textContent = paymentSelect.options[paymentSelect.selectedIndex]?.text || 'Online';
      }
    };

    const applyPaymentPanels = function () {
      if (!paymentSelect) {
        return;
      }

      const selectedMethod = paymentSelect.value;

      paymentPanels.forEach(function (panel) {
        const isActive = panel.dataset.payment === selectedMethod;
        panel.classList.toggle('is-active', isActive);

        const inputs = panel.querySelectorAll('input, textarea, select');
        inputs.forEach(function (input) {
          input.required = isActive;
        });
      });
    };

    paymentSelect?.addEventListener('change', function () {
      applyPaymentTheme();
      applyPaymentPanels();
    });
    applyPaymentTheme();
    applyPaymentPanels();

    checkoutForm.addEventListener('submit', function () {
      const { cart, totalPrice } = getCartSummary();
      if (productsInput) {
        productsInput.value = JSON.stringify(cart);
      }
      if (totalInput) {
        totalInput.value = String(totalPrice || 0);
      }
    });
  }

  const authModal = document.getElementById('authModal');
  const continueCheckoutBtn = document.getElementById('continueCheckoutBtn');

  if (authModal) {
    const authModalSeen = sessionStorage.getItem(AUTH_MODAL_STORAGE_KEY) === '1';

    if (authModalSeen) {
      authModal.style.display = 'none';
      authModal.setAttribute('aria-hidden', 'true');
    } else {
      sessionStorage.setItem(AUTH_MODAL_STORAGE_KEY, '1');
    }
  }

  if (authModal && continueCheckoutBtn) {
    continueCheckoutBtn.addEventListener('click', function () {
      authModal.style.display = 'none';
      authModal.setAttribute('aria-hidden', 'true');

      const currentUrl = new URL(window.location.href);
      currentUrl.searchParams.delete('auth');
      currentUrl.searchParams.delete('mode');
      window.history.replaceState({}, document.title, currentUrl.pathname + currentUrl.search);
    });
  }

  const validateInput = function (input) {
    const value = input.value.trim();
    const type = input.dataset.type || '';
    let isValid = false;

    if (type === 'name') {
      isValid = /^[A-Za-zÁÉÍÓÚáéíóúÑñ ]+$/.test(value) && value.length >= 2;
    } else if (type === 'text') {
      isValid = value.length >= 2;
    } else if (type === 'email') {
      isValid = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
    } else if (type === 'phone') {
      isValid = value.length >= 8;
    } else if (type === 'password') {
      isValid = value.length >= 6;
    } else if (type === 'confirm-password') {
      const passwordField = document.querySelector('#registerForm input[data-type="password"]');
      isValid = Boolean(passwordField && value && value === passwordField.value.trim() && value.length >= 6);
    } else {
      isValid = value.length > 0;
    }

    input.classList.toggle('valid', isValid);
    input.classList.toggle('invalid', !isValid && value.length > 0);
    input.closest('.input-icon')?.classList.toggle('valid-input', isValid);
    input.closest('.input-icon')?.classList.toggle('invalid-input', !isValid && value.length > 0);

    return isValid;
  };

  const forms = document.querySelectorAll('.auth-form');
  forms.forEach(function (form) {
    form.addEventListener('submit', function (event) {
      event.preventDefault();
      const inputs = form.querySelectorAll('.validate-input');
      let allValid = true;

      inputs.forEach(function (input) {
        const valid = validateInput(input);
        if (!valid) {
          allValid = false;
        }
      });

      if (allValid) {
        form.classList.add('success-message');
        form.classList.remove('error-message');
      } else {
        form.classList.add('error-message');
        form.classList.remove('success-message');
      }

      if (allValid && form.id === 'loginForm') {
        form.submit();
      }

      if (allValid && form.id === 'registerForm') {
        form.submit();
      }
    });

    form.querySelectorAll('.validate-input').forEach(function (input) {
      input.addEventListener('input', function () {
        if (input.dataset.type === 'name') {
          input.value = input.value.replace(/\d/g, '');
        }
        validateInput(input);
      });
      input.addEventListener('blur', function () {
        validateInput(input);
      });
    });
  });

  const revealSelectors = [
    '.section-heading',
    '.stats-grid article',
    '.popular-card',
    '.story-copy',
    '.story-card',
    '.review-card',
    '.feature-copy',
    '.feature-image',
    '.cta-box',
    '.contact-box',
    '.order-card',
    '.order-summary-panel div',
    '.product-card',
    '.gallery-grid img',
    '.service-card',
    '.info-card'
  ];

  const revealItems = Array.from(document.querySelectorAll(revealSelectors.join(', ')));

  revealItems.forEach(function (item, index) {
    item.classList.add('reveal');
    item.style.transitionDelay = (index * 0.04) + 's';
  });

  const observerItems = document.querySelectorAll('.reveal');

  if ('IntersectionObserver' in window) {
    const observer = new IntersectionObserver(function (entries) {
      entries.forEach(function (entry) {
        if (entry.isIntersecting) {
          entry.target.classList.add('is-visible');
          observer.unobserve(entry.target);
        }
      });
    }, {
      threshold: 0.12
    });

    observerItems.forEach(function (item) {
      observer.observe(item);
    });
  } else {
    observerItems.forEach(function (item) {
      item.classList.add('is-visible');
    });
  }

  const heroVisual = document.querySelector('.hero-visual');
  if (heroVisual) {
    heroVisual.addEventListener('mousemove', function (event) {
      const rect = heroVisual.getBoundingClientRect();
      const offsetX = (event.clientX - rect.left) / rect.width - 0.5;
      const offsetY = (event.clientY - rect.top) / rect.height - 0.5;

      heroVisual.style.setProperty('--move-x', (offsetX * 10).toFixed(2) + 'px');
      heroVisual.style.setProperty('--move-y', (offsetY * 10).toFixed(2) + 'px');
    });

    heroVisual.addEventListener('mouseleave', function () {
      heroVisual.style.setProperty('--move-x', '0px');
      heroVisual.style.setProperty('--move-y', '0px');
    });
  }

  const parallaxItems = document.querySelectorAll('.parallax');
  const applyParallax = function () {
    const scrollY = window.scrollY;

    parallaxItems.forEach(function (item) {
      const depth = Number(item.dataset.depth || 0.12);
      const offset = scrollY * depth;
      item.style.setProperty('--parallax-y', offset.toFixed(2) + 'px');
    });
  };

  applyParallax();
  window.addEventListener('scroll', applyParallax, { passive: true });
});
