class SearchAutocomplete extends HTMLElement {
    constructor() {
      super();
      this.inputId = '',
      this.inputPlaceholder  = '',
      this.searchIcon = null,
      this.categories = [],
      this.dropdownContainerId = ''
    }
    connectedCallback() {
        this.searchIcon = this.getAttribute('data-input-search-icon') || null;
        this.inputId = this.getAttribute('data-input-id') || 'autocompleteInput';
        this.dropdownContainerId = this.getAttribute('data-dropdown-container-id') || 'dropdownContainerId';
        this.inputPlaceholder = this.getAttribute('data-input-placeholder') || 'Enter Agent, Neighborhood, Zip Code, Address or Listing ID';
        this.render();
        // this.setupEventListeners();
    }
    render() {
        this.innerHTML = `
        <div class="custom-dropdown w-full">
        <div class="relative z-10 box-shadow">
            <input
                class="w-full h-12 border-white-clr rounded-none text-base pl-8 pb-1 material-icons tabletSmall:pl-1"
                style="opacity:0.83"
                title="${this.inputPlaceholder}"
                placeholder="${this.inputPlaceholder}"
                id="${this.inputId}"
            />
            <span
                style="${this.searchIcon ? 'display: inline-flex' : 'display:none'}"
                class="material-symbols-outlined h-11 w-11 text-white bg-secondary-dark-grey absolute right-[2px] inline-flex items-center justify-center mt-[2px] mobileSmall:hidden">
                ${this.searchIcon}
            </span>
        </div>
            <div id="${this.dropdownContainerId}" class="bg-white p-4 absolute w-full overflow-y-auto max-h-96 box-shadow hidden">
            </div>
        </div>
        `;

        // Add event listener to handle input changes
        const inputElement = this.querySelector(`#${this.inputId}`);
        inputElement.addEventListener('keyup', this.handleInput.bind(this));
        // Add event listener to close dropdown when clicking outside
        document.body.addEventListener('click', this.handleClickOutside.bind(this));
    }
    renderDropdownContent(){
        return this.categories.map(category => `
            <div class="category">
                <div class="flex items-center gap-x-2 mb-2">
                    <span class="material-symbols-outlined"> ${category.icon} </span>
                    <h3 class="font-bold">${category.label}</h3>
                </div>
                <ul class="pl-5">
                    ${category.items.map(item => `
                        <li class="dropdown-option-large mb-2">
                            <a href="${item.redirectUrl}">
                                <div class="flex items-center gap-x-2">
                                    <div>
                                        ${item.iconUrl ? `<img src="${item.iconUrl}" class="h-10 w-10 img-cicrle" alt="Category Icon">` : ''}
                                    </div>
                                    <div class="flex flex-col">
                                        <span class="text-lg">${item.text}</span>
                                        <span class="text-sm">${item.subText}</span>
                                    </div>
                                </div>
                            </a>
                        </li>
                    `).join('')}
                    <li class="${category.view_all ? 'block mb-3' : 'hidden'}"> <a href="${category.view_all}" class="hover:underline">View All</a></li>
                </ul>
            </div>
        `).join('');
    }
    handleInput() {
        const dropdown = this.querySelector(`#${this.dropdownContainerId}`)
        let searchValue = this.querySelector(`#${this.inputId}`).value;
        const encodedPayload = encodeURIComponent(searchValue);
        let url = 'search-new/' + encodedPayload;
        debounce(() => {
            axios.get(url)
                .then((response) => {
                    this.categories = response.data;
                    dropdown.innerHTML = this.renderDropdownContent();
                    if (searchValue && searchValue.length && this.categories.length) {
                        dropdown.classList.remove('hidden');
                    } else {
                        dropdown.classList.add('hidden');
                    }
                })
                .catch(() => {
                    this.categories = [];
                    dropdown.innerHTML = this.renderDropdownContent();
                    dropdown.classList.add('hidden');
                })
          }, 750);
    }
    handleClickOutside(event) {
        const dropdownContainer = this.querySelector(`#${this.dropdownContainerId}`);
        const targetElement = event.target;
        if (!dropdownContainer.contains(targetElement)) {
            dropdownContainer.classList.add('hidden');
        }
    }
}
customElements.define('search-autocomplete', SearchAutocomplete);