// 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();

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

  // Check if Ziex exists on the page
  chrome.devtools.inspectedWindow.eval(
    '!!(window.__ZIEX__)',
    (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) => {
          // Handle panel visibility
          panel.onShown.addListener(() => {
            console.log('Ziex DevTools panel opened');
          });

          panel.onHidden.addListener(() => {
            console.log('Ziex DevTools panel hidden');
          });
        }
      );
    }
  );
}
