// Product entry: runtime-oriented bundle.
// Shared UI and workflows are bundled eagerly; Fabric and Babylon stay behind two lazy engine boundaries.
import './styles/index.css';
import { notifyImageProviderRegistryChanged, registerImageProvider } from './core/image-providers';
import { notifyModuleRegistryChanged, registerModule } from './core/modules';
import { registerBuiltinModules } from './registerModules';
import {
  createAsukaDesigner as createAsukaDesignerCore,
  replaceAsukaDesigner as replaceAsukaDesignerCore,
} from './core/asuka';
import { ASUKA_ICON_ALIASES, ASUKA_ICON_NAMES } from './components/core/asukaIconCatalog.generated';

export const loadAsukaFabricEngineAddon = (): Promise<unknown> => import('./addons/asuka-fabric-engine.addon');
export const loadAsuka3DEngineAddon = (): Promise<unknown> => import('./addons/asuka-3d-engine.addon');

type CreateOptions = NonNullable<Parameters<typeof createAsukaDesignerCore>[1]>;

const withDefaultRenderEngineLoaders = (options?: CreateOptions): CreateOptions => {
  const base = options && typeof options === 'object' ? options : {};
  const engines = base.engines && typeof base.engines === 'object' ? base.engines : {};
  const threeD = engines['3d'] && typeof engines['3d'] === 'object' ? engines['3d'] : {};

  return {
    ...base,
    engines: {
      ...engines,
      '3d': {
        ...threeD,
        loader: typeof threeD.loader === 'function' ? threeD.loader : loadAsuka3DEngineAddon,
      },
    },
  };
};

export const createAsukaDesigner: typeof createAsukaDesignerCore = (target, options) => (
  createAsukaDesignerCore(target, withDefaultRenderEngineLoaders(options))
);

export const replaceAsukaDesigner: typeof replaceAsukaDesignerCore = (target, stateOrOptions, options = {}) => {
  const isStatePayload = Boolean(
    stateOrOptions
    && typeof stateOrOptions === 'object'
    && (stateOrOptions as any).format === 'asuka-state',
  );

  if (isStatePayload) {
    return replaceAsukaDesignerCore(
      target,
      stateOrOptions,
      withDefaultRenderEngineLoaders(options),
    );
  }

  return replaceAsukaDesignerCore(
    target,
    withDefaultRenderEngineLoaders(stateOrOptions as CreateOptions),
  );
};

registerBuiltinModules();

const publicApi = {
  createAsukaDesigner,
  replaceAsukaDesigner,
  registerBuiltinModules,
  registerModule,
  notifyModuleRegistryChanged,
  registerImageProvider,
  notifyImageProviderRegistryChanged,
  loadAsukaFabricEngineAddon,
  loadAsuka3DEngineAddon,
  iconNames: ASUKA_ICON_NAMES,
  iconAliases: ASUKA_ICON_ALIASES,
};

try {
  const g = globalThis as any;
  g.AsukaDesigner = {
    ...(g.AsukaDesigner ?? {}),
    ...publicApi,
  };
  // Vanilla-browser friendly globals.
  g.createAsukaDesigner = createAsukaDesigner;
  g.replaceAsukaDesigner = replaceAsukaDesigner;
  g.registerAsukaBuiltinModules = registerBuiltinModules;
  g.registerAsukaModule = registerModule;
  g.registerAsukaImageProvider = registerImageProvider;
  g.loadAsukaFabricEngineAddon = loadAsukaFabricEngineAddon;
  g.loadAsuka3DEngineAddon = loadAsuka3DEngineAddon;
} catch {}

export type { ThemeColorMap, ThemeInit, ThemePresetId, ThemeToken } from './core/theme';
export type { AsukaExportedState, AsukaImportOptions, AsukaRuntimeLayoutState, AsukaStatePart, AsukaStateScope, SerializedDrawingArea } from './core/stateManager';
export * from './core/portableProduct';
export * from './core/portableProductPackage';
export * from './core/modules';
export * from './core/license/license.catalog';
export * from './core/license/commercial-limits';
export {
  ASUKA_LICENSE_SERVER_ENDPOINTS,
  AsukaLicenseServerErrorResponse,
  DEFAULT_ASUKA_LICENSE_SERVER_BASE_URL,
  fetchStandardLicensePublicKey,
  isStandardLicenseServerEnvelope,
  unwrapStandardLicensePublicKey,
  unwrapStandardLicenseToken,
} from './core/license/license.contract';
export type {
  AsukaLicenseDeactivateRequest,
  AsukaLicenseDeactivateResponseData,
  AsukaLicenseDeactivateResponseEnvelope,
  AsukaLicensePublicKeyResponseData,
  AsukaLicensePublicKeyResponseEnvelope,
  AsukaLicenseRefreshRequest,
  AsukaLicenseRefreshResponseEnvelope,
  AsukaLicenseResolveRequest,
  AsukaLicenseResolveResponseData,
  AsukaLicenseResolveResponseEnvelope,
  AsukaLicenseServerError,
  AsukaLicenseServerErrorCode,
  AsukaLicenseServerErrorEnvelope,
  AsukaLicenseServerMeta,
  AsukaLicenseServerSuccessEnvelope,
} from './core/license/license.contract';
export * from './core/license/token';
export * from './core/license/verifier';
export * from './core/image-providers';
export * from './core/responsive';
export * from './core/apiEndpoints';
export * from './core/renderEngine';
export * from './core/physicalMeasurement';
export * from './core/parametricMeasurement';
export { ASUKA_ICON_ALIASES, ASUKA_ICON_NAMES, isAsukaIconName } from './components/core/asukaIconCatalog.generated';
export type { AsukaIconName } from './components/core/asukaIconCatalog.generated';
export { normalizePremiumIconName } from './components/core/AsukaIcon';
export type {
  AsukaDocumentDrawingAreaState,
  AsukaDocumentDrawingAreasState,
  AsukaDocumentEngineMode,
  AsukaDocumentSelectionState,
  AsukaDocumentState,
  AsukaDocumentViewportState,
  AsukaNativeSnapshotsState,
} from './core/asukaDocument';
export * from './core/pricingValue';
export type { AsukaElementVariationApplyInput } from './core/elementVariationSync';
export * from './core/variations';
export type { NormalizedAsukaUiOptions, NormalizedAsukaViewsPaginationOptions } from './core/uiOptions';
export * from './core/images';
export type { AsukaDocumentNamespace, AsukaRuntimeNamespace } from './core/designerNamespaces';
export { registerBuiltinModules } from './registerModules';


export type {
  AsukaDesignerOptions,
  AsukaInitialViewConfig,
  AsukaFontsConfig,
  AsukaSystemFontConfig,
  AsukaGoogleFontConfig,
  AsukaCustomFontConfig,
  AsukaRegisteredFont,
  AsukaModuleConfig,
  AsukaAssemblyModuleConfig,
  AsukaModelOptimizerModuleConfig,
  AsukaUploadModuleConfig,
  AsukaUploadStrategy,
  AsukaUploadHandlerContext,
  AsukaUploadHandlerResult,
  AsukaUploadSelectionItem,
  AsukaUploadSelectionPayload,
  AsukaUploadSelectHandlerContext,
  AsukaUploadSelectHandlerResult,
  AsukaDesignsModuleConfig,
  AsukaShapesModuleConfig,
  AsukaShapeSvgAssetConfig,
  AsukaShapeStyleConfig,
  AsukaShapeEditDefaultsConfig,
  AsukaPdfOptions,
  AsukaIntegrationsConfig,
  AsukaColorsConfig,
  AsukaPrintingMethod,
  AsukaPricingRule,
  AsukaPriceFormatConfig,
  AsukaI18nOptions,
  AsukaBootOptions,
  AsukaBootMode,
  AsukaDebugOptions,
  AsukaObservabilityErrorRecord,
  AsukaObservabilityOptions,
  AsukaAgencyFeatureOptions,
  AsukaAiFeatureOptions,
  AsukaExportsFeatureOptions,
  AsukaLicenseOptions,
  AsukaFacebookIntegrationConfig,
  AsukaThemeOptions,
  AsukaUiScalingOptions,
  AsukaUiOptions,
  AsukaViewsPaginationOptions,
  AsukaViewsPaginationMode,
  AsukaShellOptions,
  AsukaMode,
  AsukaFontSource,
  AsukaDesignCatalogItem,
  AsukaPixabayIntegrationConfig,
  AsukaPexelsIntegrationConfig,
  AsukaColorItem,
  AsukaIconOverride,
} from './types/options';

export type {
  AsukaLicensePlan,
  AsukaLicenseStatus,
  AsukaLicenseFeature,
  AsukaLicenseUsage,
  AsukaLicenseLimits,
  AsukaLicenseEntitlements,
  AsukaLicenseCompactHeader,
  AsukaSignedLicensePayload,
  AsukaLicenseTokenInput,
  AsukaLicenseResolveContext,
  AsukaLicenseDeactivateContext,
  AsukaLicenseRefreshContext,
  AsukaLicenseResolver,
  AsukaLicenseVerifier,
  AsukaLicenseHttpMethod,
  AsukaLicenseActivateInput,
  AsukaLicenseActivationState,
  AsukaLicenseRefreshOptions,
  AsukaLicenseFeatureDefinition,
  AsukaLicenseResolutionResult,
} from './core/license/license.types';
export type {
  AsukaAgencyFeatureKey,
  AsukaBrandingConfig,
  AsukaBackgroundRemovalInput,
  AsukaBackgroundRemovalResult,
  AsukaBackgroundRemovalConfig,
  AsukaAgencyOptions,
  AsukaAgencyBundle,
} from './core/agency';
export type {
  AsukaAiTextToImageInput,
  AsukaAiTextToImageResult,
  AsukaAiTextToImageConfig,
  AsukaAiBackgroundRemovalConfig,
  AsukaAiOptions,
} from './core/ai';
export type {
  AsukaPaidExportConsumeInput,
  AsukaPaidExportConsumeResult,
  AsukaPaidExportConsumeConfig,
  AsukaServerHdExportInput,
  AsukaServerHdExportPayload,
  AsukaServerHdExportResult,
  AsukaServerHdExportConfig,
  AsukaExportsOptions,
} from './core/exports';
export type {
  LayoutConfig,
  LayoutZoneConfig,
  LayoutItemConfig,
  AsukaInlineLayoutModuleDefinition,
  LayoutIconOverride,
  SelectionMenuConfig,
  OverlayAnchorBox,
  LayoutOpenArgs,
  OverlayType,
  LayoutZoneId,
} from './types/layout';
export type { ListenerOptions, AsukaListenerEntry, AsukaListenerName } from './types/listeners';
export type {
  AsukaPlacementPhase,
  AsukaPlacementSessionBeginInput,
  AsukaPlacementSessionStatus,
  AsukaPlacementSessionUpdateInput,
} from './core/placementSession';

export type { ModuleId } from './types/moduleIds';
export type { DrawingAreaPolicy, DrawingAreaShape, DrawingAreaId, DrawingAreaRect, DrawingAreaEmptyVisual } from './types/drawingAreas';
export type { AsukaPermissions, AsukaRole } from './core/permissions';
export type {
  AsukaDesigner,
  AsukaLayoutApi,
  AsukaDesignerApi,
  AsukaAssemblyApi,
  AsukaEngineApi,
  AsukaStateApi,
  AsukaUtilApi,
  AsukaObservabilityApi,
  AsukaCameraApi,
  AsukaParametric3DApi,
  AsukaLicenseApi,
  AsukaResponsiveApi,
  AsukaUploadsApi,
  AsukaThemeApi,
  AsukaRegisterModuleOptions,
  AsukaLayoutOverlayApi,
  AsukaSelectionMenuApi,
  AsukaLayoutItemRegistration,
  AsukaI18nApi,
  AsukaListenersApi,
  AsukaModulesApi,
  AsukaRuntimeUiApi,
  AsukaDrawingZone,
  AsukaSnappingState,
  AsukaViewCreatePayload,
  AsukaSnappingConfig,
  AsukaViewUpdatePatch,
  AsukaResolvedBootPlan,
} from './core/asuka';
export type {
  AsukaState,
  LayoutBlock,
  DocumentDrawingAreaState,
  DocumentHistoryInfoState,
  DocumentSelectionState,
  DocumentViewportState,
  AsukaView,
  ElementSelection,
  FixedSlot,
  IntegrationsConfig,
  AsukaListenerId,
  AsukaListenerSettings,
  ModuleConfig,
  UploadedAsset,
  UploadedAssetStatus,
  RegisterUploadedAssetInput,
  UploadedAssetsState,
  RulerProductConfig,
  RulerUnit,
  SelectionMenuType,
  ShapePlaceKind,
  SvgShapeAsset,
  FixedSlotConstraints,
  FixedSlotType,
} from './store/asukaStore';
export type {
  AsukaElement,
  AsukaElementType,
  AsukaProduct3DConfig,
  AsukaProduct3DMaterial,
  AsukaProduct3DPart,
  AsukaProduct3DPrintArea,
  AsukaProduct3DPrintAreaObject,
  ElementVariation,
} from './types/elements';
export type { AsukaCameraView, AsukaCameraLimits, AsukaCameraMoveOptions } from './types/camera';
export type { PrintingMethod, ColorScope } from './core/printing';

export type {
  PriceBreakdown,
  PriceFormat,
  PriceUiBreakdown,
  PricingConditionAggregation,
  PricingMeasurement,
  PricingRule,
  PricingRuleCondition,
  PricingMatch,
  PricingScope,
  PricingRuleTarget,
  PricingOperator,
  PricingViewSize,
} from './core/pricingEngine';
export type { PrintingColor } from './core/printing';
export type { Translations } from './core/i18n';

export { assertCanonical3DProduct, assertCanonical3DSceneState, create3DSceneState } from './core/scene3d';

export * from './types/parametric3d';
export * from './core/parametric3d';
export * from './types/assembly3d';
export * from './core/assembly3d';
