/* markemacht.de — Interaktionen
 * - Wirkung-Switch (monolithisch | editorial) + localStorage-Persistenz
 * - Mobile Drawer
 * - Reveal (IntersectionObserver, rein visuell)
 * - Keyboard: ESC schließt Drawer
 */
(function () {
  'use strict';

  function getCurrentPage() {
    const file = window.location.pathname.split('/').pop() || 'index.html';
    if (file === 'index.html') return 'start';
    if (file === 'manifest.html') return 'manifest';
    if (file === 'methode.html') return 'methode';
    if (file === 'denken.html' || file.startsWith('denken-')) return 'denken';
    return '';
  }

  function initActiveNavigation() {
    const current = getCurrentPage();
    document.querySelectorAll('[data-nav-page]').forEach((link) => {
      const isActive = link.getAttribute('data-nav-page') === current;
      link.classList.toggle('is-active', isActive);
      if (isActive) {
        link.setAttribute('aria-current', 'page');
      } else {
        link.removeAttribute('aria-current');
      }
    });
  }

  /* ---------- Wirkung ---------------------------------------------------- */

  const STORAGE_KEY = 'mm-wirkung';
  const VALID = ['monolith', 'editorial'];
  const DEFAULT = 'monolith';

 

  function getStored() {
    try {
      const v = localStorage.getItem(STORAGE_KEY);
      return VALID.includes(v) ? v : null;
    } catch (_) { return null; }
  }

  function ensureThemeFonts(mode) {
    const id = `mm-fonts-${mode}`;
    if (document.getElementById(id)) return;
    const link = document.createElement('link');
    link.id = id;
    link.rel = 'stylesheet';
    link.href = `./assets/fonts/fonts-${mode}.css`;
    document.head.appendChild(link);
  }

  function applyMode(mode) {
    if (!VALID.includes(mode)) mode = DEFAULT;
    document.documentElement.setAttribute('data-theme', mode);
    ensureThemeFonts(mode);
    try { localStorage.setItem(STORAGE_KEY, mode); } catch (_) {}
    syncButtons(mode);
  }

  function syncButtons(mode) {
    document.querySelectorAll('[data-wirkung]').forEach((btn) => {
      const pressed = btn.getAttribute('data-wirkung') === mode;
      btn.setAttribute('aria-pressed', pressed ? 'true' : 'false');
    });
  }

  function initWirkung() {
    const initial = getStored() || DEFAULT;
    applyMode(initial);

    document.querySelectorAll('[data-wirkung]').forEach((btn) => {
      btn.addEventListener('click', () => {
        const mode = btn.getAttribute('data-wirkung');
        applyMode(mode);
      });
    });
  }

  /* ---------- Mobile Drawer --------------------------------------------- */

  function initDrawer() {
    const drawer = document.querySelector('[data-mobile-drawer]');
    if (!drawer) return;

    const openBtns = document.querySelectorAll('[data-drawer-open]');
    const closeBtns = document.querySelectorAll('[data-drawer-close]');

    function open() {
      drawer.classList.add('is-open');
      document.body.classList.add('drawer-open');
      drawer.setAttribute('aria-hidden', 'false');
      openBtns.forEach((btn) => btn.setAttribute('aria-expanded', 'true'));
      const firstLink = drawer.querySelector('a, button');
      if (firstLink) firstLink.focus();
    }
    function close() {
      drawer.classList.remove('is-open');
      document.body.classList.remove('drawer-open');
      drawer.setAttribute('aria-hidden', 'true');
      openBtns.forEach((btn) => btn.setAttribute('aria-expanded', 'false'));
    }

    openBtns.forEach((b) => b.addEventListener('click', open));
    closeBtns.forEach((b) => b.addEventListener('click', close));

    drawer.querySelectorAll('a[href]').forEach((a) => {
      a.addEventListener('click', close);
    });

    document.addEventListener('keydown', (e) => {
      if (e.key === 'Escape' && drawer.classList.contains('is-open')) {
        close();
      }
    });
  }

  /* ---------- Audit Modal ------------------------------------------------ */

  function initAuditModal() {
    const modal = document.querySelector('[data-audit-modal]');
    if (!modal) return;

    const openButtons = document.querySelectorAll('[data-audit-modal-open]');
    const closeButtons = modal.querySelectorAll('[data-audit-modal-close]');
    const form = modal.querySelector('[data-audit-form]');
    const formPanel = modal.querySelector('[data-audit-form-panel]');
    const successPanel = modal.querySelector('[data-audit-form-success]');
    const status = modal.querySelector('[data-audit-form-status]');
    const focusableSelector = 'a[href], button:not([disabled]), input:not([disabled]), textarea:not([disabled])';
    let lastActive = null;

    function getFocusable() {
      return Array.from(modal.querySelectorAll(focusableSelector))
        .filter((el) => el.offsetParent !== null && el.tabIndex >= 0);
    }

    function open() {
      lastActive = document.activeElement;
      modal.classList.add('is-open');
      modal.setAttribute('aria-hidden', 'false');
      document.body.classList.add('modal-open');
      const first = getFocusable()[0];
      if (first) first.focus();
    }

    function resetFormState() {
      if (formPanel) formPanel.hidden = false;
      if (successPanel) successPanel.hidden = true;
      if (status) status.textContent = '';
      if (form) form.reset();
    }

    function showSuccess() {
      if (formPanel) formPanel.hidden = true;
      if (successPanel) {
        successPanel.hidden = false;
        const focusTarget = successPanel.querySelector('button, [href], input, textarea');
        if (focusTarget) focusTarget.focus();
      }
    }

    function close() {
      modal.classList.remove('is-open');
      modal.setAttribute('aria-hidden', 'true');
      document.body.classList.remove('modal-open');
      resetFormState();
      if (lastActive && typeof lastActive.focus === 'function') {
        lastActive.focus();
      }
    }

    resetFormState();

    openButtons.forEach((button) => {
      button.addEventListener('click', open);
    });
    closeButtons.forEach((button) => {
      button.addEventListener('click', close);
    });
    modal.addEventListener('click', (event) => {
      if (event.target === modal) close();
    });
    document.addEventListener('keydown', (event) => {
      if (!modal.classList.contains('is-open')) return;
      if (event.key === 'Escape') {
        close();
        return;
      }
      if (event.key !== 'Tab') return;

      const focusable = getFocusable();
      if (!focusable.length) return;
      const first = focusable[0];
      const last = focusable[focusable.length - 1];
      if (event.shiftKey && document.activeElement === first) {
        event.preventDefault();
        last.focus();
      } else if (!event.shiftKey && document.activeElement === last) {
        event.preventDefault();
        first.focus();
      }
    });

    if (!form) return;

    const ENDPOINT = './assets/php/send-anfrage.php';
    const submitButton = form.querySelector('[type="submit"]');

    form.addEventListener('submit', async (event) => {
      event.preventDefault();

      if (!form.checkValidity()) {
        form.reportValidity();
        return;
      }

      if (submitButton) submitButton.disabled = true;
      if (status) status.textContent = 'Anfrage wird gesendet …';

      try {
        const res = await fetch(ENDPOINT, {
          method: 'POST',
          body: new FormData(form),
          headers: { 'Accept': 'application/json' },
        });

        let payload = {};
        try { payload = await res.json(); } catch (_) {}

        if (res.ok && payload.ok) {
          showSuccess();
        } else {
          if (status) {
            status.textContent = payload.message
              || 'Versand fehlgeschlagen. Bitte versuchen Sie es später erneut.';
          }
        }
      } catch (err) {
        console.error(err);
        if (status) {
          status.textContent = 'Verbindung fehlgeschlagen. Bitte versuchen Sie es später erneut.';
        }
      } finally {
        if (submitButton) submitButton.disabled = false;
      }
    });
  }

  /* ---------- Hero Keyvisual (Lazy Load) -------------------------------- */

  function initHeroKeyvisual() {
    const slots = document.querySelectorAll('.monolith');
    if (!slots.length) return;

    /** CSS url() relativ zum app.css auflösen (nicht zur HTML-Seite). */
    const cssBase = (() => {
      const link = document.querySelector('link[rel="stylesheet"][href*="app.css"]');
      return link ? new URL(link.href, window.location.href) : null;
    })();

    const resolveCssUrl = (value) => {
      const match = (value || '').trim().match(/url\(["']?(.+?)["']?\)/);
      if (!match) return null;
      const raw = match[1];
      if (/^([a-z]+:|\/\/)/i.test(raw)) return raw;
      if (cssBase) return new URL(raw, cssBase.href).href;
      return new URL(raw, window.location.href).href;
    };

    const preloadImage = (url) => new Promise((resolve, reject) => {
      const img = new Image();
      img.onload = () => resolve();
      img.onerror = () => reject(new Error(`Hero image failed: ${url}`));
      img.src = url;
    });

    const editorialActive = () =>
      document.documentElement.getAttribute('data-theme') === 'editorial';

    slots.forEach((slot) => {
      const styles = getComputedStyle(slot);
      const monoUrl = resolveCssUrl(styles.getPropertyValue('--hero-monolith'));
      const editUrl = resolveCssUrl(styles.getPropertyValue('--hero-editorial'));

      const loadMono = () => {
        if (slot.classList.contains('is-loaded-mono') || !monoUrl) {
          return Promise.resolve();
        }
        return preloadImage(monoUrl)
          .then(() => slot.classList.add('is-loaded-mono'))
          .catch((err) => console.warn(err));
      };

      const loadEditorial = () => {
        if (slot.classList.contains('is-loaded-editorial') || !editUrl) {
          return Promise.resolve();
        }
        return preloadImage(editUrl)
          .then(() => slot.classList.add('is-loaded-editorial'))
          .catch((err) => console.warn(err));
      };

      const loadForViewport = () => {
        loadMono().then(() => {
          if (editorialActive()) loadEditorial();
        });
      };

      // Editorial-Bild erst bei Bedarf: aktiver Modus, Wechsel oder Hover auf Switch.
      document.querySelectorAll('[data-wirkung="editorial"]').forEach((btn) => {
        btn.addEventListener('mouseenter', loadEditorial, { once: true });
        btn.addEventListener('focus', loadEditorial, { once: true });
      });

      const themeObserver = new MutationObserver(() => {
        if (editorialActive()) loadEditorial();
      });
      themeObserver.observe(document.documentElement, {
        attributes: true,
        attributeFilter: ['data-theme'],
      });

      if (!('IntersectionObserver' in window)) {
        loadForViewport();
        return;
      }

      const target = slot.closest('.hero-keyvisual') || slot.closest('.split-visual') || slot;
      const io = new IntersectionObserver((entries) => {
        entries.forEach((entry) => {
          if (!entry.isIntersecting) return;
          loadForViewport();
          io.unobserve(entry.target);
        });
      }, {
        rootMargin: '120px 0px',
        threshold: 0.01,
      });

      io.observe(target);
    });
  }

  /* ---------- Reveal ----------------------------------------------------- */

  function initReveal() {
    const items = document.querySelectorAll('[data-reveal]');
    if (!items.length) return;

    const prefersReduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    if (prefersReduced || !('IntersectionObserver' in window)) {
      items.forEach((el) => el.classList.add('is-revealed'));
      return;
    }

    const io = new IntersectionObserver((entries) => {
      entries.forEach((entry) => {
        if (!entry.isIntersecting) return;

        const el = entry.target;
        const delay = parseInt(el.getAttribute('data-reveal-delay') || '0', 10);
        window.setTimeout(() => {
          el.classList.add('is-revealed');
        }, delay);
        io.unobserve(el);
      });
    }, {
      threshold: 0.08,
      rootMargin: '0px 0px -5% 0px'
    });

    items.forEach((el) => io.observe(el));
  }

  /* ---------- Scroll position on navigation -------------------------------- */

  function initScrollPosition() {
    if ('scrollRestoration' in history) {
      history.scrollRestoration = 'manual';
    }

    function scrollToTargetOrTop() {
      const hash = location.hash;
      if (hash.length > 1) {
        const target = document.getElementById(decodeURIComponent(hash.slice(1)));
        if (target) {
          target.scrollIntoView();
          return;
        }
      }
      window.scrollTo(0, 0);
    }

    scrollToTargetOrTop();

    window.addEventListener('pageshow', (event) => {
      if (event.persisted) scrollToTargetOrTop();
    });

    requestAnimationFrame(() => {
      const active = document.activeElement;
      if (active && active.closest('.site-footer')) {
        active.blur();
        scrollToTargetOrTop();
      }
    });
  }

  /* ---------- Boot ------------------------------------------------------- */

  function boot() {
    initScrollPosition();
    initActiveNavigation();
    initWirkung();
    initDrawer();
    initAuditModal();
    initHeroKeyvisual();
    initReveal();
  }

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', boot);
  } else {
    boot();
  }
})();
