/*
 * Celena CMS — Default theme JS (Bunzo)
 * Без зависимостей. Запускается после DOMContentLoaded.
 */
(function () {
  'use strict';

  function ready(fn) {
    if (document.readyState !== 'loading') fn();
    else document.addEventListener('DOMContentLoaded', fn);
  }

  /* ──────── Hero slider ──────── */
  function initHero() {
    var hero = document.querySelector('[data-bz-hero]');
    if (!hero) return;
    var thumbs = hero.querySelectorAll('[data-bz-hero-thumb]');
    var mainImg = hero.querySelector('[data-bz-hero-main-img]');
    if (!thumbs.length || !mainImg) return;

    var titleEl = hero.querySelector('[data-bz-hero-title]');
    var tagEl   = hero.querySelector('[data-bz-hero-tag]');
    var dateEl  = hero.querySelector('[data-bz-hero-date]');
    var viewsEl = hero.querySelector('[data-bz-hero-views]');
    var linkEl  = hero.querySelector('[data-bz-hero-link]');

    function setActive(idx) {
      var thumb = thumbs[idx];
      if (!thumb) return;
      thumbs.forEach(function (t, i) {
        t.classList.toggle('is-active', i === idx);
      });
      var src   = thumb.getAttribute('data-src')   || '';
      var title = thumb.getAttribute('data-title') || '';
      var url   = thumb.getAttribute('data-url')   || '#';
      var tag   = thumb.getAttribute('data-tag')   || 'Featured';
      var date  = thumb.getAttribute('data-date')  || '';
      var views = thumb.getAttribute('data-views') || '';

      if (src) { mainImg.src = src; mainImg.alt = title; }
      if (titleEl) titleEl.textContent = title;
      if (tagEl)   tagEl.textContent   = tag;
      if (dateEl)  dateEl.textContent  = date;
      if (viewsEl) viewsEl.textContent = views;
      if (linkEl)  linkEl.setAttribute('href', url);
    }

    thumbs.forEach(function (t, i) {
      t.addEventListener('click', function () { setActive(i); });
    });
    setActive(0);
  }

  /* ──────── Burger menu ──────── */
  function initBurger() {
    var burger = document.querySelector('[data-bz-burger]');
    var menu = document.querySelector('[data-bz-menu]');
    if (!burger || !menu) return;
    burger.addEventListener('click', function () {
      menu.classList.toggle('is-open');
    });
    document.addEventListener('click', function (e) {
      if (!menu.contains(e.target) && !burger.contains(e.target)) {
        menu.classList.remove('is-open');
      }
    });
  }

  /* ──────── Section carousel arrows ──────── */
  function initCarousels() {
    document.querySelectorAll('[data-bz-carousel]').forEach(function (carousel) {
      var prev = carousel.querySelector('[data-bz-carousel-prev]');
      var next = carousel.querySelector('[data-bz-carousel-next]');
      var track = carousel.querySelector('[data-bz-carousel-track]');
      if (!track) return;
      function step(dir) {
        var amount = Math.max(track.clientWidth * 0.8, 200);
        track.scrollBy({ left: dir * amount, behavior: 'smooth' });
      }
      if (prev) prev.addEventListener('click', function () { step(-1); });
      if (next) next.addEventListener('click', function () { step(1); });
    });
  }

  /* ──────── Video modal ──────── */
  function initVideoModal() {
    var modal = document.querySelector('[data-bz-video-modal]');
    if (!modal) return;
    var iframe = modal.querySelector('iframe');
    var closeBtn = modal.querySelector('[data-bz-video-close]');

    function close() {
      modal.setAttribute('hidden', '');
      if (iframe) iframe.src = '';
    }
    function openWith(url) {
      if (!iframe) return;
      iframe.src = url;
      modal.removeAttribute('hidden');
    }
    document.addEventListener('click', function (e) {
      var trigger = e.target.closest('[data-bz-video-open]');
      if (!trigger) return;
      var url = trigger.getAttribute('data-bz-video-open');
      if (!url) return;
      e.preventDefault();
      // Преобразуем YouTube/Vimeo в embed-формат
      var embed = toEmbedUrl(url);
      openWith(embed);
    });
    if (closeBtn) closeBtn.addEventListener('click', close);
    modal.addEventListener('click', function (e) {
      if (e.target === modal) close();
    });
    document.addEventListener('keydown', function (e) {
      if (e.key === 'Escape' && !modal.hasAttribute('hidden')) close();
    });
  }
  function toEmbedUrl(url) {
    // youtu.be/ID  → youtube.com/embed/ID
    var ytShort = url.match(/youtu\.be\/([\w-]+)/);
    if (ytShort) return 'https://www.youtube.com/embed/' + ytShort[1] + '?autoplay=1';
    // youtube.com/watch?v=ID
    var ytLong = url.match(/[?&]v=([\w-]+)/);
    if (ytLong && /youtube\.com/.test(url)) return 'https://www.youtube.com/embed/' + ytLong[1] + '?autoplay=1';
    // vimeo.com/ID
    var vimeo = url.match(/vimeo\.com\/(\d+)/);
    if (vimeo) return 'https://player.vimeo.com/video/' + vimeo[1] + '?autoplay=1';
    return url; // как есть
  }

  /* ──────── Newsletter заглушка ──────── */
  function initNewsletter() {
    document.querySelectorAll('[data-bz-newsletter]').forEach(function (form) {
      form.addEventListener('submit', function (e) {
        e.preventDefault();
        var msg = form.querySelector('[data-bz-newsletter-msg]');
        if (msg) {
          msg.textContent = 'Спасибо! Подписка скоро будет реализована — пока что мы сохранили ваш интерес.';
        }
      });
    });
  }

  /* ──────── Theme switch (синхронизация с celena.js) ──────── */
  function initThemeSwitch() {
    var btns = document.querySelectorAll('[data-bz-theme]');
    if (!btns.length) return;
    function getCurrent() {
      try { return localStorage.getItem('celena_theme') || 'auto'; } catch (e) { return 'auto'; }
    }
    function refresh() {
      var cur = getCurrent();
      btns.forEach(function (b) {
        b.setAttribute('aria-pressed', b.getAttribute('data-bz-theme') === cur ? 'true' : 'false');
      });
    }
    btns.forEach(function (b) {
      b.addEventListener('click', function () {
        // celena.js слушает [data-celena-theme] — у нас тот же атрибут уже стоит,
        // мы только обновляем aria-pressed.
        setTimeout(refresh, 30);
      });
    });
    refresh();
  }

  ready(function () {
    initHero();
    initBurger();
    initCarousels();
    initVideoModal();
    initNewsletter();
    initThemeSwitch();
  });
})();
