/**
 * ICD Test Runner — Entry Point / Module Loader
 *
 * Creates the shared ICD namespace and loads modules in dependency order.
 * Each module is an IIFE that attaches to window.ICD.
 *
 * Load order:
 *   1. framework.js  — DOM helpers, assertions, shapes, API wrappers, test harness
 *   2. fixtures.js   — Test user/team/group provisioning
 *   3. tier-smoke.js — Read-only GET tests
 *   4. crud/_helpers.js — Shared CRUD utilities (ZIP builder)
 *   5. crud/*.js     — Per-group CRUD test modules (register on T.crud)
 *   6. tier-crud.js  — CRUD orchestrator (calls each group)
 *   7. tier-authz.js — Permission boundary tests
 *   8. tier-security.js — Adversarial red-team tests (auth, cross-tenant, input validation)
 *   9. tier-providers.js — Three-tier provider CRUD + live completions
 *  10. tier-packaging.js — Extension permission lifecycle + secrets (v0.29.0)
 *  11. tier-sdk.js  — Switchboard SDK contract tests
 *  12. ui.js         — Render functions, export, provider setup panel
 *  11. (this file)   — Boot
 */
(async function () {
  'use strict';

  var mount = document.getElementById('extension-mount');
  if (!mount) return;

  // ─── Boot Preact SDK (v0.37.14) ───────────────────────────
  // Extension surfaces don't load Preact vendors or the SDK.
  // Load vendors first, then boot SDK so window.sw is available.
  try {
    var base = window.__BASE__ || '';
    var ver = window.__VERSION__ || '0';

    // Load Preact vendor modules (required by SDK)
    if (!window.preact) {
      var { h, render } = await import(base + '/js/sw/vendor/preact.module.js');
      var hooksModule = await import(base + '/js/sw/vendor/hooks.module.js');
      var htmModule = await import(base + '/js/sw/vendor/htm.module.js');
      window.preact = { h, render };
      window.hooks = hooksModule;
      window.html = htmModule.default.bind(h);
    }

    var sdk = await import(base + '/js/sw/sdk/index.js?v=' + ver);
    await sdk.boot();
    console.log('[ICD] SDK booted — window.sw ready');
  } catch (e) {
    console.warn('[ICD] SDK boot failed:', e.message);
  }

  // ─── Shared Namespace ───────────────────────────────────────
  window.ICD = {
    mount: mount,
    manifest: window.__MANIFEST__ || {},
    user: window.sw?.auth?.user || {},
    base: window.__BASE__ || '',

    // State (populated by framework.js)
    results: [],
    cleanup: [],
    running: false,

    // DOM refs (populated by ui.js)
    el: {},

    // Module slots (populated by each module)
    S: {},           // shapes
    crud: {},        // CRUD group functions
    fixtures: { ready: false, users: [], team: null, group: null },
    providerSetup: { provider: 'openai', apiKey: '', endpoint: '', configured: false }
  };

  // ─── Script Loader ──────────────────────────────────────────
  var surfaceId = window.ICD.manifest.id || 'icd-test-runner';
  var assetBase = '/surfaces/' + surfaceId + '/js/';

  // In split-deployment (nginx path routing), assets may be under __BASE__
  if (window.ICD.base) {
    assetBase = window.ICD.base + assetBase;
  }

  var modules = [
    'framework.js',
    'fixtures.js',
    'tier-smoke.js',
    // CRUD helpers + per-group modules (order among groups doesn't matter)
    'crud/_helpers.js',
    'crud/channels.js',
    'crud/models.js',
    'crud/notes.js',
    'crud/projects.js',
    'crud/knowledge.js',
    'crud/workspaces.js',
    'crud/profile.js',
    'crud/notifications.js',
    'crud/memory.js',
    'crud/admin.js',
    'crud/workflows.js',
    'crud/team-workflows.js',
    'crud/tasks.js',
    'crud/teams.js',
    'crud/personas.js',
    'crud/extensions.js',
    'crud/surfaces.js',
    'crud/editor-package.js',
    'crud/dashboard-package.js',
    'crud/observability.js',
    'crud/workflow-product.js',
    // Orchestrator (must come after all crud/*.js)
    'tier-crud.js',
    'tier-authz.js',
    'tier-security.js',
    'tier-providers.js',
    'tier-packaging.js',
    'tier-sdk.js',
    'ui.js'
  ];

  var loaded = 0;

  function loadNext() {
    if (loaded >= modules.length) {
      boot();
      return;
    }
    var script = document.createElement('script');
    script.src = assetBase + modules[loaded] + '?v=' + (window.__VERSION__ || '0') + '.' + Date.now();
    script.onload = function () { loaded++; loadNext(); };
    script.onerror = function () {
      console.error('[ICD] Failed to load: ' + modules[loaded]);
      loaded++; loadNext(); // continue loading remaining modules
    };
    document.body.appendChild(script);
  }

  function boot() {
    if (typeof window.ICD.renderShell === 'function') {
      window.ICD.renderShell();
    } else {
      mount.innerHTML = '<p style="color:var(--danger);padding:24px;">ICD Test Runner failed to load modules. Check console.</p>';
    }
  }

  loadNext();
})();
