(function () {
  const placeholders = document.querySelectorAll('[data-sidebar]');
  if (!placeholders.length) return;

  const cache = new Map();
  const body = document.body || document.documentElement;

  function ensureOverlay(layout) {
    let overlay = layout.querySelector('[data-sidebar-overlay]');
    if (!overlay) {
      overlay = document.createElement('div');
      overlay.className = 'sidebar-overlay';
      overlay.setAttribute('data-sidebar-overlay', '');
      layout.appendChild(overlay);
    }
    return overlay;
  }

  function ensureLauncher(layout) {
    let launcher = layout.querySelector('[data-sidebar-launcher]');
    if (launcher) return launcher;
    launcher = document.createElement('div');
    launcher.className = 'sidebar-launcher';
    launcher.setAttribute('data-sidebar-launcher', '');
    launcher.innerHTML = `
      <button class="sidebar-toggle" type="button" aria-label="Toggle sidebar" aria-expanded="false" data-sidebar-toggle>
        <span></span>
        <span></span>
        <span></span>
      </button>
      <a class="launcher-brand" href="/domains/demo/index.html">
        <span class="brand-mark">LS</span>
        <div class="launcher-copy">
          <strong>LeadSniper</strong>
          <span>Workspace</span>
        </div>
      </a>
    `;
    layout.prepend(launcher);
    return launcher;
  }

  function initToolSidebar(placeholder) {
    const layout = placeholder.closest('.tool-layout');
    if (!layout || layout.dataset.sidebarReady === 'true') return;

    ensureLauncher(layout);
    const overlay = ensureOverlay(layout);
    const toggles = layout.querySelectorAll('[data-sidebar-toggle]');
    if (!toggles.length) return;

    const setState = (open) => {
      layout.classList.toggle('sidebar-open', open);
      body.classList.toggle('sidebar-open', open);
      toggles.forEach((btn) => btn.setAttribute('aria-expanded', open ? 'true' : 'false'));
    };

    const toggleState = () => setState(!layout.classList.contains('sidebar-open'));
    toggles.forEach((btn) => btn.addEventListener('click', toggleState));
    overlay.addEventListener('click', () => setState(false));
    document.addEventListener('keydown', (event) => {
      if (event.key === 'Escape') setState(false);
    });

    layout.dataset.sidebarReady = 'true';
  }

  placeholders.forEach((placeholder) => {
    const src = placeholder.getAttribute('data-sidebar-src') || '/domains/demo/includes/sidebar.html';
    if (!cache.has(src)) {
      cache.set(
        src,
        fetch(src, { cache: 'no-cache' })
          .then((res) => {
            if (!res.ok) throw new Error('Failed to load sidebar include');
            return res.text();
          })
          .catch((err) => {
            console.error('Sidebar include error:', err);
            return '';
          })
      );
    }

    cache.get(src).then((html) => {
      if (!html) return;
      placeholder.innerHTML = html;
      placeholder.classList.add('sidebar');

      const activeKey = placeholder.getAttribute('data-active');
      if (activeKey) {
        const activeItem = placeholder.querySelector(`[data-item="${activeKey}"]`);
        if (activeItem) activeItem.classList.add('active');
      }

      initToolSidebar(placeholder);
    });
  });
})();
