/*
 * Nábytkárstvo.sk — správanie úvodnej stránky vo Webareale.
 * Vložiť do vlastného JavaScriptu alebo do pätičky za HTML úvodnej stránky.
 * Hodnotenia a cestu k obrázkom možno prepísať cez window.NABYTKARSTVO_HOMEPAGE.
 */
(function () {
  'use strict';

  var defaults = {
    assetBase: '/fotky13204/homepage_redesign/',
    mobileBannerSuffix: '-mobile',
    mobileBannerMedia: '(max-width: 560px)',
    productCount: 6,
    ratings: {
      google: { score: '4,4', suffix: '/ 5' },
      facebook: { score: '98', suffix: '% odporúča' }
    }
  };

  function mergeConfig() {
    var supplied = window.NABYTKARSTVO_HOMEPAGE || {};
    var assetBase = supplied.assetBase || defaults.assetBase;
    return {
      assetBase: assetBase,
      mobileBannerBase: supplied.mobileBannerBase || normalizeAssetBase(assetBase) + 'bannery/',
      mobileBannerSuffix: supplied.mobileBannerSuffix || defaults.mobileBannerSuffix,
      mobileBannerMedia: supplied.mobileBannerMedia || defaults.mobileBannerMedia,
      mobileBannerMap: supplied.mobileBannerMap || {},
      productCount: Number(supplied.productCount || defaults.productCount),
      ratings: {
        google: Object.assign({}, defaults.ratings.google, supplied.ratings && supplied.ratings.google),
        facebook: Object.assign({}, defaults.ratings.facebook, supplied.ratings && supplied.ratings.facebook)
      }
    };
  }

  function normalizeAssetBase(value) {
    if (!value) return '';
    return value.charAt(value.length - 1) === '/' ? value : value + '/';
  }

  function loadHomepageFonts() {
    if (document.querySelector('link[data-wa-home-fonts]')) return;

    var stylesheet = document.createElement('link');
    stylesheet.rel = 'stylesheet';
    stylesheet.href = 'https://fonts.googleapis.com/css2?family=Manrope:wght@400;500;600;700;800&family=Nunito:wght@400;500;600;700;800&display=swap';
    stylesheet.setAttribute('data-wa-home-fonts', 'true');
    document.head.appendChild(stylesheet);
  }

  function applyAssets(root, assetBase) {
    var base = normalizeAssetBase(assetBase);
    if (!base) return;

    root.querySelectorAll('[data-wa-asset]').forEach(function (image) {
      image.src = base + image.getAttribute('data-wa-asset');
    });
  }

  function applyRatings(root, ratings) {
    Object.keys(ratings).forEach(function (source) {
      var value = ratings[source];
      root.querySelectorAll('[data-wa-rating-source="' + source + '"]').forEach(function (display) {
        var score = display.querySelector('[data-wa-rating-score]');
        var suffix = display.querySelector('[data-wa-rating-suffix]');

        if (score && value.score) score.textContent = value.score;
        if (suffix) suffix.textContent = value.suffix || '';
      });
    });
  }

  function nativeHeroSlider() {
    var slider = document.querySelector('#page-slider-1');
    return {
      slider: slider,
      slides: slider ? Array.prototype.slice.call(slider.querySelectorAll('.page-slider-content')) : []
    };
  }

  function bannerFileParts(value) {
    if (!value) return null;

    try {
      var path = new URL(value, document.baseURI).pathname;
      var filename = decodeURIComponent(path.split('/').pop() || '');
      var dot = filename.lastIndexOf('.');

      if (dot <= 0 || dot === filename.length - 1) return null;
      return {
        filename: filename,
        stem: filename.slice(0, dot),
        extension: filename.slice(dot)
      };
    } catch (error) {
      return null;
    }
  }

  function mobileBannerUrls(image, config) {
    var parts = bannerFileParts(image.getAttribute('src') || image.src);
    if (!parts) return [];

    var webarealCopy = parts.stem.match(/^(.*)_\d+$/);
    var mapped = config.mobileBannerMap[parts.filename];
    if (mapped === undefined) mapped = config.mobileBannerMap[parts.stem];
    if (mapped === undefined && webarealCopy && webarealCopy[1]) {
      mapped = config.mobileBannerMap[webarealCopy[1]];
    }
    if (mapped === false || mapped === null) return [];
    if (mapped) return [mapped];

    var stems = [parts.stem];

    /* Webareal pri rovnakom n\u00e1zve niekedy dopln\u00ed _2, _3 at\u010f.
       Najprv sk\u00fasime presn\u00fd n\u00e1zov a potom aj p\u00f4vodn\u00fd n\u00e1zov bez tejto pr\u00edpony. */
    if (webarealCopy && webarealCopy[1]) stems.push(webarealCopy[1]);

    return stems.map(function (stem) {
      return normalizeAssetBase(config.mobileBannerBase) +
        encodeURIComponent(stem) + config.mobileBannerSuffix + parts.extension;
    });
  }

  function imageRatio(width, height) {
    return width > 0 && height > 0 ? width + ' / ' + height : '';
  }

  function probeImage(source, done) {
    var probe = new Image();
    probe.onload = function () {
      done({ width: probe.naturalWidth, height: probe.naturalHeight });
    };
    probe.onerror = function () { done(null); };
    probe.src = source;
  }

  function probeFirstImage(sources, done, index) {
    var currentIndex = index || 0;
    if (currentIndex >= sources.length) {
      done(null);
      return;
    }

    probeImage(sources[currentIndex], function (size) {
      if (size) {
        done({ source: sources[currentIndex], size: size });
        return;
      }

      probeFirstImage(sources, done, currentIndex + 1);
    });
  }

  function responsivePicture(image, mobileUrl, media) {
    var picture = image.closest('picture');
    if (!picture) {
      picture = document.createElement('picture');
      image.parentNode.insertBefore(picture, image);
      picture.appendChild(image);
    }

    picture.classList.add('wa-hero__picture');
    picture.setAttribute('data-wa-banner-picture', '');
    picture.setAttribute('data-wa-mobile-status', 'ready');

    var mobileSource = picture.querySelector('source[data-wa-banner-mobile]');
    if (!mobileSource) {
      mobileSource = document.createElement('source');
      mobileSource.setAttribute('data-wa-banner-mobile', '');
      picture.insertBefore(mobileSource, image);
    }

    mobileSource.media = media;
    mobileSource.srcset = mobileUrl;
    return { picture: picture, source: mobileSource };
  }

  function prepareResponsiveBanner(slide, config, onChange) {
    var image = slide.querySelector('img.page-slider-image') || slide.querySelector('img');
    if (!image || slide.hasAttribute('data-wa-mobile-status')) return;

    /* Ka\u017ed\u00fd banner zo slidera je hotov\u00fd grafick\u00fd banner s vlastn\u00fdm textom.
       HTML prekrytie sa preto skryje aj vtedy, ke\u010f mobiln\u00fd variant ch\u00fdba. */
    slide.setAttribute('data-wa-banner-mode', 'graphic');
    slide.setAttribute('data-wa-mobile-status', 'checking');
    var mobileUrls = mobileBannerUrls(image, config);
    var desktopUrl = image.getAttribute('src') || image.src;
    var desktopRatio = imageRatio(image.naturalWidth, image.naturalHeight);

    if (desktopRatio) {
      slide.setAttribute('data-wa-desktop-ratio', desktopRatio);
      slide.setAttribute('data-wa-mobile-ratio', desktopRatio);
    }

    if (!desktopRatio) {
      probeImage(desktopUrl, function (size) {
        if (!size) return;
        var ratio = imageRatio(size.width, size.height);
        slide.setAttribute('data-wa-desktop-ratio', ratio);
        if (slide.getAttribute('data-wa-mobile-status') !== 'ready') {
          slide.setAttribute('data-wa-mobile-ratio', ratio);
        }
        onChange();
      });
    }

    if (!mobileUrls.length) {
      slide.setAttribute('data-wa-mobile-status', 'fallback');
      onChange();
      return;
    }

    probeFirstImage(mobileUrls, function (result) {
      if (!result) {
        slide.setAttribute('data-wa-mobile-status', 'fallback');
        onChange();
        return;
      }

      var mobileUrl = result.source;
      var size = result.size;
      var responsive = responsivePicture(image, mobileUrl, config.mobileBannerMedia);
      slide.setAttribute('data-wa-mobile-status', 'ready');
      slide.setAttribute('data-wa-mobile-ratio', imageRatio(size.width, size.height));
      if (desktopRatio) slide.setAttribute('data-wa-desktop-ratio', desktopRatio);

      image.addEventListener('error', function mobileBannerFallback() {
        if (!window.matchMedia(config.mobileBannerMedia).matches) return;
        if (!responsive.source.isConnected) return;

        responsive.source.remove();
        responsive.picture.setAttribute('data-wa-mobile-status', 'fallback');
        slide.setAttribute('data-wa-mobile-status', 'fallback');
        slide.setAttribute('data-wa-mobile-ratio', slide.getAttribute('data-wa-desktop-ratio') || '7 / 3');
        image.src = desktopUrl;
        onChange();
      }, { once: true });

      onChange();
    });
  }

  function mountNativeHero(root, config) {
    var mount = root.querySelector('[data-wa-hero-native]');
    var hero = mount && mount.closest('.wa-hero');
    var counter = root.querySelector('[data-wa-hero-counter]');
    var source = nativeHeroSlider();

    if (!mount) return;

    if (!source.slider || !source.slides.length) {
      var fallback = document.createElement('img');
      fallback.className = 'wa-hero__fallback';
      fallback.src = normalizeAssetBase(config.assetBase) + 'hero-sedacky.jpg';
      fallback.alt = 'Svetlá obývačka s pohodlnou sedacou súpravou';
      fallback.setAttribute('fetchpriority', 'high');
      mount.replaceChildren(fallback);
      if (hero) hero.classList.add('wa-hero--fallback');
      if (counter) counter.textContent = '01 / 01';
      return;
    }

    /* Presunutie zachová pôvodný Webareal slider, jeho časovanie aj obsluhu.
       Nevytvára sa druhý obrázok ani vlastný interval na striedanie bannerov. */
    mount.replaceChildren(source.slider);
    source.slider.classList.add('wa-home-native-slider');
    if (hero) hero.classList.add('wa-hero--native');

    function isVisible(slide) {
      if (slide.style.display) return slide.style.display !== 'none';
      return window.getComputedStyle(slide).display !== 'none';
    }

    function syncHeroState() {
      var activeIndex = source.slides.findIndex(isVisible);
      var index = activeIndex >= 0 ? activeIndex : 0;
      var activeSlide = source.slides[index];
      var isGraphic = activeSlide && activeSlide.getAttribute('data-wa-banner-mode') === 'graphic';

      if (counter) {
        counter.textContent = String(index + 1).padStart(2, '0') + ' / ' +
          String(source.slides.length).padStart(2, '0');
      }

      if (!hero) return;
      hero.classList.toggle('wa-hero--graphic-active', Boolean(isGraphic));

      if (isGraphic) {
        hero.style.setProperty('--wa-hero-desktop-ratio', activeSlide.getAttribute('data-wa-desktop-ratio') || '7 / 3');
        hero.style.setProperty('--wa-hero-mobile-ratio', activeSlide.getAttribute('data-wa-mobile-ratio') || '4 / 5');
      } else {
        hero.style.removeProperty('--wa-hero-desktop-ratio');
        hero.style.removeProperty('--wa-hero-mobile-ratio');
      }
    }

    source.slides.forEach(function (slide) {
      prepareResponsiveBanner(slide, config, syncHeroState);
    });

    syncHeroState();

    if (source.slides.length > 1 && 'MutationObserver' in window) {
      var observer = new MutationObserver(function () {
        syncHeroState();
      });

      source.slides.forEach(function (slide) {
        observer.observe(slide, { attributes: true, attributeFilter: ['style', 'class'] });
      });
    }
  }

  function hashText(value) {
    var hash = 2166136261;
    for (var index = 0; index < value.length; index += 1) {
      hash ^= value.charCodeAt(index);
      hash = Math.imul(hash, 16777619);
    }
    return hash >>> 0;
  }

  function dailyProductSelection(products, count) {
    var today = new Date();
    var dailySeed = [today.getFullYear(), today.getMonth() + 1, today.getDate()].join('-');

    return products
      .map(function (product, index) {
        var productId = product.getAttribute('data-id') || String(index);
        return { product: product, score: hashText(dailySeed + ':' + productId) };
      })
      .sort(function (left, right) { return left.score - right.score; })
      .slice(0, Math.max(1, count))
      .map(function (item) { return item.product; });
  }

  function mountNativeProducts(root, productCount) {
    var slot = root.querySelector('[data-wa-products-slot]');
    var nativeProducts = document.querySelector('#incenterpage > .products_wrap.full');

    if (!slot) return;

    if (!nativeProducts) {
      slot.innerHTML = '<p class="wa-products__fallback">Aktuálnu ponuku nájdete v sekcii <a href="/TOVAR-SKLADOM-c50_0_1.htm">Tovar skladom</a>.</p>';
      return;
    }

    var container = nativeProducts.querySelector('.product_wraper');
    var products = container
      ? Array.prototype.filter.call(container.children, function (item) {
          return item.classList.contains('product');
        })
      : [];

    if (products.length) {
      var selected = dailyProductSelection(products, Math.min(productCount, products.length));

      products.forEach(function (product) {
        var visible = selected.indexOf(product) !== -1;
        product.hidden = !visible;
        product.classList.toggle('wa-home-product--visible', visible);
        product.setAttribute('aria-hidden', visible ? 'false' : 'true');
      });

      selected.forEach(function (product) {
        container.appendChild(product);
      });
    }

    nativeProducts.classList.add('wa-home-native-products');
    slot.replaceChildren(nativeProducts);
    slot.removeAttribute('aria-live');
  }

  function mountNativeBlog(root) {
    var slot = root.querySelector('[data-wa-blog-slot]');
    var section = root.querySelector('.wa-inspiration');
    var nativeBlog = document.querySelector('#centerpage > [class*="homepage_blog_"]');

    if (!slot) return;

    function showFallback() {
      slot.innerHTML = '<p class="wa-blog__fallback">Najnovšie články nájdete na našom <a href="/blog">blogu</a>.</p>';
      if (section) section.classList.add('wa-inspiration--ready');
      slot.removeAttribute('aria-live');
    }

    if (!nativeBlog) {
      showFallback();
      return;
    }

    var articles = Array.prototype.filter.call(nativeBlog.children, function (item) {
      return item.classList.contains('article');
    });

    if (!articles.length) {
      showFallback();
      return;
    }

    articles.forEach(function (article, index) {
      var image = article.querySelector('.image img');
      var detail = article.querySelector('.detail-btn');

      article.classList.add('wa-home-blog-card');
      article.classList.toggle('wa-home-blog-card--featured', index === 0);
      if (image) image.loading = 'lazy';
      if (detail) detail.textContent = 'Čítať článok →';
    });

    nativeBlog.classList.add('wa-home-native-blog');
    nativeBlog.setAttribute('aria-label', 'Najnovšie články z blogu');
    slot.replaceChildren(nativeBlog);
    slot.removeAttribute('aria-live');
    if (section) section.classList.add('wa-inspiration--ready');
  }

  function showMobileSearchField() {
    if (document.getElementById('wa-mobile-search-field')) return;

    var style = document.createElement('style');
    style.id = 'wa-mobile-search-field';
    style.textContent = '@media only screen and (max-width:767px){'
      + 'html body #page .myheader{padding-bottom:62px;height:auto}'
      + 'html body #page .myheader #search{position:absolute !important;top:auto !important;bottom:8px !important;left:12px !important;right:12px !important;width:auto !important;max-width:none !important;height:auto !important;margin:0 !important;border:1.5px solid #171613 !important;background:#fff !important;border-radius:999px !important;padding:0 4px 0 16px !important;box-shadow:none !important;z-index:40}'
      + 'html body #page .myheader #search:focus-within{border-color:#40b3df !important;box-shadow:0 0 0 3px rgba(64,179,223,.18) !important}'
      + 'html body.search_act #page .myheader #search,html body.search_act #search{position:absolute !important;top:auto !important;bottom:8px !important;left:12px !important;right:12px !important;width:auto !important;max-width:none !important;margin:0 !important;transform:none !important}'
      + 'body.search_act #page::after{content:none !important;display:none !important}'
      + 'html body #page .myheader #search #searchForm,html body #page .myheader #search #searchForm:focus-within{width:100% !important;display:flex !important;align-items:center;border:0 !important;box-shadow:none !important}'
      + 'html body #page .myheader #search,html body #page .myheader #search *{-webkit-tap-highlight-color:transparent}'
      + 'html body #page .myheader #search #searchForm #q:focus,html body #page .myheader #search #searchForm #q:focus-visible{outline:none !important;box-shadow:none !important}'
      + 'html body #page .myheader #search #searchForm p{display:block !important;flex:1 1 auto;width:auto !important;margin:0 !important;min-width:0}'
      + 'html body #page .myheader #search #searchForm #q{display:block !important;width:100% !important;height:44px !important;min-height:44px !important;padding:0 8px 0 0 !important;margin:0 !important;font-size:16px !important;line-height:1.2 !important;color:#171613 !important;background:transparent !important;border:0 !important;box-shadow:none !important}'
      + 'html body #page .myheader #search #searchForm #q::placeholder{color:#5c574f !important;opacity:1 !important}'
      + '}';
    document.head.appendChild(style);
  }

  function setSearchPlaceholder() {
    var input = document.getElementById('q');
    if (input) input.placeholder = 'Hľadám sedačku, posteľ, skriňu…';
  }

  // Webareal zapína našepkávač iba pri načítaní v desktopovom rozložení
  // (#responsive_layout_large); na mobile ho zapneme s rovnakými voľbami.
  function enableMobileAutocomplete() {
    var $ = window.jQuery;
    var BS = window.BS;
    if (!$ || !$.fn || !$.fn.bsautocomplete || !BS || !BS.Request) return;

    var $input = $('#q');
    if (!$input.length || $input.hasClass('ui-autocomplete-input')) return;

    $input.bsautocomplete({
      minLength: 3,
      delay: 500,
      source: function (request, response) {
        var exactPhrase = $('#search_exact_phrase').is(':checked') ? 1 : 0;
        var ajaxRequest = BS.extend(BS.Request.$default, {
          data: {
            action: 'Search_autocompleter',
            id_zakaznik: BS.User.id,
            term: request.term,
            exact_phrase: exactPhrase,
            source_service: $('#source_service').val()
          },
          timeout: 2000,
          success: function (data) {
            BS.Fce.hide_top_bar_loading();
            $('.ui-autocomplete').data('total_category', data.total_categories);
            $('.ui-autocomplete').data('total_product', data.total_products);
            response(data.found_items.length ? data.found_items : [{ type: 'no_results_found' }]);
          },
          error: function () {
            BS.Fce.hide_top_bar_loading();
            response([{ type: 'too_ambiguous' }]);
          }
        });
        $.ajax(ajaxRequest);
      },
      select: function (event, ui) {
        window.location.href = ui.item.url;
      },
      open: function () {
        if (BS.Fce.call_conversion_request) {
          BS.Fce.call_conversion_request('search', { search_term: $input.val() });
        }
        $('.ui-autocomplete').addClass('search_autocomplete');
      },
      search: function () {
        var query = $input.val();
        if (!query
          || query.length > BS.User.max_search_query_length
          || query.split(' ').length > BS.User.max_autocomplete_words_count) {
          $('.ui-autocomplete').hide();
          return false;
        }
        BS.Fce.show_top_bar_loading();
      },
      response: function () {
        BS.Fce.hide_top_bar_loading();
      }
    });
  }

  function keepMobileSearchText() {
    if (window.__waMobileSearchGuard) return;
    window.__waMobileSearchGuard = true;

    document.addEventListener('click', function (event) {
      if (window.innerWidth > 767) return;

      var form = document.getElementById('searchForm');
      var input = document.getElementById('q');
      if (!form || !input || form.contains(event.target)) return;

      var value = input.value;
      if (!value) return;

      setTimeout(function () {
        if (input.value !== value) input.value = value;
      }, 0);
    }, true);
  }

  function initHomepage() {
    if (!document.body.classList.contains('home')) return;

    var root = document.querySelector('[data-wa-homepage]');
    if (!root || root.getAttribute('data-wa-initialized') === 'true') return;

    root.setAttribute('data-wa-initialized', 'true');
    var config = mergeConfig();

    loadHomepageFonts();
    applyAssets(root, config.assetBase);
    applyRatings(root, config.ratings);
    mountNativeHero(root, config);
    mountNativeProducts(root, config.productCount);
    mountNativeBlog(root);
    document.body.classList.add('wa-home-ready');
  }

  showMobileSearchField();
  keepMobileSearchText();

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', setSearchPlaceholder, { once: true });
    document.addEventListener('DOMContentLoaded', initHomepage, { once: true });
  } else {
    setSearchPlaceholder();
    initHomepage();
  }

  if (window.jQuery) {
    window.jQuery(function () { setTimeout(enableMobileAutocomplete, 0); });
  }
})();
