// Load Cornerstone.js libraries and viewer script dynamically
// CRITICAL: Scripts MUST load sequentially to respect dependencies
console.log('[lib-loader.js] Script executing...');

(async function() {
  try {
    console.log('[lib-loader.js] IIFE starting...');

    const viewerPath = chrome.runtime.getURL('src/viewers/dicom/');
    const libPath = viewerPath + 'lib/';

    console.log('[lib-loader.js] Viewer path:', viewerPath);
    console.log('[lib-loader.js] Lib path:', libPath);
    console.log('[DICOM Viewer] Starting sequential library loading...');

  // Load libraries in strict dependency order (SEQUENTIAL, not parallel)
  // Order is critical: dicomParser -> cornerstone -> cornerstoneMath -> cornerstoneTools -> cornerstoneWADOImageLoader
  const scripts = [
    'dicomParser.min.js',      // 1. DICOM parsing (no dependencies)
    'cornerstone.min.js',      // 2. Core rendering (depends on dicomParser)
    'cornerstoneMath.min.js',  // 3. Math utilities (depends on cornerstone)
    'cornerstoneTools.min.js', // 4. Interactive tools (depends on cornerstone + cornerstoneMath)
    'cornerstoneWADOImageLoader.min.js' // 5. Image loader (depends on cornerstone + dicomParser)
  ];

  /**
   * Load a single script and wait for it to complete
   * Returns a promise that resolves when script is loaded
   */
  function loadScript(scriptPath) {
    return new Promise((resolve, reject) => {
      const scriptEl = document.createElement('script');
      scriptEl.src = scriptPath;

      scriptEl.onload = () => {
        console.log('[DICOM Viewer] ✓ Loaded:', scriptPath.split('/').pop());
        resolve();
      };

      scriptEl.onerror = () => {
        const scriptName = scriptPath.split('/').pop();
        console.error('[DICOM Viewer] ✗ Failed to load:', scriptName);
        reject(new Error(`Failed to load ${scriptName}`));
      };

      document.head.appendChild(scriptEl);
    });
  }

  // Load libraries sequentially (await each one before starting next)
  for (let i = 0; i < scripts.length; i++) {
      const scriptPath = libPath + scripts[i];
      console.log(`[DICOM Viewer] Loading ${i + 1}/${scripts.length}: ${scripts[i]}...`);
      await loadScript(scriptPath);

      // Brief delay between loads to ensure global objects are fully initialized
      await new Promise(resolve => setTimeout(resolve, 50));
    }

    console.log('[DICOM Viewer] ✓ All libraries loaded successfully');

    // Verify all required globals are available
    const requiredGlobals = [
      'dicomParser',
      'cornerstone',
      'cornerstoneMath',
      'cornerstoneTools',
      'cornerstoneWADOImageLoader'
    ];

    const missing = requiredGlobals.filter(name => typeof window[name] === 'undefined');

    if (missing.length > 0) {
      throw new Error(`Missing required libraries: ${missing.join(', ')}`);
    }

    console.log('[DICOM Viewer] ✓ All required globals verified');

    // Load viewport classes before viewer.js
    console.log('[DICOM Viewer] Loading viewport classes...');
    await loadScript(viewerPath + 'viewport.js');
    console.log('[DICOM Viewer] ✓ Viewport.js loaded');

    await loadScript(viewerPath + 'viewport-manager.js');
    console.log('[DICOM Viewer] ✓ ViewportManager.js loaded');

    // Now load viewer.js after all libraries and viewport classes are ready
    console.log('[DICOM Viewer] Loading viewer.js...');
    await loadScript(viewerPath + 'viewer.js');
    console.log('[DICOM Viewer] ✓ Viewer.js loaded');

    // Dispatch success event
    window.dispatchEvent(new CustomEvent('dicom-libraries-loaded'));

  } catch (error) {
    console.error('[DICOM Viewer] Library loading failed:', error);
    window.dispatchEvent(new CustomEvent('dicom-libraries-error', {
      detail: {
        error: error.message,
        stack: error.stack
      }
    }));
  }
})();
