import { WccDashboard } from './elements/wcc-dashboard.js';
import { LitElement } from 'lit';
import type { TTemplateFactory } from './elements/wcctools.helpers.js';
import type { IWccConfig, IWccSection } from './wcctools.interfaces.js';

// Export recording components and service
export { RecorderService, type IRecorderEvents, type IRecordingOptions } from './services/recorder.service.js';
export { WccRecordButton } from './elements/wcc-record-button.js';
export { WccRecordingPanel } from './elements/wcc-recording-panel.js';

// Export types for external use
export type { IWccConfig, IWccSection } from './wcctools.interfaces.js';

/**
 * Converts legacy (elements, pages) format to new sections config
 */
const convertLegacyToConfig = (
  elementsArg?: { [key: string]: LitElement },
  pagesArg?: Record<string, TTemplateFactory>
): IWccConfig => {
  const sections: IWccSection[] = [];

  if (pagesArg && Object.keys(pagesArg).length > 0) {
    sections.push({
      name: 'Pages',
      type: 'pages',
      items: pagesArg,
    });
  }

  if (elementsArg && Object.keys(elementsArg).length > 0) {
    sections.push({
      name: 'Elements',
      type: 'elements',
      items: elementsArg,
    });
  }

  return { sections };
};

/**
 * Check if the argument is the new config format
 */
const isWccConfig = (arg: any): arg is IWccConfig => {
  return arg && typeof arg === 'object' && 'sections' in arg && Array.isArray(arg.sections);
};

/**
 * Setup WCC Tools dashboard
 *
 * New format (recommended):
 * ```typescript
 * setupWccTools({
 *   sections: [
 *     { name: 'Elements', type: 'elements', items: elements },
 *     { name: 'Pages', type: 'pages', items: pages },
 *   ]
 * });
 * ```
 *
 * Legacy format (still supported):
 * ```typescript
 * setupWccTools(elements, pages);
 * ```
 */
const setupWccTools = (
  configOrElements?: IWccConfig | { [key: string]: LitElement },
  pagesArg?: Record<string, TTemplateFactory>
) => {
  let config: IWccConfig;

  if (isWccConfig(configOrElements)) {
    config = configOrElements;
  } else {
    config = convertLegacyToConfig(configOrElements, pagesArg);
  }

  let hasRun = false;
  const runWccToolsSetup = async () => {
    if (document.readyState === 'complete' && !hasRun) {
      hasRun = true;
      const wccTools = new WccDashboard(config);
      document.querySelector('body').append(wccTools);
    }
  };
  document.addEventListener('readystatechange', runWccToolsSetup);
  runWccToolsSetup();
};

export {
  setupWccTools
};
