/*
 * EveryHer — script.js
 * Cart, checkout, product toggle, scroll animations, navbar
 */

'use strict';

/* ─────────────────────────────────────────────────────────────────────────────
   PRODUCT CATALOGUE
   Edit prices/sizes here — these populate the size toggle and cart.
───────────────────────────────────────────────────────────────────────────── */
const PRODUCTS = {
  regular: {
    id:    'eh-regular-240',
    name:  'EveryHer Sanitary Pads',
    size:  'Regular (240mm)',
    count: '10 pads',
    price: 1500,
    image: 'src/images/IMG_0938.jpg',
    alt:   'EveryHer Sanitary Pads Regular 240mm — forest green and cream packaging, front view',
  },
  extralong: {
    id:    'eh-extralong-290',
    name:  'EveryHer Sanitary Pads',
    size:  'Extra Long (290mm) Ultra Thin',
    count: '10 pads',
    price: 1800,
    image: 'src/images/IMG_09360.jpg',
    alt:   'EveryHer Sanitary Pads Extra Long 290mm Ultra Thin — angled product view',
  },
};

/* ─────────────────────────────────────────────────────────────────────────────
   CART STATE
   Persisted to localStorage under key 'everyher_cart'.
   Shape: { items: Array<CartItem> }
   CartItem: { id, name, size, count, price, image, alt, qty }
───────────────────────────────────────────────────────────────────────────── */
let cart = loadCart();

function loadCart() {
  try {
    return JSON.parse(localStorage.getItem('everyher_cart')) || { items: [] };
  } catch {
    return { items: [] };
  }
}

function saveCart() {
  localStorage.setItem('everyher_cart', JSON.stringify(cart));
}

/* ─── helpers ─── */
const fmt    = (n) => '₦' + Number(n).toLocaleString('en-NG');
const sum    = () => cart.items.reduce((s, i) => s + i.price * i.qty, 0);
const count  = () => cart.items.reduce((s, i) => s + i.qty, 0);

/* ─────────────────────────────────────────────────────────────────────────────
   CART OPERATIONS
───────────────────────────────────────────────────────────────────────────── */

/** Add a product to cart (or increment if already present) */
function addToCart(productKey, qty) {
  const p    = PRODUCTS[productKey];
  const item = cart.items.find(i => i.id === p.id);
  if (item) {
    item.qty += qty;
  } else {
    cart.items.push({ ...p, qty });
  }
  saveCart();
  updateCartUI();
  openCart();
  animateAddBtn();
}

/** Adjust qty of a cart item by delta; remove if result ≤ 0 */
function adjustQty(id, delta) {
  const item = cart.items.find(i => i.id === id);
  if (!item) return;
  item.qty = Math.max(0, item.qty + delta);
  if (item.qty === 0) removeItem(id);
  else { saveCart(); updateCartUI(); }
}

/** Remove item from cart */
function removeItem(id) {
  cart.items = cart.items.filter(i => i.id !== id);
  saveCart();
  updateCartUI();
}

/* ─── UI sync ─── */

function updateCartUI() {
  /* Badge */
  const badge = document.querySelector('.cart-badge');
  const n     = count();
  if (badge) {
    badge.textContent = n;
    badge.classList.toggle('visible', n > 0);
  }

  /* Live region so screen readers announce changes */
  const live = document.getElementById('cart-live');
  if (live && n > 0) live.textContent = `Cart updated. ${n} item${n !== 1 ? 's' : ''} in cart.`;

  renderCartBody();
  renderCheckoutSummary();
  updateCheckoutBtn();
}

function renderCartBody() {
  const body  = document.querySelector('.cart-drawer__body');
  const total = document.querySelector('.cart-subtotal__value');
  if (!body) return;

  if (cart.items.length === 0) {
    body.innerHTML = `
      <div class="cart-empty">
        <div class="cart-empty__icon">🛍️</div>
        <p class="cart-empty__title">Your cart is empty</p>
        <p class="cart-empty__sub">Add a product to get started</p>
      </div>`;
  } else {
    body.innerHTML = `<div class="cart-items">${cart.items.map(cartItemHTML).join('')}</div>`;
  }

  if (total) total.textContent = fmt(sum());
}

function cartItemHTML(item) {
  return `
    <div class="cart-item" data-id="${item.id}">
      <img class="cart-item__img"
           src="${item.image}"
           alt="${item.alt}"
           loading="lazy"
           width="76" height="76">
      <div class="cart-item__info">
        <div class="cart-item__name">${item.name}</div>
        <div class="cart-item__size">${item.size} · ${item.count}</div>
        <div class="cart-item__qty">
          <button class="cart-item__qty-btn"
                  aria-label="Decrease quantity of ${item.name}"
                  onclick="adjustQty('${item.id}', -1)">−</button>
          <span class="cart-item__qty-num" aria-label="Quantity">${item.qty}</span>
          <button class="cart-item__qty-btn"
                  aria-label="Increase quantity of ${item.name}"
                  onclick="adjustQty('${item.id}', 1)">+</button>
        </div>
      </div>
      <div class="cart-item__right">
        <button class="cart-item__remove"
                aria-label="Remove ${item.name} from cart"
                onclick="removeItem('${item.id}')">×</button>
        <div class="cart-item__price">${fmt(item.price * item.qty)}</div>
      </div>
    </div>`;
}

function renderCheckoutSummary() {
  const list  = document.querySelector('.checkout-summary__items');
  const total = document.querySelector('.checkout-summary__total span:last-child');
  if (!list) return;

  if (cart.items.length === 0) {
    list.innerHTML = '<p style="color:var(--color-text-muted);font-size:14px;">No items</p>';
  } else {
    list.innerHTML = cart.items.map(i => `
      <div class="checkout-summary__item">
        <span>${i.name} (${i.size}) × ${i.qty}</span>
        <span>${fmt(i.price * i.qty)}</span>
      </div>`).join('');
  }
  if (total) total.textContent = fmt(sum());
}

function updateCheckoutBtn() {
  const btn = document.querySelector('.js-checkout-btn');
  if (btn) btn.disabled = cart.items.length === 0;
}

/* ─────────────────────────────────────────────────────────────────────────────
   CART DRAWER — open / close
───────────────────────────────────────────────────────────────────────────── */
function openCart() {
  document.querySelector('.cart-drawer').classList.add('open');
  document.querySelector('.cart-overlay').classList.add('open');
  document.body.style.overflow = 'hidden';
  /* Focus the close button for keyboard users */
  setTimeout(() => document.querySelector('.cart-close')?.focus(), 60);
}

function closeCart() {
  document.querySelector('.cart-drawer').classList.remove('open');
  document.querySelector('.cart-overlay').classList.remove('open');
  document.body.style.overflow = '';
  document.querySelector('.cart-btn')?.focus();
}

/* ─────────────────────────────────────────────────────────────────────────────
   CHECKOUT MODAL — open / close
───────────────────────────────────────────────────────────────────────────── */
function openCheckout() {
  if (cart.items.length === 0) return;
  closeCart();
  renderCheckoutSummary();

  /* Reset any previous success state */
  const body = document.querySelector('.checkout-modal__body');
  if (body) body.classList.remove('success-mode');
  const form = document.querySelector('.checkout-form');
  if (form) form.reset();

  document.querySelector('.checkout-overlay').classList.add('open');
  document.body.style.overflow = 'hidden';
  setTimeout(() => document.querySelector('#co-fname')?.focus(), 60);
}

function closeCheckout() {
  document.querySelector('.checkout-overlay').classList.remove('open');
  document.body.style.overflow = '';
}

/* Checkout form submit — shows success state, clears cart */
function handleCheckout(e) {
  e.preventDefault();
  const body = document.querySelector('.checkout-modal__body');
  if (body) body.classList.add('success-mode');
  cart = { items: [] };
  saveCart();
  updateCartUI();
}

/* ─────────────────────────────────────────────────────────────────────────────
   PRODUCT SIZE TOGGLE
───────────────────────────────────────────────────────────────────────────── */
let selectedSize = 'regular';
let selectedQty  = 1;

function selectSize(key) {
  if (key === selectedSize) return;
  selectedSize = key;

  /* Update size button active states */
  document.querySelectorAll('.size-btn').forEach(btn => {
    btn.classList.toggle('active', btn.dataset.size === key);
    btn.setAttribute('aria-pressed', String(btn.dataset.size === key));
  });

  const p = PRODUCTS[key];

  /* Animate price (fade out → update → fade in) */
  const priceEl = document.querySelector('.product__price');
  if (priceEl) {
    priceEl.classList.add('fade-out');
    setTimeout(() => {
      priceEl.textContent = fmt(p.price);
      priceEl.classList.remove('fade-out');
    }, 160);
  }

  /* Crossfade main product image */
  const mainImg = document.querySelector('.product__img-main img');
  if (mainImg) {
    mainImg.classList.add('fade-out');
    setTimeout(() => {
      mainImg.src = p.image;
      mainImg.alt = p.alt;
      mainImg.classList.remove('fade-out');
    }, 160);
  }

  /* Update thumbnail active indicator */
  document.querySelectorAll('.product__thumb').forEach(thumb => {
    thumb.classList.toggle('active', thumb.dataset.size === key);
  });
}

function changeQty(delta) {
  selectedQty = Math.max(1, selectedQty + delta);
  const el = document.querySelector('.qty-display');
  if (el) el.textContent = selectedQty;
}

/* Thumbnail click — switch main image without changing size price */
function thumbClick(src, alt, size) {
  const mainImg = document.querySelector('.product__img-main img');
  if (!mainImg) return;
  mainImg.classList.add('fade-out');
  setTimeout(() => {
    mainImg.src = src;
    mainImg.alt = alt;
    mainImg.classList.remove('fade-out');
  }, 160);
  document.querySelectorAll('.product__thumb').forEach(t => {
    t.classList.toggle('active', t.dataset.size === size);
  });
}

/* ─── "Add to cart" button micro-interaction ─── */
function animateAddBtn() {
  const btn = document.querySelector('.js-add-to-cart');
  if (!btn || btn._animating) return;
  btn._animating = true;
  const orig = btn.innerHTML;
  btn.innerHTML = `
    <svg width="16" height="16" viewBox="0 0 16 16" fill="none" aria-hidden="true">
      <path d="M2 8l4 4L14 3" stroke="currentColor" stroke-width="2"
            stroke-linecap="round" stroke-linejoin="round"/>
    </svg> Added!`;
  btn.style.background = 'var(--color-primary-light)';
  setTimeout(() => {
    btn.innerHTML = orig;
    btn.style.background = '';
    btn._animating = false;
  }, 1400);
}

/* ─────────────────────────────────────────────────────────────────────────────
   SCROLL ANIMATIONS — IntersectionObserver
───────────────────────────────────────────────────────────────────────────── */
function initScrollReveal() {
  const all = Array.from(document.querySelectorAll('.reveal'));

  /* Reveal everything immediately in browsers without IntersectionObserver */
  if (!('IntersectionObserver' in window)) {
    all.forEach(el => el.classList.add('visible'));
    return;
  }

  /*
   * PRE-ASSIGN STAGGER DELAYS.
   * Must be done before .visible is ever added — setting transitionDelay
   * after the transition has started has no effect.
   * Walk each unique parent once; if it owns multiple .reveal children,
   * give them incrementing delays so they cascade in (60 ms apart).
   */
  const seen = new Set();
  all.forEach(el => {
    const p = el.parentElement;
    if (!p || seen.has(p)) return;
    seen.add(p);
    const kids = Array.from(p.children).filter(c => c.classList.contains('reveal'));
    if (kids.length > 1) {
      kids.forEach((c, i) => { c.style.transitionDelay = i * 60 + 'ms'; });
    }
  });

  /*
   * Observer — fires once per element when it enters the viewport.
   * io.unobserve() is called FIRST so the element can never be re-triggered
   * no matter how many times the user scrolls up and down.
   * After the animation duration + stagger delay, clear the inline
   * transitionDelay so it doesn't interfere with future hover transitions.
   */
  const io = new IntersectionObserver(entries => {
    entries.forEach(({ target, isIntersecting }) => {
      if (!isIntersecting) return;
      io.unobserve(target);
      target.classList.add('visible');
      const stagger = parseFloat(target.style.transitionDelay) || 0;
      setTimeout(() => { target.style.transitionDelay = ''; }, 480 + stagger);
    });
  }, { threshold: 0.12 });

  all.forEach(el => io.observe(el));
}

/* ─────────────────────────────────────────────────────────────────────────────
   NAVBAR
───────────────────────────────────────────────────────────────────────────── */
function initNavbar() {
  const navbar = document.querySelector('.navbar');
  window.addEventListener('scroll', () => {
    navbar?.classList.toggle('scrolled', window.scrollY > 60);
  }, { passive: true });

  /* Hamburger / mobile menu */
  const hamburger  = document.querySelector('.hamburger');
  const mobileMenu = document.querySelector('.mobile-menu');
  hamburger?.addEventListener('click', () => {
    const open = mobileMenu.classList.toggle('open');
    hamburger.classList.toggle('open', open);
    hamburger.setAttribute('aria-expanded', String(open));
    document.body.style.overflow = open ? 'hidden' : '';
  });

  /* Close mobile menu when any link is clicked */
  mobileMenu?.querySelectorAll('a').forEach(a => {
    a.addEventListener('click', closeMobileMenu);
  });
}

function closeMobileMenu() {
  const hamburger  = document.querySelector('.hamburger');
  const mobileMenu = document.querySelector('.mobile-menu');
  mobileMenu?.classList.remove('open');
  hamburger?.classList.remove('open');
  hamburger?.setAttribute('aria-expanded', 'false');
  document.body.style.overflow = '';
}

/* ─────────────────────────────────────────────────────────────────────────────
   KEYBOARD ACCESSIBILITY — Esc closes any open overlay
───────────────────────────────────────────────────────────────────────────── */
function initKeyboard() {
  document.addEventListener('keydown', (e) => {
    if (e.key !== 'Escape') return;
    if (document.querySelector('.checkout-overlay.open')) { closeCheckout(); return; }
    if (document.querySelector('.cart-drawer.open'))      { closeCart();     return; }
    if (document.querySelector('.mobile-menu.open'))      { closeMobileMenu(); }
  });
}

/* ─────────────────────────────────────────────────────────────────────────────
   CONTACT FORM
───────────────────────────────────────────────────────────────────────────── */
function initContactForm() {
  const form = document.querySelector('.contact-form');
  form?.addEventListener('submit', (e) => {
    e.preventDefault();
    const btn = form.querySelector('button[type="submit"]');
    const orig = btn.textContent;
    btn.textContent = 'Message sent ✓';
    btn.disabled = true;
    btn.style.background = 'var(--color-primary-light)';
    form.reset();
    setTimeout(() => {
      btn.textContent = orig;
      btn.disabled = false;
      btn.style.background = '';
    }, 3000);
  });
}

/* ─────────────────────────────────────────────────────────────────────────────
   INIT
───────────────────────────────────────────────────────────────────────────── */
document.addEventListener('DOMContentLoaded', () => {
  updateCartUI();
  initScrollReveal();
  initNavbar();
  initKeyboard();
  initContactForm();

  /* Wire up checkout form */
  document.querySelector('.checkout-form')
    ?.addEventListener('submit', handleCheckout);

  /* Wire up cart overlay click-outside */
  document.querySelector('.cart-overlay')
    ?.addEventListener('click', closeCart);

  /* Wire up checkout overlay click-outside */
  document.querySelector('.checkout-overlay')
    ?.addEventListener('click', (e) => {
      if (e.target === e.currentTarget) closeCheckout();
    });
});
