import { Controller } from "@hotwired/stimulus";

export default class extends Controller {
  static targets = ["input", "selected"]

  static values = {
    min: { type: Number, default: 2 }
  }

  connect() {
    this.sync();
  }

  open(event) {
    const input = this.inputTarget;
    const root = this.element;
    if (!root) return;

    const popover = root.querySelector('el-options[popover]');
    if (!popover) return;

    const value = (input.value || '').trim();

    if (value.length >= this.minValue) {
      popover.showPopover();
    } else {
      popover.hidePopover();
    }
  }

  focusInput() {
    if (this.hasInputTarget) {
      this.inputTarget.focus();
      this.sync();
    }
  }

  sync() {
    if (!this.hasInputTarget || !this.hasSelectedTarget) return;

    const root = this.element;
    const hasSelection = !!root?.value;
    const isFocused = document.activeElement === this.inputTarget;
    const hasSearchQuery = this.inputTarget.value.length > 0;

    if (hasSelection && !isFocused && !hasSearchQuery) {
      this.selectedTarget.classList.remove('hidden');
      this.inputTarget.classList.add('hidden');
    } else {
      this.selectedTarget.classList.add('hidden');
      this.inputTarget.classList.remove('hidden');
    }
  }
}
