import { DestroyRef, inject, Injectable, Signal, signal } from '@angular/core';

export interface Breadcrumb {
  translation: string;
  link?: string;
}

@Injectable({ providedIn: 'root' })
export class BreadcrumbService {
  readonly items = signal<Breadcrumb[]>([]);

  set(breadcrumbs: Breadcrumb[]) {
    this.items.set(breadcrumbs);
  }

  clear() {
    this.items.set([]);
  }
}

/**
 * Sets the breadcrumb for the current component.
 * Accepts translation keys — the site-header translates them via *transloco.
 * Clears automatically on destroy.
 * Must be called in an injection context (constructor or field initializer).
 *
 * @example
 * ```ts
 * export default class TagListComponent {
 *   private readonly breadcrumb = useBreadcrumbs([
 *     { translation: 'navigation.Tags' },
 *   ]);
 * }
 * ```
 */
export function useBreadcrumbs(breadcrumbs: Breadcrumb[]): Signal<Breadcrumb[]> {
  const service = inject(BreadcrumbService);
  const destroyRef = inject(DestroyRef);

  service.set(breadcrumbs);
  destroyRef.onDestroy(() => service.clear());

  return service.items.asReadonly();
}
