import {
  Directive,
  effect,
  inject,
  TemplateRef,
  ViewContainerRef,
} from '@angular/core';
import { ExpandableDirective } from './expandable.directive';

/**
 * Structural directive that conditionally renders content when the
 * parent ExpandableDirective is in the collapsed state.
 *
 * This directive must be used within an element that has the uiExpandable
 * directive applied. It shows its content only when the parent expandable
 * is in the collapsed state.
 *
 * @example
 * ```html
 * <div uiExpandable>
 *   <ng-container *uiCollapsed>
 *     Content shown when collapsed
 *   </ng-container>
 * </div>
 * ```
 */
@Directive({ selector: '[uiCollapsed]' })
export class CollapsedDirective {
  /**
   * Reference to the parent ExpandableDirective that controls state
   * @private
   */
  #expandable = inject(ExpandableDirective, { host: true });

  /**
   * Template to be rendered
   * @private
   */
  #templateRef = inject(TemplateRef<unknown>);

  /**
   * Container for rendering the view
   * @private
   */
  #viewContainer = inject(ViewContainerRef);

  /**
   * Effect that reacts to changes in the expanded state.
   * Creates or clears the view based on the expandable state.
   * @private
   */
  render = effect(() => {
    if (this.#expandable.expanded()) {
      this.#viewContainer.clear();
    } else {
      this.#viewContainer.createEmbeddedView(this.#templateRef);
    }
  });
}
