/* Celena CMS — runtime: async block loader, theme toggle, CSRF helpers. ~3 KB minified. */
(function () {
  'use strict';

  var meta = document.querySelector('meta[name="csrf-token"]');
  var CSRF = meta ? meta.getAttribute('content') : '';

  function fetchBlock(el) {
    if (el.__celenaLoaded) return;
    var url = el.getAttribute('data-celena-async');
    if (!url) return;
    el.__celenaLoaded = true;
    el.classList.add('is-loading');
    fetch(url, {
      method: 'GET',
      credentials: 'same-origin',
      headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'X-CSRF-Token': CSRF,
        'Accept': 'text/html,application/json'
      }
    })
      .then(function (r) {
        var ct = r.headers.get('content-type') || '';
        if (ct.indexOf('application/json') !== -1) return r.json().then(function (j) { return j.html || ''; });
        return r.text();
      })
      .then(function (html) {
        el.innerHTML = html;
        el.classList.remove('is-loading');
        el.classList.add('is-loaded');
        el.dispatchEvent(new CustomEvent('celena:loaded', { bubbles: true }));
        var poll = el.getAttribute('data-celena-poll');
        if (poll) {
          var ms = parsePoll(poll);
          if (ms > 0) {
            setTimeout(function () { el.__celenaLoaded = false; fetchBlock(el); }, ms);
          }
        }
      })
      .catch(function (err) {
        el.classList.remove('is-loading');
        el.classList.add('is-error');
        el.innerHTML = '<div class="celena-async-error">Failed to load.</div>';
        if (window.console) console.warn('[celena] async load failed', url, err);
      });
  }

  function parsePoll(v) {
    var m = /^(\d+)\s*(ms|s|m)?$/.exec(v.trim());
    if (!m) return 0;
    var n = parseInt(m[1], 10);
    switch (m[2] || 's') {
      case 'ms': return n;
      case 's':  return n * 1000;
      case 'm':  return n * 60000;
    }
    return 0;
  }

  function initBlocks() {
    var nodes = document.querySelectorAll('[data-celena-async]');
    nodes.forEach(function (el) {
      var trigger = el.getAttribute('data-celena-trigger') || 'load';
      if (trigger === 'load') {
        fetchBlock(el);
      } else if (trigger === 'visible' && 'IntersectionObserver' in window) {
        var io = new IntersectionObserver(function (entries) {
          entries.forEach(function (e) {
            if (e.isIntersecting) {
              fetchBlock(e.target);
              io.unobserve(e.target);
            }
          });
        }, { rootMargin: '100px' });
        io.observe(el);
      }
      // 'manual' — ничего не делаем; вызывать window.Celena.refresh(el)
    });
  }

  /* Тема: сохранение пользовательского выбора + авто-режим (18:00–07:00 локального времени). */
  var THEME_KEY = 'celena_theme';
  function applyTheme(mode) {
    var theme = mode;
    if (mode === 'auto') {
      var h = new Date().getHours();
      theme = (h >= 18 || h < 7) ? 'dark' : 'light';
    }
    document.documentElement.setAttribute('data-theme', theme);
  }
  function setTheme(mode) {
    try { localStorage.setItem(THEME_KEY, mode); } catch (e) {}
    applyTheme(mode);
  }
  function currentThemeMode() {
    try { return localStorage.getItem(THEME_KEY) || 'auto'; } catch (e) { return 'auto'; }
  }
  function initTheme() {
    applyTheme(currentThemeMode());
    // Набор отдельных кнопок (фронт сайта): каждая задаёт конкретный режим.
    document.querySelectorAll('[data-celena-theme]').forEach(function (btn) {
      btn.addEventListener('click', function () {
        setTheme(btn.getAttribute('data-celena-theme'));
      });
    });
    // Компактный переключатель (админка): одна кнопка циклически меняет тему.
    var cycleOrder = ['light', 'dark', 'auto'];
    document.querySelectorAll('[data-celena-theme-cycle]').forEach(function (btn) {
      document.documentElement.setAttribute('data-theme-mode', currentThemeMode());
      btn.addEventListener('click', function () {
        var next = cycleOrder[(cycleOrder.indexOf(currentThemeMode()) + 1) % cycleOrder.length];
        setTheme(next);
        document.documentElement.setAttribute('data-theme-mode', next);
      });
    });
  }

  /* Перехват async-форм: data-celena-form="<target-selector>" */
  function initForms() {
    document.addEventListener('submit', function (ev) {
      var form = ev.target;
      if (!form.matches || !form.matches('form[data-celena-form]')) return;
      ev.preventDefault();
      var target = document.querySelector(form.getAttribute('data-celena-form')) || form;
      var fd = new FormData(form);
      target.classList.add('is-loading');
      fetch(form.action || window.location.href, {
        method: form.method || 'POST',
        body: fd,
        credentials: 'same-origin',
        headers: { 'X-Requested-With': 'XMLHttpRequest', 'X-CSRF-Token': CSRF }
      })
        .then(function (r) { return r.text(); })
        .then(function (html) {
          target.innerHTML = html;
          target.classList.remove('is-loading');
          target.dispatchEvent(new CustomEvent('celena:form:done', { bubbles: true }));
        })
        .catch(function () { target.classList.remove('is-loading'); });
    });
  }

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

  /* GDPR-баннер: показать, если сервер его отрендерил и в localStorage нет согласия. */
  var GDPR_KEY = 'celena_gdpr_consent';
  function initGdpr() {
    var el = document.querySelector('[data-gdpr]');
    if (!el) return;
    var stored = null;
    try { stored = localStorage.getItem(GDPR_KEY); } catch (e) {}
    if (stored === 'accept' || stored === 'decline') return;
    el.hidden = false;
    requestAnimationFrame(function () { el.classList.add('is-visible'); });
    function dismiss(choice) {
      try { localStorage.setItem(GDPR_KEY, choice); } catch (e) {}
      el.classList.remove('is-visible');
      setTimeout(function () { el.hidden = true; }, 260);
    }
    var a = el.querySelector('[data-gdpr-accept]');
    var d = el.querySelector('[data-gdpr-decline]');
    if (a) a.addEventListener('click', function () { dismiss('accept'); });
    if (d) d.addEventListener('click', function () { dismiss('decline'); });
  }

  ready(function () {
    initTheme();
    initBlocks();
    initForms();
    initGdpr();
  });

  window.Celena = {
    refresh: function (el) { if (typeof el === 'string') el = document.querySelector(el); if (el) { el.__celenaLoaded = false; fetchBlock(el); } },
    setTheme: setTheme,
    csrf: function () { return CSRF; }
  };
})();
