'use strict';

(() => {
  const STORAGE_KEY = 'arkhon_theme';
  const CHOICES = ['auto', 'light', 'dark'];
  const media = window.matchMedia ? window.matchMedia('(prefers-color-scheme: dark)') : null;

  function preference() {
    const value = localStorage.getItem(STORAGE_KEY) || 'auto';
    return CHOICES.includes(value) ? value : 'auto';
  }

  function resolve(value = preference()) {
    if (value === 'light' || value === 'dark') return value;
    const hour = new Date().getHours();
    return media?.matches || hour >= 19 || hour < 7 ? 'dark' : 'light';
  }

  function themeDocument(doc, resolved, selected) {
    if (!doc?.documentElement) return;
    doc.documentElement.dataset.theme = resolved;
    doc.documentElement.dataset.themePreference = selected;
    if (doc !== document && doc.head && !doc.querySelector('link[data-arkhon-theme]')) {
      const link = doc.createElement('link');
      link.rel = 'stylesheet';
      link.href = '/css/theme.css?v=5035a';
      link.dataset.arkhonTheme = 'true';
      doc.head.appendChild(link);
    }
  }

  function themeFrames(resolved, selected) {
    document.querySelectorAll('iframe').forEach((frame) => {
      try { themeDocument(frame.contentDocument, resolved, selected); } catch (_) {}
    });
  }

  function renderControls(selected) {
    document.querySelectorAll('[data-theme-choice]').forEach((button) => {
      const active = button.dataset.themeChoice === selected;
      button.classList.toggle('active', active);
      button.setAttribute('aria-pressed', String(active));
    });
  }

  function apply(selected = preference(), options = {}) {
    const safe = CHOICES.includes(selected) ? selected : 'auto';
    const resolved = resolve(safe);
    if (options.persist !== false) localStorage.setItem(STORAGE_KEY, safe);
    themeDocument(document, resolved, safe);
    renderControls(safe);
    themeFrames(resolved, safe);
    const meta = document.querySelector('meta[name="theme-color"]');
    if (meta) meta.content = resolved === 'dark' ? '#0d1119' : '#f7f8fc';
    window.dispatchEvent(new CustomEvent('arkhon:themechange', { detail: { preference: safe, theme: resolved } }));
  }

  function bind() {
    document.querySelectorAll('[data-theme-choice]').forEach((button) => {
      button.addEventListener('click', () => apply(button.dataset.themeChoice));
    });
    document.querySelectorAll('iframe').forEach((frame) => {
      frame.addEventListener('load', () => apply(preference(), { persist: false }));
    });
    new MutationObserver((mutations) => {
      if (mutations.some((mutation) => [...mutation.addedNodes].some((node) => node.nodeType === 1 && (node.matches?.('iframe') || node.querySelector?.('iframe'))))) {
        apply(preference(), { persist: false });
      }
    }).observe(document.body, { childList: true, subtree: true });
  }

  const refreshAuto = () => { if (preference() === 'auto') apply('auto', { persist: false }); };
  media?.addEventListener?.('change', refreshAuto);
  setInterval(refreshAuto, 5 * 60 * 1000);
  window.arkhonTheme = { apply, resolve, preference };
  bind();
  apply(preference(), { persist: false });
})();
