import { Directive, OnDestroy, OnInit, TemplateRef } from '@angular/core';
import { PageHeaderService } from '../services/page-header.service';

/**
 * Place on an <ng-template> to project that page's action controls into the
 * shared system header's right-side slot (rendered by UserPortalComponent):
 *
 *   <ng-template appPageHeaderActions>
 *     <button kendoButton themeColor="primary" (click)="openAdd()">+ Add</button>
 *   </ng-template>
 *
 * The directive publishes the template on init and clears it on destroy, so a
 * page's controls never leak to the next page.
 */
@Directive({
  selector: '[appPageHeaderActions]',
  standalone: true,
})
export class PageHeaderActionsDirective implements OnInit, OnDestroy {
  constructor(
    private template: TemplateRef<unknown>,
    private pageHeader: PageHeaderService,
  ) {}

  ngOnInit(): void {
    // Defer one microtask: the shell consumes the actions signal in a view that
    // has already been checked by the time this child directive initializes, so
    // setting it synchronously would trip ExpressionChangedAfterItHasBeenChecked.
    queueMicrotask(() => this.pageHeader.setActions(this.template));
  }

  ngOnDestroy(): void {
    this.pageHeader.clear();
  }
}
