import { Injector, ProviderToken, Type } from '@angular/core';
import { createCustomElement } from '@angular/elements';
import { bootstrapCrtModule } from '@creatio-devkit/common';
import { DesignFeatureModule } from './design-feature.module';
import { RatingPanelComponent } from './property-panels/rating/rating-panel.component';
import { RATING_PANEL_SELECTOR } from './design-feature.ids';
import { ensureFeatureModuleRef } from '../../remote-app-context';

function defineCustomElement(selector: string, component: Type<unknown>, injector: Injector): void {
  if (!customElements.get(selector)) {
    customElements.define(selector, createCustomElement(component, { injector }));
  }
}

/**
 * Initializes the design feature module, registers property panel custom elements.
 */
export async function activateDesignFeature(): Promise<void> {
  const moduleRef = await ensureFeatureModuleRef(DesignFeatureModule);

  defineCustomElement(RATING_PANEL_SELECTOR, RatingPanelComponent, moduleRef.injector);

  bootstrapCrtModule('sdk_custom_component_ai', DesignFeatureModule, {
    resolveDependency: (token: unknown) => moduleRef.injector.get(token as ProviderToken<unknown>),
  });
}
