/* Nabytkarstvo.sk — Novinky. Public category is the single source of products. */
(function () {
  'use strict';
  if (window.__waNewsV1) return;
  window.__waNewsV1 = true;
  var categoryUrl = '/Novinky-c98_0_1.htm';
  var css = document.createElement('style');
  css.id = 'wa-news-v1-style';
  css.textContent = '.wa-mnav-quick{grid-template-columns:repeat(3,minmax(0,1fr))!important;gap:8px!important}' +
    '.wa-mnav-quick a,.wa-mnav-quick a:first-child,.wa-mnav-quick a:last-child{background:#f3f3f3!important;border:0!important;border-radius:8px!important;color:#171613!important;min-height:46px!important;min-width:0!important;padding:10px 5px!important;font-size:13px!important;font-weight:700!important;line-height:1.2!important;letter-spacing:0!important;text-transform:none!important;white-space:normal!important;box-shadow:none!important}' +
    '.wa-mnav-quick a:last-child{color:#bd5c00!important}.wa-mnav-quick a:hover{background:#eaeaea!important}' +
    '.wa-news .wa-heading{display:flex;align-items:flex-end;justify-content:space-between;gap:20px}' +
    '.wa-news-all{font-size:12px;font-weight:800;text-transform:uppercase;white-space:nowrap;text-decoration:none!important;color:#171613!important}.wa-news-all:hover{color:#ce6c07!important}' +
    'body.home #page .wa-news .wa-news-detail{display:flex!important;align-items:center;justify-content:center;min-height:44px;width:100%;box-sizing:border-box;border-radius:8px;background:#f0830e!important;color:#fff!important;font-size:13px;font-weight:800;text-align:center;text-decoration:none!important;padding:10px 8px}' +
    'body.home #page .wa-news .wa-news-detail:hover{background:#ce6c07!important}' +
    '.wa-news .wa-news-fallback{padding:20px 0}.wa-news .productSubtitle{display:none!important}' +
    'body.home #page [data-wa-homepage] .wa-products{padding-top:36px!important;padding-bottom:36px!important}' +
    'body.home #page [data-wa-homepage] .wa-products .wa-heading{margin-bottom:24px!important}' +
    'body.home #page .wa-products .wa-home-native-products .product .img_box{position:relative!important;height:auto!important;min-height:0!important;aspect-ratio:1/1;padding:0!important;box-sizing:border-box!important}' +
    'body.home #page .wa-products .wa-home-native-products .product .img_box a{display:block!important;position:absolute!important;inset:56px 0 0!important;width:100%!important;height:auto!important;min-height:0!important}' +
    'body.home #page .wa-products .wa-home-native-products .product .img_box img:not([alt="empty"]){width:100%!important;height:100%!important;max-height:100%!important;object-fit:contain!important}' +
    'body.home #page .wa-products .wa-home-detail{display:flex!important;align-items:center;justify-content:center;min-height:44px;width:100%;box-sizing:border-box;border-radius:8px;background:#f0830e!important;color:#fff!important;font-size:13px;font-weight:800;text-align:center;text-decoration:none!important;padding:10px 6px}' +
    'body.home #page .wa-products .wa-home-detail:hover{background:#ce6c07!important}' +
    '@media(max-width:600px){.wa-news .wa-heading{align-items:flex-start;flex-direction:column;gap:12px}body.home #page [data-wa-homepage] .wa-products{padding-top:24px!important;padding-bottom:24px!important}}';
  document.head.appendChild(css);

  function connectMenu() {
    var quick = document.querySelector('.wa-mnav-drawer .wa-mnav-quick');
    if (!quick) return false;
    if (!quick.querySelector('[data-wa-news-menu]')) {
      var link = document.createElement('a');
      link.href = categoryUrl;
      link.textContent = 'Novinky';
      link.setAttribute('data-wa-news-menu', 'true');
      quick.insertBefore(link, quick.firstChild);
      var links = quick.querySelectorAll('a');
      if (links[1]) links[1].textContent = 'Tovar skladom';
      if (links[2]) links[2].textContent = 'Výpredaj';
    }
    return true;
  }
  function hash(text) {
    var n = 2166136261;
    for (var i = 0; i < text.length; i++) { n ^= text.charCodeAt(i); n = Math.imul(n, 16777619); }
    return n >>> 0;
  }
  function mountSection() {
    if (!document.body.classList.contains('home')) return;
    var root = document.querySelector('[data-wa-homepage]');
    if (!root || root.querySelector('#wa-novinky')) return;
    var reference = root.querySelector('.wa-products');
    if (!reference) return;
    var section = document.createElement('section');
    section.id = 'wa-novinky';
    section.className = 'wa-section wa-products wa-news';
    section.setAttribute('aria-labelledby', 'wa-news-title');
    section.innerHTML = '<div class="wa-shell"><div class="wa-heading"><div><p class="wa-eyebrow">Práve v ponuke</p><h2 id="wa-news-title">Novinky v našej ponuke</h2></div><a class="wa-news-all" href="' + categoryUrl + '">Všetky novinky <span aria-hidden="true">→</span></a></div><div class="wa-products__slot" data-wa-news-slot aria-live="polite"><p>Načítavame novinky…</p></div></div>';
    root.insertBefore(section, reference);
    var slot = section.querySelector('[data-wa-news-slot]');
    var controller = new AbortController();
    var timeout = setTimeout(function () { controller.abort(); }, 15000);
    fetch(categoryUrl, { credentials: 'same-origin', signal: controller.signal })
      .then(function (response) { if (!response.ok) throw new Error('Category unavailable'); return response.text(); })
      .then(function (html) {
        var doc = new DOMParser().parseFromString(html, 'text/html');
        var seen = {};
        var products = Array.prototype.filter.call(doc.querySelectorAll('#incenterpage .product[data-id]'), function (product) {
          var id = product.getAttribute('data-id');
          if (!/^\d+$/.test(id || '') || seen[id]) return false;
          seen[id] = true;
          return !!product.querySelector('a[href*="-d"]');
        });
        if (!products.length) { section.remove(); return; }
        var date = new Date();
        var seed = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
        products.sort(function (a, b) { return hash(seed + ':' + a.getAttribute('data-id')) - hash(seed + ':' + b.getAttribute('data-id')); });
        var wrap = document.createElement('div');
        wrap.className = 'products_wrap full wa-home-native-products wa-news-native-products';
        var container = document.createElement('div');
        container.className = 'product_wraper container';
        products.slice(0, 6).forEach(function (source) {
          var product = document.importNode(source, true);
          product.hidden = false;
          product.classList.add('wa-home-product--visible');
          product.removeAttribute('aria-hidden');
          product.querySelectorAll('script,iframe,object,embed').forEach(function (e) { e.remove(); });
          [product].concat(Array.prototype.slice.call(product.querySelectorAll('*'))).forEach(function (e) {
            e.removeAttribute('id');
            Array.prototype.slice.call(e.attributes).forEach(function (a) { if (/^on/i.test(a.name)) e.removeAttribute(a.name); });
          });
          var titleLink = product.querySelector('.productTitle a[href]') || product.querySelector('a[href*="-d"]');
          var url = new URL(titleLink.getAttribute('href'), location.origin);
          if (url.origin !== location.origin) return;
          product.querySelectorAll('a[href]').forEach(function (a) {
            var target = new URL(a.getAttribute('href'), location.origin);
            if (target.origin !== location.origin || !/^https?:$/.test(target.protocol)) a.removeAttribute('href');
          });
          product.querySelectorAll('img').forEach(function (img) {
            var src = img.getAttribute('data-src') || img.getAttribute('data-original') || img.getAttribute('src');
            if (src) img.src = new URL(src, location.origin).href;
            img.loading = 'lazy';
          });
          var buy = product.querySelector('.buy_btn, input[type="submit"],button[type="submit"]');
          if (buy) {
            var action = document.createElement('a');
            action.className = 'wa-news-detail';
            action.href = url.href;
            action.textContent = 'Pozrieť produkt';
            buy.parentNode.replaceChild(action, buy);
          }
          product.querySelectorAll('form').forEach(function (form) { form.removeAttribute('action'); form.addEventListener('submit', function (e) { e.preventDefault(); }); });
          container.appendChild(product);
        });
        wrap.appendChild(container);
        slot.replaceChildren(wrap);
        slot.removeAttribute('aria-live');
      })
      .catch(function () { slot.innerHTML = '<p class="wa-news-fallback">Pozrite si <a href="' + categoryUrl + '">všetky novinky v našej ponuke →</a></p>'; slot.removeAttribute('aria-live'); })
      .finally(function () { clearTimeout(timeout); });
  }
  function start() {
    var tries = 0;
    var timer = setInterval(function () { tries++; if (connectMenu() || tries >= 100) clearInterval(timer); }, 50);
    connectMenu();
    mountSection();
    // Both homepage sections link to detail; no accidental purchase without options.
    var home = document.querySelector('[data-wa-homepage]');
    if (home && document.body.classList.contains('home')) {
      var pending = false;
      function normalizeActions() {
        home.querySelectorAll('.wa-products .product').forEach(function (product) {
          var title = product.querySelector('.productTitle a[href]');
          if (!title) return;
          var url = new URL(title.getAttribute('href'), location.origin);
          if (url.origin !== location.origin) return;
          product.querySelectorAll('.buy_btn,input[type="submit"],button[type="submit"],.wa-news-detail').forEach(function (buy) {
            var action = document.createElement('a');
            action.className = 'wa-home-detail';
            action.href = url.href;
            action.textContent = 'Pozrieť produkt';
            buy.replaceWith(action);
          });
        });
      }
      normalizeActions();
      new MutationObserver(function () {
        if (pending) return;
        pending = true;
        requestAnimationFrame(function () { pending = false; normalizeActions(); });
      }).observe(home, {childList:true, subtree:true});
    }
  }
  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', function () { setTimeout(start, 0); });
  else setTimeout(start, 0);
})();
