import {
  Component,
  ElementRef,
  effect,
  input,
  viewChild
} from '@angular/core';

export type PluginRenderable = () => HTMLElement | string;

@Component({
  selector: 'app-plugin-render-host',
  standalone: true,
  template: '<div #host></div>'
})
export class PluginRenderHostComponent {
  readonly render = input.required<PluginRenderable>();
  private readonly host = viewChild.required<ElementRef<HTMLElement>>('host');

  constructor() {
    effect(() => {
      this.renderContribution(this.render());
    });
  }

  private renderContribution(render: PluginRenderable): void {
    const hostElement = this.host().nativeElement;

    hostElement.replaceChildren();

    try {
      const rendered = render();

      if (typeof rendered === 'string') {
        hostElement.textContent = rendered;
        return;
      }

      hostElement.appendChild(rendered);
    } catch (error) {
      hostElement.textContent = error instanceof Error ? error.message : 'Plugin contribution failed to render';
    }
  }
}
