(function () {
  'use strict';

  /* ---- Footer year ---- */
  var yearEl = document.getElementById('year');
  if (yearEl) yearEl.textContent = new Date().getFullYear();

  /* ---- Toast helper ---- */
  var toastEl = document.getElementById('toast');
  var toastTimer;
  function showToast(msg) {
    if (!toastEl) return;
    toastEl.textContent = msg;
    toastEl.classList.add('show');
    clearTimeout(toastTimer);
    toastTimer = setTimeout(function () {
      toastEl.classList.remove('show');
    }, 2200);
  }

  /* ---- Cart (in-memory count) ---- */
  var cartCount = 0;
  var cartCountEl = document.getElementById('cart-count');
  document.querySelectorAll('.btn-add').forEach(function (btn) {
    btn.addEventListener('click', function () {
      cartCount += 1;
      if (cartCountEl) cartCountEl.textContent = String(cartCount);
      var name = btn.getAttribute('data-name') || 'Item';
      showToast('Added "' + name + '" to your cart');
    });
  });

  /* ---- Category filter ---- */
  var chips = document.querySelectorAll('.chip');
  var cards = document.querySelectorAll('.card');
  chips.forEach(function (chip) {
    chip.addEventListener('click', function () {
      chips.forEach(function (c) { c.classList.remove('is-active'); });
      chip.classList.add('is-active');
      var filter = chip.getAttribute('data-filter');
      cards.forEach(function (card) {
        var match = filter === 'all' || card.getAttribute('data-category') === filter;
        card.style.display = match ? '' : 'none';
      });
    });
  });

  /* ---- Simple email validation + form handlers ---- */
  function isValidEmail(value) {
    return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value.trim());
  }

  function wireForm(formId, inputId, noteId, successMsg) {
    var form = document.getElementById(formId);
    var input = document.getElementById(inputId);
    var note = document.getElementById(noteId);
    if (!form || !input || !note) return;
    form.addEventListener('submit', function (e) {
      e.preventDefault();
      if (!isValidEmail(input.value)) {
        note.style.color = '#c9603f';
        note.textContent = 'Please enter a valid email address.';
        input.focus();
        return;
      }
      note.style.color = '';
      note.textContent = successMsg;
      form.reset();
    });
  }

  wireForm('sell-form', 'sell-email', 'sell-note', 'Thanks! Check your inbox for a free shipping label.');
  wireForm('news-form', 'news-email', 'news-note', "You're in! Look out for Thursday's drop.");
})();
