/* Error Debug Page — interactive behavior (inlined by ErrorRenderer) */

function initErrorDebug(root = document) {
  if (!root || typeof root.querySelectorAll !== 'function') {
    return { destroy: () => {} };
  }

  const body = root.body;
  if (!(body instanceof HTMLElement)) {
    return { destroy: () => {} };
  }
  if (body.dataset.errorDebugBound === '1') {
    return { destroy: () => {} };
  }
  body.dataset.errorDebugBound = '1';

  const cleanupFns = [];
  const bind = (target, eventName, handler, options = undefined) => {
    if (!target || typeof target.addEventListener !== 'function') {
      return;
    }
    target.addEventListener(eventName, handler, options);
    cleanupFns.push(() => target.removeEventListener(eventName, handler, options));
  };

  const tabs = Array.from(root.querySelectorAll('.app-error-debug-tab'));
  const panels = Array.from(root.querySelectorAll('.app-error-debug-panel'));

  const activateTab = (tab) => {
    if (!(tab instanceof HTMLElement)) {
      return;
    }
    const target = tab.dataset.panel;
    tabs.forEach((value) => {
      if (value instanceof HTMLElement) {
        value.classList.remove('active');
        value.setAttribute('aria-selected', 'false');
        value.setAttribute('tabindex', '-1');
      }
    });
    panels.forEach((panel) => {
      if (panel instanceof HTMLElement) {
        panel.classList.remove('active');
      }
    });
    tab.classList.add('active');
    tab.setAttribute('aria-selected', 'true');
    tab.setAttribute('tabindex', '0');
    const panel = root.getElementById(target || '');
    if (panel instanceof HTMLElement) {
      panel.classList.add('active');
    }
  };

  tabs.forEach((tab) => {
    if (!(tab instanceof HTMLElement)) {
      return;
    }

    bind(tab, 'click', () => {
      activateTab(tab);
    });

    bind(tab, 'keydown', (event) => {
      if (!(event instanceof KeyboardEvent) || tabs.length === 0) {
        return;
      }
      const currentIndex = tabs.indexOf(tab);
      if (currentIndex < 0) {
        return;
      }

      let nextIndex = currentIndex;
      if (event.key === 'ArrowRight') {
        nextIndex = (currentIndex + 1) % tabs.length;
      } else if (event.key === 'ArrowLeft') {
        nextIndex = (currentIndex - 1 + tabs.length) % tabs.length;
      } else if (event.key === 'Home') {
        nextIndex = 0;
      } else if (event.key === 'End') {
        nextIndex = tabs.length - 1;
      } else {
        return;
      }

      event.preventDefault();
      const nextTab = tabs[nextIndex];
      if (!(nextTab instanceof HTMLElement)) {
        return;
      }
      activateTab(nextTab);
      nextTab.focus();
    });
  });

  root.querySelectorAll('.app-error-debug-frame__toggle').forEach((toggle) => {
    bind(toggle, 'click', () => {
      const frame = toggle.closest('.app-error-debug-frame');
      if (!(frame instanceof HTMLElement) || !(toggle instanceof HTMLElement)) {
        return;
      }
      const isOpen = frame.classList.toggle('open');
      toggle.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
    });
  });

  root.querySelectorAll('.app-error-debug-frame').forEach((frame) => {
    const toggle = frame.querySelector('.app-error-debug-frame__toggle');
    if (!(frame instanceof HTMLElement) || !(toggle instanceof HTMLElement)) {
      return;
    }
    toggle.setAttribute('aria-expanded', frame.classList.contains('open') ? 'true' : 'false');
  });

  root.querySelectorAll('.app-error-debug-query__toggle').forEach((toggle) => {
    bind(toggle, 'click', () => {
      const query = toggle.closest('.app-error-debug-query');
      if (!(query instanceof HTMLElement) || !(toggle instanceof HTMLElement)) {
        return;
      }
      const isOpen = query.classList.toggle('open');
      toggle.setAttribute('aria-expanded', isOpen ? 'true' : 'false');
    });
  });

  root.querySelectorAll('.app-error-debug-copy-button').forEach((button) => {
    bind(button, 'click', async (event) => {
      event.stopPropagation();
      if (!(button instanceof HTMLElement)) {
        return;
      }
      const text = button.dataset.copy;
      if (!text || !navigator?.clipboard?.writeText) {
        return;
      }

      try {
        await navigator.clipboard.writeText(text);
        button.classList.add('copied');
        const original = button.innerHTML;
        button.innerHTML = '<svg width="14" height="14" viewBox="0 0 16 16" fill="currentColor"><path d="M13.854 3.646a.5.5 0 0 1 0 .708l-7 7a.5.5 0 0 1-.708 0l-3.5-3.5a.5.5 0 1 1 .708-.708L6.5 10.293l6.646-6.647a.5.5 0 0 1 .708 0z"/></svg>';
        const timerId = window.setTimeout(() => {
          button.classList.remove('copied');
          button.innerHTML = original;
        }, 1500);
        cleanupFns.push(() => window.clearTimeout(timerId));
      } catch {
        // Clipboard API may not be available in all contexts.
      }
    });
  });

  const destroy = () => {
    cleanupFns.forEach((cleanup) => cleanup());
    cleanupFns.length = 0;
    delete body.dataset.errorDebugBound;
  };

  return { destroy };
}

if (typeof window !== 'undefined' && typeof document !== 'undefined') {
  const api = initErrorDebug(document);
  window.__appErrorDebugApi = api;
}
