import { Directive, input, model } from '@angular/core';

/**
 * A directive that manages individual checkbox values within a ChecklistComponent.
 *
 * This directive should be applied to checkbox input elements that are children of
 * a ChecklistComponent. It tracks the checked state of individual checkboxes and
 * communicates with the parent ChecklistComponent to maintain the overall selected values.
 *
 * @example
 * ```html
 * <ui-checklist [(ngModel)]="selectedItems">
 *   <label>
 *     <input type="checkbox" [uiChecklistValue]="'option1'"> Option 1
 *   </label>
 *   <label>
 *     <input type="checkbox" [uiChecklistValue]="'option2'"> Option 2
 *   </label>
 * </ui-checklist>
 * ```
 */
@Directive({
  selector: '[uiChecklistValue]',
  host: {
    'class': 'ui-checklist-value',
    '[checked]': 'checked()',
    '(change)': 'onChange($event)',
  },
})
export class ChecklistValueDirective {
  /**
   * The value associated with this checkbox that will be included in the
   * ChecklistComponent's value array when checked.
   */
  uiChecklistValue = input<unknown>(null);

  /**
   * Signal that tracks whether this checkbox is currently checked.
   * This is managed by the directive and synchronized with the parent ChecklistComponent.
   */
  checked = model<boolean>(false);

  /**
   * Event handler for the checkbox's change event.
   * Updates the checked state when the user interacts with the checkbox.
   *
   * @param event - The DOM change event from the checkbox input
   */
  onChange(event: Event) {
    if (event.target instanceof HTMLInputElement) {
      this.checked.set(event.target.checked);
    }
  }
}
