// nk-switch.directive.ts — Anbindung von <nk-switch> an Angular Signal Forms (paketierung.md §4.2a, Stufe 4d).
// Implementiert FormCheckboxControl, NICHT ControlValueAccessor — niemals beides am selben Element.
// Quelle zum Kopieren — @node-k/ui liefert kein kompiliertes Angular-Paket. Liegt als .ts.txt, weil der
// Design-System-Compiler jede .ts als Komponente zu bündeln versucht; im Zielprojekt als nk-switch.directive.ts ablegen.
import { Directive, ElementRef, effect, inject, input, model } from '@angular/core';
import type { FormCheckboxControl } from '@angular/forms/signals';

type NkSwitchElement = HTMLElement & { checked: boolean; disabled: boolean };

@Directive({
  selector: 'nk-switch[field]',
  host: { '(change)': 'onChange($event)', '(focusout)': 'touched.set(true)' },
})
export class NkSwitchDirective implements FormCheckboxControl {
  readonly checked = model(false);
  readonly disabled = input(false);
  readonly touched = model(false);

  readonly #el = inject<ElementRef<NkSwitchElement>>(ElementRef).nativeElement;

  constructor() {
    effect(() => { const c = this.checked(); if (this.#el.checked !== c) this.#el.checked = c; });
    effect(() => { this.#el.disabled = this.disabled(); });
  }

  protected onChange(e: Event) { this.checked.set((e.target as NkSwitchElement).checked); }
}
