/**
 * Kutby Theme Core
 *
 * @package Kutby
 */
(function () {
  'use strict';

  var root = document.documentElement;
  root.classList.add('kutby-js');

  var THEME_KEY = 'kutby-color-scheme';

  function applyDark(on) {
    root.classList.toggle('kutby-dark', on);
    document.body.classList.toggle('kutby-dark', on);
    document.querySelectorAll('[data-kutby-theme-toggle]').forEach(function (btn) {
      btn.setAttribute('aria-pressed', on ? 'true' : 'false');
      btn.setAttribute('aria-label', on ? 'تبديل إلى الوضع النهاري' : 'تبديل المظهر');
    });
  }

  try {
    if (localStorage.getItem(THEME_KEY) === 'dark') {
      applyDark(true);
    }
  } catch (e) {}

  document.querySelectorAll('[data-kutby-theme-toggle]').forEach(function (btn) {
    btn.addEventListener('click', function () {
      var next = !root.classList.contains('kutby-dark');
      applyDark(next);
      try {
        localStorage.setItem(THEME_KEY, next ? 'dark' : 'light');
      } catch (err) {}
    });
  });

  var eduHeader = document.querySelector('[data-kutby-edu-header]');
  if (eduHeader) {
    var onScroll = function () {
      eduHeader.classList.toggle('is-scrolled', window.scrollY > 8);
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
  }

  document.dispatchEvent(new CustomEvent('kutby:ready', { detail: window.kutbyData || {} }));
})();
