import { Component, ElementRef, input, output, viewChild } from '@angular/core';

/** Atom: a styled file picker. Wraps a native `<input type="file">` and emits the
    selected files; resets its value after each change so re-picking the same file
    re-fires. Pure UI — no validation, no upload. */
@Component({
  selector: 'app-file-input',
  styles: [`
    :host { display: inline-block; }
    .field { position: relative; display: inline-flex; }
    input[type='file'] {
      position: absolute;
      inset: 0;
      width: 100%;
      height: 100%;
      opacity: 0;
      cursor: pointer;
    }
    input[type='file']:disabled { cursor: not-allowed; }
    .label {
      pointer-events: none;
      display: inline-flex;
      align-items: center;
      gap: var(--rhc-space-max-sm);
    }
  `],
  template: `
    <span class="field">
      <input
        #fileInput
        type="file"
        [id]="inputId()"
        [attr.aria-label]="label()"
        [accept]="accept().join(',')"
        [multiple]="multiple()"
        [disabled]="disabled()"
        (change)="onChange($event)" />
      <span class="btn btn-outline-primary label" [class.disabled]="disabled()">
        <span aria-hidden="true">↑</span>
        <span>{{ label() }}</span>
      </span>
    </span>
  `,
})
export class FileInputComponent {
  accept = input<string[]>([]);
  multiple = input(false);
  disabled = input(false);
  inputId = input.required<string>();
  /** Accessible name + button text; the domain caller supplies a per-category label. */
  label = input($localize`:@@upload.fileInput.label:Bestand kiezen`);

  filesSelected = output<File[]>();

  private fileInput = viewChild.required<ElementRef<HTMLInputElement>>('fileInput');

  onChange(event: Event) {
    const input = event.target as HTMLInputElement;
    this.filesSelected.emit(Array.from(input.files ?? []));
    this.fileInput().nativeElement.value = '';
  }
}
