import { toSignal } from '@angular/core/rxjs-interop';
import { CommonModule } from '@angular/common';
import {
  Component,
  computed,
  inject
} from '@angular/core';
import { ActivatedRoute, RouterLink } from '@angular/router';
import { map } from 'rxjs/operators';
import { PluginUiRegistryService } from '../../application/services/plugin-ui-registry.service';
import { APP_TRANSLATE_IMPORTS } from '../../../../core/i18n';
import { PluginRenderHostComponent } from '../plugin-render-host/plugin-render-host.component';

@Component({
  selector: 'app-plugin-page-host',
  standalone: true,
  imports: [
    CommonModule,
    RouterLink,
    PluginRenderHostComponent,
    ...APP_TRANSLATE_IMPORTS
  ],
  templateUrl: './plugin-page-host.component.html'
})
export class PluginPageHostComponent {
  readonly page = computed(() => {
    const params = this.params();

    if (!params?.pluginId || !params.pageId) {
      return null;
    }

    return this.uiRegistry.appPageRecords().find((record) =>
      record.pluginId === params.pluginId && record.contributionKey === params.pageId
    ) ?? null;
  });

  private readonly route = inject(ActivatedRoute);
  private readonly uiRegistry = inject(PluginUiRegistryService);
  private readonly params = toSignal(this.route.paramMap.pipe(map((params) => ({
    pageId: params.get('pageId'),
    pluginId: params.get('pluginId')
  }))));
}
