/* ============================================================
   Aquafix Homepage — interactions
   ============================================================ */
(function () {
  'use strict';

  /* -------- Mobile navigation -------- */
  var navToggle = document.getElementById('navToggle');
  var mainNav = document.getElementById('mainNav');
  if (navToggle && mainNav) {
    navToggle.addEventListener('click', function () {
      var open = mainNav.classList.toggle('open');
      navToggle.setAttribute('aria-expanded', open ? 'true' : 'false');
    });
    mainNav.addEventListener('click', function (e) {
      if (e.target.tagName === 'A') {
        mainNav.classList.remove('open');
        navToggle.setAttribute('aria-expanded', 'false');
      }
    });
  }

  /* -------- Hero carousel -------- */
  var slides = Array.prototype.slice.call(document.querySelectorAll('.hero-slide'));
  var dotsWrap = document.getElementById('heroDots');
  var current = 0, timer;

  if (slides.length) {
    slides.forEach(function (_, i) {
      var b = document.createElement('button');
      b.setAttribute('role', 'tab');
      b.setAttribute('aria-label', 'Go to slide ' + (i + 1));
      if (i === 0) b.className = 'active';
      b.addEventListener('click', function () { go(i); reset(); });
      dotsWrap.appendChild(b);
    });

    var dots = Array.prototype.slice.call(dotsWrap.children);

    function go(n) {
      slides[current].classList.remove('is-active');
      dots[current].classList.remove('active');
      current = (n + slides.length) % slides.length;
      slides[current].classList.add('is-active');
      dots[current].classList.add('active');
    }
    function next() { go(current + 1); }
    function prev() { go(current - 1); }
    function reset() { clearInterval(timer); timer = setInterval(next, 6000); }

    var pn = document.getElementById('heroNext');
    var pp = document.getElementById('heroPrev');
    if (pn) pn.addEventListener('click', function () { next(); reset(); });
    if (pp) pp.addEventListener('click', function () { prev(); reset(); });
    reset();
  }

  /* -------- Products: category data + tabs -------- */
  var categories = {
    pipes: {
      label: 'Pipes',
      desc: 'A complete pipe range spanning thermoplastic and metal materials, sized for marine, commercial and industrial routing.',
      items: [
        { material: 'PVC-U / PVC-C', desc: 'Solvent-cemented waterline and chemical-process routing.', img: 'products/Fittings 1' },
        { material: 'PPR & PPR-CT', desc: 'Welded polypropylene for hot and cold water distribution.', img: 'products/Fittings 3' },
        { material: 'Stainless Steel', desc: 'Corrosion-resistant piping for potable water and process lines.', img: 'products/Fittings 4' },
        { material: 'Carbon Steel', desc: 'Piping for heating circuits and cooling water networks.', img: 'products/Fittings 5' },
        { material: 'Copper', desc: 'Jointing pipe for drinking water, gas and solar applications.', img: 'products/Fittings 6' },
        { material: 'HDPE', desc: 'Drainage and neutralization-tank grade piping.', img: 'products/Fittings 7' }
      ]
    },
    fittings: {
      label: 'Fittings',
      desc: 'Press-fit and welded fittings across stainless steel, copper, carbon steel and thermoplastic materials.',
      items: [
        { material: 'Stainless Steel Press', desc: '316L / 304 grade, 15mm–168.3mm.', img: 'supply-ss-fitting' },
        { material: 'Copper & Bronze Press', desc: 'Clean seals for drinking water, gas and cooling.', img: 'fittings-reference' },
        { material: 'Carbon Steel Press', desc: 'Press-jointed components for heating networks.', img: 'supply-containment' },
        { material: 'PPR Fittings', desc: 'Welded polypropylene joints for water systems.', img: 'supply-ppr' }
      ]
    },
    valves: {
      label: 'Valves',
      desc: 'A full valve line in metal and thermoplastic, built to DN and ASTM standards — ball, gate, butterfly, check, globe, three-way, wafer, angle and diaphragm.',
      items: [
        { material: 'Ball Valves', desc: 'Metal and thermoplastic, for shut-off and flow control.', img: 'valves-reference' },
        { material: 'Butterfly Valves', desc: 'Compact wafer and lug-style flow regulation.', img: 'products/Fittings 3' },
        { material: 'Gate Valves', desc: 'Full-bore isolation for industrial and marine lines.', img: 'products/Fittings 4' },
        { material: 'Check & Diaphragm', desc: 'Non-return and diaphragm valves for process control.', img: 'supply-drainage' }
      ]
    },
    tools: {
      label: 'Tools & Accessories',
      desc: 'Jointing consumables and fusion welding equipment to support installation across every piping material.',
      items: [
        { material: 'Solvent Cement, Cleaner & Primer', desc: 'Consumables for solvent-cemented PVC / CPVC joints.', img: 'supply-pvc' },
        { material: 'Socket Fusion Machines', desc: 'Welding equipment for socket-fusion thermoplastic joints.', img: 'products/Fittings 5' },
        { material: 'Butt Fusion Machines', desc: 'Welding equipment for butt-fusion pipe joints.', img: 'products/Fittings 6' },
        { material: 'Electrofusion Machines', desc: 'Fusion welding equipment for electrofusion fittings.', img: 'products/Fittings 7' }
      ]
    }
  };

  var order = ['pipes', 'fittings', 'valves', 'tools'];
  var tabsWrap = document.getElementById('catTabs');
  var descEl = document.getElementById('catDesc');
  var gridEl = document.getElementById('prodGrid');
  var showMore = document.getElementById('showMore');
  var activeCat = 'pipes';
  var expanded = false;

  function esc(s) { return String(s).replace(/[&<>"]/g, function (c) { return ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]; }); }

  function renderProducts() {
    var cat = categories[activeCat];
    descEl.textContent = cat.desc;
    var items = expanded ? cat.items : cat.items.slice(0, 4);
    gridEl.innerHTML = items.map(function (it) {
      return '<article class="prod-card">' +
        '<div class="prod-img" data-img="' + it.img + '"></div>' +
        '<div class="prod-body"><h4>' + esc(it.material) + '</h4><p>' + esc(it.desc) + '</p>' +
        '<button class="btn btn-outline btn-full quote-btn" data-product="' + esc(it.material) + '">Get Quote</button></div>' +
        '</article>';
    }).join('');
    applyImages(gridEl);
    showMore.style.display = cat.items.length > 4 ? '' : 'none';
    showMore.textContent = expanded ? 'Show Fewer Products' : 'Show More Products';
  }

  if (tabsWrap) {
    order.forEach(function (key) {
      var b = document.createElement('button');
      b.className = 'cat-tab' + (key === activeCat ? ' active' : '');
      b.setAttribute('role', 'tab');
      b.textContent = categories[key].label;
      b.addEventListener('click', function () {
        activeCat = key; expanded = false;
        Array.prototype.forEach.call(tabsWrap.children, function (c) { c.classList.remove('active'); });
        b.classList.add('active');
        renderProducts();
      });
      tabsWrap.appendChild(b);
    });
    if (showMore) showMore.addEventListener('click', function () { expanded = !expanded; renderProducts(); });
    renderProducts();
  }

  /* -------- Contact form -------- */
  var form = document.getElementById('enquiryForm');
  if (form) {
    form.addEventListener('submit', function (e) {
      e.preventDefault();
      if (!form.checkValidity()) { form.reportValidity(); return; }
      document.getElementById('formSuccess').hidden = false;
      form.reset();
    });
  }

  /* -------- Drop-in image loader --------
     Any element with data-img="<name>" will use images/<name>.(jpg|png|webp)
     as a background if that file exists. Otherwise the CSS pattern shows.
     Drop real photos into /images using these names — see images/README.txt. */
  function applyImages(scope) {
    var els = (scope || document).querySelectorAll('[data-img]');
    Array.prototype.forEach.call(els, function (el) {
      if (el.dataset.loaded) return;
      var name = el.getAttribute('data-img');
      tryLoad(el, name, ['jpg', 'png', 'webp', 'jpeg'], 0);
    });
  }
  function tryLoad(el, name, exts, i) {
    if (i >= exts.length) return;
    var url = 'images/' + name + '.' + exts[i];
    var img = new Image();
    img.onload = function () {
      el.style.backgroundImage = "url('" + url + "')";
      el.dataset.loaded = '1';
    };
    img.onerror = function () { tryLoad(el, name, exts, i + 1); };
    img.src = url;
  }

  /* -------- Quote Modal -------- */
  var quoteModal = document.getElementById('quoteModal');
  var closeQuoteModal = document.getElementById('closeQuoteModal');
  var quoteForm = document.getElementById('quoteForm');
  var quoteProductInput = document.getElementById('quoteProductInput');
  var quoteSuccess = document.getElementById('quoteSuccess');

  if (quoteModal && gridEl) {
    gridEl.addEventListener('click', function(e) {
      if (e.target.classList.contains('quote-btn')) {
        var product = e.target.getAttribute('data-product');
        quoteProductInput.value = product;
        quoteSuccess.hidden = true;
        quoteForm.reset();
        quoteProductInput.value = product; // Reset might clear it, so set it again
        quoteModal.hidden = false;
      }
    });

    closeQuoteModal.addEventListener('click', function() {
      quoteModal.hidden = true;
    });

    quoteModal.addEventListener('click', function(e) {
      if (e.target === quoteModal) {
        quoteModal.hidden = true;
      }
    });

    if (quoteForm) {
      quoteForm.addEventListener('submit', function(e) {
        e.preventDefault();
        if (!quoteForm.checkValidity()) { quoteForm.reportValidity(); return; }
        quoteSuccess.hidden = false;
        setTimeout(function() {
          quoteModal.hidden = true;
          quoteForm.reset();
        }, 2500);
      });
    }
  }

  /* -------- Floating Widgets -------- */
  var backToTopBtn = document.getElementById('backToTop');
  if (backToTopBtn) {
    window.addEventListener('scroll', function() {
      if (window.scrollY > 300) {
        backToTopBtn.classList.add('show');
      } else {
        backToTopBtn.classList.remove('show');
      }
    });
    backToTopBtn.addEventListener('click', function() {
      window.scrollTo({
        top: 0,
        behavior: 'smooth'
      });
    });
  }

  /* -------- Products Page Filtering -------- */
  var filterCheckboxes = document.querySelectorAll('.products-sidebar input[type="checkbox"]');
  var prodCards = document.querySelectorAll('.products-grid .prod-card');
  var noProdMsg = document.getElementById('no-products-msg');

  if (filterCheckboxes.length > 0 && prodCards.length > 0) {
    function updateProductFilters() {
      var selectedCategories = [];
      var selectedMaterials = [];

      // Gather selected filters
      Array.prototype.forEach.call(filterCheckboxes, function(cb) {
        if (cb.checked) {
          if (cb.getAttribute('data-filter-type') === 'category') {
            selectedCategories.push(cb.value);
          } else if (cb.getAttribute('data-filter-type') === 'material') {
            selectedMaterials.push(cb.value);
          }
        }
      });

      var visibleCount = 0;

      // Filter products
      Array.prototype.forEach.call(prodCards, function(card) {
        var itemCategory = card.getAttribute('data-category');
        var itemMaterial = card.getAttribute('data-material');

        var categoryMatch = selectedCategories.length === 0 || selectedCategories.indexOf(itemCategory) !== -1;
        var materialMatch = selectedMaterials.length === 0 || selectedMaterials.indexOf(itemMaterial) !== -1;

        if (categoryMatch && materialMatch) {
          card.style.display = '';
          visibleCount++;
        } else {
          card.style.display = 'none';
        }
      });

      // Show/hide no products message
      if (noProdMsg) {
        noProdMsg.style.display = (visibleCount === 0) ? 'block' : 'none';
      }
    }

    Array.prototype.forEach.call(filterCheckboxes, function(cb) {
      cb.addEventListener('change', updateProductFilters);
    });
  }

  applyImages(document);
})();
