document.addEventListener('DOMContentLoaded', () => {
  class IrentQuickSearch extends HTMLElement {
    static GUESTS_TYPE = ['adults', 'children', 'infants'];
    static HELPERS_IDS = ['Datepicker', 'Guests', 'Destinations']
    static LOCATION_LEVELS = {
      0: {Plu: 'Countries', Sin: 'Country'},
      1: {Plu: 'Areas', Sin: 'Area'},
      2: {Plu: 'Cities', Sin: 'City'},
      3: {Plu: 'Neighborhoods', Sin: 'Neighborhood'},
    }
    
    constructor() {
      super();
      this.attachShadow({ mode: 'open' });
      this.state =  {
        adults: 1,
        children: 0,
        infants: 0,
        arrival: null,
        departure: null,
        destType: null,
        destId: null,
      };
      this.flexibility = 0;
      this.dropdowns = new Map();
      this.elements = new Map();
      this.stylesPromises = new Map();
      this.scriptsPromises = new Map();
      this.translations = {};
      this.locations = [];
    }
    
    async connectedCallback() {
      if (!this.hasAttribute('guid')) return;
 
      try {
        await Promise.all([
          this.loadStyles(),
          this.loadScripts(),
          this.loadLocations(),
          this.loadTranslations()
        ])
        await this.render();
      } catch (e) {
        console.error('Error initializing IrentQuickSearch:', e);
      }
    }

    async render() {
      const { quicksearch } = this.getHTMLTemplate();
      const container = document.createElement('div')
      container.id = 'Irent_Quicksearch'
      container.className = 'i-card i-card--flat bg-transparent i-card--density-default i-card--variant-elevated mx-auto pa-4'
      container.style.maxWidth = '1200px'
      container.innerHTML = quicksearch
      
      this.shadowRoot.appendChild(container)
      
      this.shadowRoot
        .querySelector('#Irent_Quicksearch')
        ?.classList.add(this.getAttribute('theme'));
      const datakey = Math.floor(10000000 + Math.random() * 90000000);

      this.shadowRoot.querySelectorAll('div').forEach((el) => {
        el.setAttribute(`data-i-${datakey}`, '');
      });

      ['Input', 'Control'].forEach( selector => 
        IrentQuickSearch.HELPERS_IDS.forEach(helper => {
          const id = `#Irent_${selector}_${helper}`
          this.elements.set(id, this.shadowRoot.querySelector(id))
        })
      )
      this.elements.set('#Irent_Search', this.shadowRoot.querySelector('#Irent_Search'))

      this.elements
        .get('#Irent_Search')
        ?.addEventListener('click', (e) => this.handleSearch(e));

      IrentQuickSearch.HELPERS_IDS.forEach(helper => {
        this.elements
          .get(`#Irent_Control_${helper}`)
          ?.addEventListener('click', async (e) => {
            e.stopPropagation()
            await this.initPickers(helper)
          })
      })

    }

    async initPickers(helper){
      const existingDropdowns = document.querySelectorAll('[id^="Irent_Dropdown_"]');

      existingDropdowns.forEach(e => e.remove())

      if (helper !== 'Destinations' && Array.from(existingDropdowns).some(e => e.id === `Irent_Dropdown_${helper}`)) {
        return;
      }

      const maxWidth = helper === 'Datepicker' ? 700 : null
      const opt = this.initDropdown({ id: helper, content: this.getHTMLTemplate()[helper], maxWidth: maxWidth})
      if (!opt.control || !opt.input || !opt.classTag) return

      this.initHandlers({ helper, ...opt, maxWidth })
      this.setupDropdownBehavior({helper, ...opt, maxWidth })
      this.positionDropdown({ ...opt, maxWidth })
    }

    async initHandlers({helper, input, dropdown, control, panel, classTag, maxWidth}) {
      if(helper === 'Datepicker'){

        const clearBtn = control.querySelector('.i-icon--clear-btn')

        // Pending state — committed only on Apply
        let pendingArrival = this.state.arrival
        let pendingDeparture = this.state.departure
        let pendingFlexibility = this.flexibility

        const displayDate = (d) => {
          const [dd, mm, yyyy] = d.split('-');
          const shortYear = yyyy.slice(-2);
          return `${dd}/${mm}/${shortYear}`;
        };

        const formatDate = (d) => {
          const [dd, mm, yyyy] = d.split('-');
          return new Date(+yyyy, +mm - 1, +dd).toLocaleDateString('en-GB');
        };

        const calendar = document.createElement('i-calendar')
        calendar.setAttribute('lang', this.lang)
        calendar.setAttribute('mode', 'input')

        if (this.state.arrival != null && this.state.departure != null) {
          calendar.calendarDisplay = {
            rangeSelection: {
              interval: {
                start: this.state.arrival.replaceAll('/', '-'),
                end: this.state.departure.replaceAll('/', '-')
              }
            }
          }
        }

        classTag.appendChild(calendar)

        calendar?.addEventListener('range-date', ({ detail }) => {
          const [{ start, end }] = detail || [];
          if (!start || !end) return;
          pendingArrival = formatDate(start);
          pendingDeparture = formatDate(end);
        });

        const flexChips = panel.querySelectorAll('.i-flexibility-chip')
        flexChips.forEach(chip => {
          chip.addEventListener('click', (e) => {
            e.stopPropagation()
            pendingFlexibility = parseInt(chip.dataset.flex)
            flexChips.forEach(c => c.classList.remove('i-flexibility-chip--active'))
            chip.classList.add('i-flexibility-chip--active')
          })
        })

        const applyBtn = panel.querySelector('#Irent_Datepicker_Apply')
        applyBtn?.addEventListener('click', (e) => {
          e.stopPropagation()
          if (pendingArrival && pendingDeparture) {
            this.state.arrival = pendingArrival
            this.state.departure = pendingDeparture
            this.flexibility = pendingFlexibility
            const [ad, am, ay] = pendingArrival.split('/')
            const [dd, dm, dy] = pendingDeparture.split('/')
            input.value = `${ad}/${am}/${ay.slice(-2)} — ${dd}/${dm}/${dy.slice(-2)}`
            clearBtn.classList.add('i-icon--clear-btn__active')
          }
          dropdown.remove()
        })

        const cancelBtn = panel.querySelector('#Irent_Datepicker_Cancel')
        cancelBtn?.addEventListener('click', (e) => {
          e.stopPropagation()
          dropdown.remove()
        })

        clearBtn?.addEventListener('click', (e) => {
          e.stopPropagation()
          this.state.arrival = null
          this.state.departure = null
          this.flexibility = 0
          input.value = ''
          clearBtn.classList.remove('i-icon--clear-btn__active')
          dropdown.remove();
        })

        panel.classList.add('panel-dropdown-content__active')
      }

      if(helper === 'Destinations') {
        const clearBtn = control.querySelector('.i-icon--clear-btn')

        const filterLocations = (text = '') => {
          const q = text.toLowerCase()
          return this.locations.filter(loc =>
            loc.Name?.toLowerCase().includes(q) || loc.Hierarchy?.toLowerCase().includes(q)
          )
        }

        const renderList = (items) => {
          classTag.innerHTML = ''
          panel.classList.toggle('panel-dropdown-content__active', items.length > 0)
          if (!items.length) return
          items.forEach((loc, index) => {
            const item = document.createElement('div')
            item.className = 'irent_destination_item i-list-item i-list-item--link i-list-item--density-default i-list-item--one-line rounded-0 i-list-item--variant-text'
            item.setAttribute('tabindex', index)
      
            item.innerHTML = `
              <span class="i-list-item__overlay"></span>
              <span class="i-list-item__underlay"></span>
              <div class="i-list-item__content" data-no-activator="">
                <div class="i-list-item-title">
                  <div class="i-list-item-title destination_name">${loc.Name}</div>
                  <div class="i-list-item-subtitle destination_hierarchy">${loc.Hierarchy || ''}</div>
                </div>
              </div>`
      
            item.dataset.id = loc.Id ?? ''
            item.dataset.type = loc.LevelId ?? ''
            item.dataset.name = loc.Name ?? ''
            classTag.appendChild(item)
          })

          panel.querySelectorAll('.irent_destination_item').forEach(el => el.addEventListener('click', (e) => {
            this.state.destType = IrentQuickSearch.LOCATION_LEVELS[el.dataset.type].Sin
            this.state.destId = el.dataset.id
            input.value = el.dataset.name
            clearBtn.classList.add('i-icon--clear-btn__active')
            dropdown.remove()
          }))
        }

        input.addEventListener('input', (e) => {
          const query = e.target.value || ''
          renderList(filterLocations(query))
        })
        
        clearBtn?.addEventListener('click', (e) => {
          e.stopPropagation()
          this.state.destId = null
          this.state.destType = null
          input.value = ''
          clearBtn.classList.remove('i-icon--clear-btn__active')
          dropdown.remove();
        })

        input.focus()
        renderList(filterLocations(input.value))
      }

      if(helper === 'Guests'){
        const updateGuestCount = (input, dropdown, panel, type, increment) => {
          const current = this.state[type];
          const min = type === 'adults' ? 1 : 0;
          const newValue = increment ? current + 1 : Math.max(min, current - 1);
    
          if (newValue !== current) {
            this.state[type] = newValue;
            updateGuestDisplay(input, dropdown, panel);
          }
        }
    
        const updateGuestDisplay = (input, dropdown, panel) => {
          const guests = IrentQuickSearch.GUESTS_TYPE;
          const total = guests.reduce((sum, type) => sum + this.state[type], 0);
          const isDefault = this.state.adults === 1 && this.state.children === 0 && this.state.infants === 0;

          if (input) {
            input.value = isDefault
              ? ''
              : `${total} ${this.$t('home.header.quicksearch.guest.guest', total)}`;
          }
    
          if (dropdown) {
            guests.forEach((type) => {
              const label = panel.querySelector(`#Irent_Label_${type}`);
              if (label) label.textContent = this.state[type];
            });
    
            panel.querySelectorAll('.qtyDec').forEach((btn) => {
              const type = btn.dataset.key;
              const min = type === 'adults' ? 1 : 0;
              btn.classList.toggle('i-btn--disabled', this.state[type] <= min);
            });
          }
        }

        IrentQuickSearch.GUESTS_TYPE.forEach((type) => {
          const label = panel.querySelector(`#Irent_Label_${type}`);
          if (label) label.textContent = this.state[type];
        });

        panel.addEventListener('click', (e) => {
          const button = e.target.closest('button');
          if (!button) return;

          const type = button.dataset.key;
          const isIncrement = button.classList.contains('qtyInc');

          if (type && IrentQuickSearch.GUESTS_TYPE.includes(type)) {
            updateGuestCount(input, dropdown, panel, type, isIncrement);
            e.stopPropagation();
          }
        });

        updateGuestDisplay(input, dropdown, panel)
        panel.classList.add('panel-dropdown-content__active')
      }
    }

    async loadStyles(root = this.shadowRoot) {
      try {
        const cssMap = JSON.parse(this.getAttribute('css-urls'))
        if (!cssMap) return

        await Promise.all(
          Object.entries(cssMap).map(async ([key, value]) => {
            const styleTag = document.createElement('style')
            styleTag.dataset.key = key

            if (!this.stylesPromises.has(key)) {
              this.stylesPromises.set(key, await fetch(value)
                .then((r) => r.text())
                .then(this.minifyCss)
                .catch(() => '')
              )
            }
            styleTag.textContent = this.stylesPromises.get(key);
            root.appendChild(styleTag);
          })
        );
      } catch (e) {
        console.warn('Style loading failed:', e);
      }
    }

    async loadScripts() {
      try {
        const scriptsMap = JSON.parse(this.getAttribute('js-urls')) ?? {
          'component-library': 'http://localhost:5000/pluginwpe1/wp-content/plugins/pluginwpe1/views/public/../../assets/js/component-library.umd.cjs'
        }
  
        Object.entries(scriptsMap).forEach(async ([key, value]) => {
          const scriptTag = document.createElement('script');
          scriptTag.dataset.key = key
          if (!this.scriptsPromises.has(key)) {
            this.scriptsPromises.set(key, await fetch(value)
              .then((r) => r.text())
              .catch(() => '')
            )
          }
          scriptTag.textContent = this.scriptsPromises.get(key);
          document.head.appendChild(scriptTag);
        })
      } catch (e) {
        console.warn('Script loading failed:', e);
      }
    }

    async loadLocations() {
      const buildHierarchy = (parentId, localLocations) => {
        let hierarchy = [];
        let currenId = parentId
  
        while (currenId) {
          let foundItem = Object.entries(IrentQuickSearch.LOCATION_LEVELS)
            .map(([key, name]) => localLocations[name.Plu]?.find(location => location.Id === currenId))
            .find(location => location !== undefined)
  
          if(!foundItem) break;
  
          hierarchy.unshift(foundItem.Name);
          currenId = foundItem.ParentId || null;
        }
  
        let name = hierarchy.join(', ');
        return name;
      }

      if (!this.locations || this.locations.length === 0) {
        try {
          const res = await fetch(`${IRENT_API_URL_API}/v1/plugin/locations?guid=${this.getAttribute('guid')}&language=${this.getAttribute('lang')}`)
          if (!res.ok) throw new Error(`Error fetching destinations: ${res.status}`)
          const localLocations = await res.json()

          this.locations = Object.entries(IrentQuickSearch.LOCATION_LEVELS).flatMap(([key, name]) => {
            return (localLocations[name.Plu] || []).map(location => ({
              ParentId: location.ParentId || null,
              LevelId: Number(key),
              Hierarchy: location.ParentId ? buildHierarchy(location.ParentId, localLocations) : null,
              ...location
            }))
          })

        } catch (error) {
          console.error(error.message)
          return
        }
      }
    }

    async loadTranslations() {
      const getTranslations = async(lang) => {
        try {
          const localeMessags = await fetch(
            `${IRENT_API_URL_EDITOR}/v1/translations/${lang}`,
            { headers: { 'X-Apliccation-Origin': 'pluginwpe1' } }
          );
  
          const data = await localeMessags.json();
          return data ?? {};
        } catch (error) {
          console.error('Error loading translations: ', error);
        }
      }

      if (!this.translations || Object.keys(this.translations).length === 0) this.translations = await getTranslations(this.getAttribute('lang'));
    }

    initDropdown({ id, content, maxWidth = null }) {
      const dropdownId = `Irent_Dropdown_${id}`

      const input = this.elements.get(`#Irent_Input_${id}`) || null
      const control = this.elements.get(`#Irent_Control_${id}`) || null

      let dropdown = document.querySelector(`#${dropdownId}`)
      if (!dropdown) {
        dropdown = document.createElement('div')
        dropdown.id = dropdownId
        dropdown.style.cssText = 'width: 0; height: 0; position: absolute'
        document.body.appendChild(dropdown)
      }
    
      let shadow = dropdown.shadowRoot
      if (!shadow) shadow = dropdown.attachShadow({ mode: 'open' })
      this.loadStyles(shadow)
      const shadowContent = document.createElement('div')
      shadowContent.className = `panel-dropdown-content ${this.getAttribute("theme")}`
      shadowContent.innerHTML = content
      shadow.appendChild(shadowContent)
    
      this.dropdowns.set(id, { shadowContent, maxWidth })
      
      const panel = dropdown.shadowRoot.querySelector('.panel-dropdown-content')
      const classTag = panel.querySelector(`i-${id.toLowerCase()}`)

      return { dropdown, input, control, panel, classTag }
    }

    setupDropdownBehavior({ helper, control, dropdown, input, panel, maxWidth = null }) {
      window.addEventListener('resize', () =>
        this.positionDropdown({input, control, dropdown, panel, maxWidth})
      );
    }

    positionDropdown({ control, dropdown, panel, maxWidth }) {
      const rect = control.getBoundingClientRect();
      const scrollY = window.scrollY || document.documentElement.scrollTop;
      const scrollX = window.scrollX || document.documentElement.scrollLeft;
      const fontSize = parseFloat(getComputedStyle(document.documentElement).fontSize);

      const controlTop = rect.top + scrollY;
      const controlLeft = rect.left + scrollX;
      const controlRight = rect.right + scrollX;
      const controlBottom = rect.top + scrollY + control.offsetHeight;

      dropdown.style.top = `${controlBottom + (fontSize * 0.5) }px`;
      panel.style.right = 'unset';
      panel.style.left = 'unset';

      if (maxWidth) {
        const container = this.shadowRoot?.querySelector('#Irent_Quicksearch') || this;
        const containerRect = container.getBoundingClientRect();
        const containerStyle = getComputedStyle(container);
        const pl = parseFloat(containerStyle.paddingLeft) || 0;
        const pr = parseFloat(containerStyle.paddingRight) || 0;
        const effectiveWidth = Math.min(maxWidth, containerRect.width - pl - pr);
        panel.style.width = `${effectiveWidth}px`;
        panel.style.left = `${containerRect.left + scrollX + pl}px`;
      } else {
        panel.style.width = `${rect.width}px`;
        panel.style.left = `${controlLeft}px`;
      }
    }

    handleSearch(event) {
      event?.stopPropagation();

      const pageId = this.getAttribute('page-id');
      if (!pageId) return;

      const omitIfDefault = { adults: 1, children: 0, infants: 0 };
      const url = new URL(pageId);
      Object.entries(this.state).forEach(([key, value]) => {
        if (value !== null && value !== undefined && value !== omitIfDefault[key]) {
          url.searchParams.append(key, value);
        }
      });

      if (this.flexibility > 0 && this.state.arrival && this.state.departure) {
        url.searchParams.append('flexibility', this.flexibility);
      }

      window.location.href = url;
    }

    minifyCss(css) {
      return css
        .replace(/\/\*[\s\S]*?\*\//g, '')
        .replace(/\s{2,}/g, ' ')
        .replace(/\n/g, '')
        .replace(/\s*([{}:;,])\s*/g, '$1')
        .trim();
    }

    $t(key, params = null) {
      let value = key.split('.').reduce((acc, cur) => acc && acc[cur], this.translations);
      if (typeof value !== 'string') return key;
      if (value.includes('|')) {
        const count = typeof params === 'number'
          ? params
          : (params && typeof params.count === 'number'
            ? params.count
            : null);
        const [singular, plural] = value.split('|').map(str => str.trim());
        value = count !== null && count > 1 ? (plural || singular) : singular;
      }

      if (params && typeof params === 'object') {
        Object.entries(params).forEach(([placeholder, replacement]) => {
          value.replace(new RegExp(`${placeholder}`, 'g'), replacement)
        });
      }

      return value;
    }

    closeAllDropdowns() {
      const existingDropdowns = document.querySelectorAll('[id^="Irent_Dropdown_"]');
      existingDropdowns.forEach(e => e.remove())
    }

    getHTMLTemplate() {
      return {
        quicksearch: `<i-quicksearch-container>
            <div class="i-row">
              <div class="i-col">
                <div class="i-input i-input--horizontal i-input--center-affix i-input--density-default i-locale--is-ltr i-text-field i-autocomplete i-autocomplete--single" style="min-width: 250px" id="Irent_Control_Destinations">
                  <div class="i-input__control">
                    <div class="i-field i-field--appended i-field--center-affix i-field--flat i-field--has-background i-field--no-label i-field--variant-outlined bg-surface rounded-lg i-locale--is-ltr">
                      <div class="i-field__overlay"></div>
                      <div class="i-field__field">
                        <div class="i-field__input">
                          <input type="text" id="Irent_Input_Destinations" placeholder="${this.$t('home.header.quicksearch.destination', 1)}" autocomplete="off">
                        </div>
                      </div>
                      <div class="i-field__append-inner">
                        <span class="i-icon i-icon--size-default i-icon--clear-btn" data-id="Destinations">
                          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M12,2C17.53,2 22,6.47 22,12C22,17.53 17.53,22 12,22C6.47,22 2,17.53 2,12C2,6.47 6.47,2 12,2M15.59,7L12,10.59L8.41,7L7,8.41L10.59,12L7,15.59L8.41,17L12,13.41L15.59,17L17,15.59L13.41,12L17,8.41L15.59,7Z"/></svg>
                        </span>
                        <span class="i-icon i-icon--size-default">
                          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" color="currentColor"><path d="M12,11.5A2.5,2.5 0 0,1 9.5,9A2.5,2.5 0 0,1 12,6.5A2.5,2.5 0 0,1 14.5,9A2.5,2.5 0 0,1 12,11.5M12,2A7,7 0 0,0 5,9C5,14.25 12,22 12,22C12,22 19,14.25 19,9A7,7 0 0,0 12,2Z"/></svg>
                        </span>
                      </div>
                      <div class="i-field__outline rounded-lg">
                        <div class="i-field__outline__start"></div>
                        <div class="i-field__outline__end"></div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="i-col">
                <div class="i-input i-input--horizontal i-input--center-affix i-input--density-default i-locale--is-ltr i-text-field i-text-field--clickeable" style="min-width: 250px" id="Irent_Control_Datepicker">
                  <div class="i-input__control">
                    <div class="i-field i-field--appended i-field--center-affix i-field--flat i-field--has-background i-field--no-label i-field--variant-outlined bg-surface rounded-lg i-locale--is-ltr">
                      <div class="i-field__overlay"></div>
                      <div class="i-field__field">
                        <div class="i-field__input">
                          <input type="text" id="Irent_Input_Datepicker" placeholder="${this.$t('home.header.quicksearch.select_dates')}" readonly>
                        </div>
                      </div>
                      <div class="i-field__append-inner">
                        <span class="i-icon i-icon--size-default i-icon--clear-btn" data-id="Datepicker">
                          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M12,2C17.53,2 22,6.47 22,12C22,17.53 17.53,22 12,22C6.47,22 2,17.53 2,12C2,6.47 6.47,2 12,2M15.59,7L12,10.59L8.41,7L7,8.41L10.59,12L7,15.59L8.41,17L12,13.41L15.59,17L17,15.59L13.41,12L17,8.41L15.59,7Z"/></svg>
                        </span>
                        <span class="i-icon i-icon--size-default">
                          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M19,19H5V8H19M16,1V3H8V1H6V3H5C3.89,3 3,3.89 3,5V19A2,2 0 0,0 5,21H19A2,2 0 0,0 21,19V5C21,3.89 20.1,3 19,3H18V1M17,12H12V17H17V12Z"/></svg>
                        </span>
                      </div>
                      <div class="i-field__outline rounded-lg">
                        <div class="i-field__outline__start"></div>
                        <div class="i-field__outline__end"></div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="i-col">
                <div class="i-input i-input--horizontal i-input--center-affix i-input--density-default i-locale--is-ltr i-text-field i-text-field--clickeable" style="min-width: 250px" id="Irent_Control_Guests">
                  <div class="i-input__control">
                    <div class="i-field i-field--appended i-field--center-affix i-field--flat i-field--has-background i-field--no-label i-field--variant-outlined bg-surface rounded-lg i-locale--is-ltr">
                      <div class="i-field__overlay"></div>
                      <div class="i-field__field">
                        <div class="i-field__input">
                          <input type="text" id="Irent_Input_Guests" readonly placeholder="${this.$t('home.header.quicksearch.guest.guest', 1)}" value="${(() => {
                            const adults = this.state.adults || 0;
                            const children = this.state.children || 0;
                            const infants = this.state.infants || 0;
                            const total = adults + children + infants;
                            const isDefault = adults === 1 && children === 0 && infants === 0;
                            return isDefault
                              ? ''
                              : `${total} ${this.$t('home.header.quicksearch.guest.guest', total)}`;
                          })()}">
                        </div>
                      </div>
                      <div class="i-field__append-inner">
                        <span class="i-icon i-icon--size-default">
                          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M16 17V19H2V17S2 13 9 13 16 17 16 17M12.5 7.5A3.5 3.5 0 1 0 9 11A3.5 3.5 0 0 0 12.5 7.5M15.94 13A5.32 5.32 0 0 1 18 17V19H22V17S22 13.37 15.94 13M15 4A3.39 3.39 0 0 0 13.07 4.59A5 5 0 0 1 13.07 10.41A3.39 3.39 0 0 0 15 11A3.5 3.5 0 0 0 15 4Z"/></svg>
                        </span>
                      </div>
                      <div class="i-field__outline rounded-lg">
                        <div class="i-field__outline__start"></div>
                        <div class="i-field__outline__end"></div>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="i-col">
                <button id="Irent_Search" type="button" class="i-btn i-quicksearch i-btn--flat bg-primary i-btn--density-default rounded-lg i-btn--size-default i-btn--variant-elevated">
                  <span class="i-btn__overlay"></span>
                  <span class="i-btn__underlay"></span>
                  <span class="i-btn__content">
                    <span class="button-text">${this.$t('home.header.quicksearch.search')}</span>
                  </span>
                </button>
              </div>
            </div>
          </i-quicksearch-container>`,
        Datepicker: `<div style="min-width: 250px; max-width: 700px">
          <i-datepicker></i-datepicker>
          <div class="i-flexibility-options">
            <div class="i-flexibility-chips">
              ${[
                { value: 0, label: this.$t('home.header.quicksearch.flexibility.exact') },
                { value: 1, label: '&plusmn;1' },
                { value: 2, label: '&plusmn;2' },
                { value: 3, label: '&plusmn;3' },
                { value: 7, label: '&plusmn;7' },
              ].map(opt => `<button class="i-flexibility-chip${opt.value === this.flexibility ? ' i-flexibility-chip--active' : ''}" data-flex="${opt.value}">${opt.label}</button>`).join('')}
            </div>
            <div class="i-flexibility-actions">
              <button id="Irent_Datepicker_Cancel" class="i-datepicker-btn i-datepicker-btn--cancel">${this.$t('home.header.quicksearch.flexibility.cancel')}</button>
              <button id="Irent_Datepicker_Apply" class="i-datepicker-btn i-datepicker-btn--apply">${this.$t('home.header.quicksearch.flexibility.apply')}</button>
            </div>
          </div>
        </div>`,
        Guests: `
            <div class="i-card i-card--density-default rounded-lg i-card--variant-elevated i-card--flat i-card--visible">
              <i-guests>
                ${IrentQuickSearch.GUESTS_TYPE.map(
                  (type) => `
                    <div class="i-row i-row--no-gutters">
                      <div class="i-col px-4 d-flex justify-space-between align-center">
                        <span class="i-card__text">${this.$t(`home.header.quicksearch.guest.${type.toLowerCase()}`)}</span>
                        <div>
                          <div class="i-input i-input--horizontal i-input--center-affix i-input--density-default i-locale--is-ltr d-flex align-center">
                            <div class="i-input__prepend">
                              <button
                                data-key="${type}"
                                type="button"
                                class="i-btn i-btn--flat i-btn--slim border-sm i-btn--density-compact rounded-sm i-btn--variant-elevated bg-primary qtyDec" style="width: 20px; height: 20px">
                                <span class="i-btn__overlay"></span>
                                <span class="i-btn__underlay"></span>
                                <span class="i-btn__content">
                                  <span class="i-icon notranslate" aria-hidden="true" style="font-size: 10px; height: 10px; width: 10px">
                                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M19,13H5V11H19V13Z"/></svg>
                                  </span>
                                </span>
                              </button>
                            </div>
                            <div class="i-input__control">
                              <span id="Irent_Label_${type}" style="font-weight: 600; min-width: 20px; text-align: center;"></span>
                            </div>
                            <div class="i-input__append">
                              <button data-key="${type}" type="button" class="i-btn i-btn--flat i-btn--slim border-sm i-btn--density-compact rounded-sm i-btn--variant-elevated bg-primary qtyInc" style="width: 20px; height: 20px">
                                <span class="i-btn__overlay"></span>
                                <span class="i-btn__underlay"></span>
                                <span class="i-btn__content">
                                  <span class="i-icon notranslate" aria-hidden="true" style="font-size: 10px; height: 10px; width: 10px">
                                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor"><path d="M19,13H13V19H11V13H5V11H11V5H13V11H19V13Z"/></svg>
                                  </span>
                                </span>
                              </button>
                            </div>
                          </div>
                        </div>
                      </div>
                    </div>
                  `
                ).join("")}
              </i-guests>
          </div>`,
        Destinations: `
          <div class="i-card i-card--density-default rounded-lg i-card--variant-elevated i-card--flat i-card--visible" style="min-width: 200px; padding: .5rem;">
            <div class="i-destinations i-menu">
              <div class="i-list i-list--density-default i-list--one-line">
                <i-destinations></i-destinations>
              </div>
            </div>
          </div>`,
      };
    }

  }

  document.addEventListener('click', e => {
    const id = e.target.id
    const existingDropdowns = document.querySelectorAll('[id^="Irent_Dropdown_"]');
    if (!Array.from(existingDropdowns).some(el => el.id === id)) existingDropdowns.forEach(e => e.remove())
  })
  
  customElements.define('irent-quicksearch', IrentQuickSearch);
});

String.prototype.iCapitalize = function () {
  return `${this.trim().charAt(0).toUpperCase()}${this.trim().slice(1)}`;
};

String.prototype.iFormatHtml = function () {
  return this.replaceAll(/&lt;/g, '<').replaceAll(/&gt;/g, '>');
};

String.prototype.iNormalize = function () {
  return this.normalize('NFD')
    .replace(/[\u0300-\u036f]/g, '')
    .replace(/[^a-zA-Z0-9ñÑ\s]/g, '')
    .toLowerCase();
};

// Function to set the position of the dropdown based on input position
function setPosition(input, dropdown) {
  const rect = input.getBoundingClientRect(); // Get the bounding rectangle of the input
  const scrollTop = window.scrollY || document.documentElement.scrollTop; // Get the vertical scroll position
  const scrollLeft = window.scrollX || document.documentElement.scrollLeft; // Get the horizontal scroll position
  dropdown.style.top = (rect.top + scrollTop + input.offsetHeight) + 'px'; // Position dropdown below the input
  dropdown.style.left = (rect.left + scrollLeft) + 'px'; // Align dropdown horizontally
}