import { Element } from '../../core/element.js';
import { ResultsDropdown } from './results/results-dropdown.js';
import { normalizeTerm } from '@gouvfr/dsfr-kit';

class SearchBar extends Element {
  constructor (element) {
    super(element, 'searchBar');
    this._searchInput = this.element.querySelector('#search-input');
    this._searchButton = this.element.querySelector('#search-button');
    this._query = normalizeTerm(this._searchInput.value);
    this._url = this._searchButton.getAttribute('data-href');
  }

  async init () {
    this._resultsDropdown = new ResultsDropdown(this._url);
    this._searchInput.after(this._resultsDropdown.element);
    await this._resultsDropdown.init();

    document.addEventListener('click', this.handleDocumentClick.bind(this));

    this._searchButton.addEventListener(
      'click',
      this.handleButtonClick.bind(this)
    );

    this._searchInput.addEventListener(
      'focus',
      this.handleInputFocus.bind(this)
    );

    this._searchInput.addEventListener(
      'keyup',
      this.handleKeyup.bind(this)
    );

    // Handle search input clear
    this._searchInput.addEventListener(
      'search',
      this.handleKeyup.bind(this)
    );
  }

  update (query) {
    this._query = query;
    this._resultsDropdown.update(query);
  }

  handleButtonClick (event) {
    event.preventDefault();
    document.location.href = `${this._url}?query=${this._query}`;
  }

  handleDocumentClick (event) {
    const outsideClick = !this.element.contains(event.target);
    if (outsideClick) {
      this._resultsDropdown.reset();
    }
  }

  handleKeyup (event) {
    if (event.key === 'Enter') {
      this.handleButtonClick(event);
    } else if (event.key === 'Escape') {
      this._resultsDropdown.reset();
    } else {
      this.update(normalizeTerm(event.target.value));
    }
  }

  handleInputFocus () {
    this.update(this._query);
  }
}

export { SearchBar };
