// This script runs when DevTools is opened
// It detects if Ziex is present and creates the DevTools panel

let created = false;
let checkCount = 0;

// Listen for page navigation
chrome.devtools.network.onNavigated.addListener(createPanelOnZiexDetected);

// Check for Ziex periodically
const checkZiexInterval = setInterval(createPanelOnZiexDetected, 1000);

// Initial check
createPanelOnZiexDetected();

// Connect to the background service worker so it can forward SPA navigation
// events from the content script to the devtools panel window.
const bgPort = chrome.runtime.connect({ name: 'zx-devtools' });
bgPort.postMessage({ type: 'zx-devtools-init', tabId: chrome.devtools.inspectedWindow.tabId });

// When the panel window is available, relay navigation messages into it.
let panelWindow = null;

bgPort.onMessage.addListener((msg) => {
  if (msg.type === 'zx-navigation' && panelWindow) {
    panelWindow.dispatchEvent(new CustomEvent('zx-navigation', { detail: { href: msg.href } }));
  }
});

function createPanelOnZiexDetected() {
  if (created || checkCount++ > 10) {
    clearInterval(checkZiexInterval);
    return;
  }

  // Check if Ziex exists on the page
  chrome.devtools.inspectedWindow.eval(
    '!!(window.__ZIEX_DEVTOOLS_GLOBAL_HOOK__)',
    (ziexDetected) => {
      if (!ziexDetected || created) return;

      clearInterval(checkZiexInterval);
      created = true;

      // Create the DevTools panel
      chrome.devtools.panels.create(
        'Ziex',
        'icons/zx-icon-dark.svg',
        'pages/index.html', // Pointing to the file generated by ui-zx build
        (panel) => {
          panel.onShown.addListener((win) => {
            panelWindow = win;
          });

          panel.onHidden.addListener(() => {
            panelWindow = null;
          });
        }
      );
    }
  );
}
