document.addEventListener('DOMContentLoaded', () => {
  const form = document.querySelector('[data-trip-entry-form]') || document.querySelector('.morning-trip-modal form');
  if (!form) {
    return;
  }

  const typeOptions = Array.from(form.querySelectorAll('[data-trip-type-option], [data-type-option]'));
  const internationalFields = form.querySelector('[data-trip-international-fields]');
  const countryPicker = form.querySelector('[data-trip-country-picker]');
  const countryValue = form.querySelector('[data-trip-country-value]');
  const countryLabel = form.querySelector('[data-trip-country-label]');
  const countryToggle = form.querySelector('[data-trip-country-toggle]');
  const countryMenu = form.querySelector('[data-trip-country-menu]');
  const countrySearch = form.querySelector('[data-trip-country-search]');
  const countryOptions = Array.from(form.querySelectorAll('[data-country-value]'));
  const countryEmpty = form.querySelector('[data-trip-country-empty]');
  const visaOptions = Array.from(form.querySelectorAll('.trip-visa-option'));
  const defaultCountryLabel = countryLabel ? countryLabel.textContent.trim() || 'Select country' : 'Select country';

  const syncVisaState = () => {
    visaOptions.forEach((option) => {
      const input = option.querySelector('input[type="radio"]');
      option.classList.toggle('is-selected', !!input && input.checked);
    });
  };

  const setCountryMenuState = (open) => {
    if (!countryMenu || !countryToggle) {
      return;
    }

    countryMenu.hidden = !open;
    countryToggle.setAttribute('aria-expanded', open ? 'true' : 'false');
    countryToggle.classList.toggle('is-open', open);
    if (open && countrySearch) {
      countrySearch.focus();
      countrySearch.select();
    }
  };

  const filterCountryOptions = () => {
    if (!countrySearch || !countryEmpty) {
      return;
    }

    const term = countrySearch.value.trim().toLowerCase();
    let visibleCount = 0;

    countryOptions.forEach((option) => {
      const value = (option.getAttribute('data-country-value') || '').toLowerCase();
      const visible = term === '' || value.includes(term);
      option.hidden = !visible;
      if (visible) {
        visibleCount += 1;
      }
    });

    countryEmpty.hidden = visibleCount > 0;
  };

  const syncTypeState = () => {
    const checked = form.querySelector('input[name="travel_type"]:checked');
    const travelType = checked ? checked.value : 'domestic';

    typeOptions.forEach((option) => {
      const radio = option.querySelector('input[type="radio"]');
      const selected = !!radio && radio.value === travelType;
      option.classList.toggle('is-selected', selected);
      option.classList.toggle('selected', selected);
      if (radio) {
        radio.checked = selected;
      }
    });

    if (internationalFields) {
      internationalFields.classList.toggle('is-hidden', travelType !== 'international');
    }

    if (travelType !== 'international') {
      const visaInputs = form.querySelectorAll('input[name="is_visa_required"]');
      visaInputs.forEach((input) => {
        input.checked = input.value === '0';
      });
      syncVisaState();
      if (countryValue) {
        countryValue.value = '';
      }
      if (countryLabel) {
        countryLabel.textContent = defaultCountryLabel;
      }
      if (countryToggle) {
        countryToggle.classList.remove('has-value');
      }
      countryOptions.forEach((item) => {
        item.classList.remove('is-selected');
        item.setAttribute('aria-selected', 'false');
      });
      setCountryMenuState(false);
    }
  };

  typeOptions.forEach((option) => {
    const radio = option.querySelector('input[type="radio"]');
    if (!radio) {
      return;
    }

    radio.addEventListener('change', syncTypeState);
    option.addEventListener('click', () => {
      window.setTimeout(syncTypeState, 0);
    });
  });

  visaOptions.forEach((option) => {
    const input = option.querySelector('input[type="radio"]');
    if (!input) {
      return;
    }

    input.addEventListener('change', syncVisaState);
    option.addEventListener('click', () => {
      window.setTimeout(syncVisaState, 0);
    });
  });

  if (countryToggle && countryMenu) {
    countryToggle.addEventListener('click', () => {
      setCountryMenuState(countryMenu.hidden);
      filterCountryOptions();
    });

    countryToggle.addEventListener('keydown', (event) => {
      if (event.key === 'ArrowDown' || event.key === 'Enter' || event.key === ' ') {
        event.preventDefault();
        setCountryMenuState(true);
        filterCountryOptions();
      }
    });

    document.addEventListener('click', (event) => {
      if (!countryPicker || countryMenu.hidden) {
        return;
      }

      if (!countryPicker.contains(event.target)) {
        setCountryMenuState(false);
      }
    });
  }

  if (countrySearch) {
    countrySearch.addEventListener('input', filterCountryOptions);
    countrySearch.addEventListener('keydown', (event) => {
      if (event.key === 'Escape') {
        event.preventDefault();
        setCountryMenuState(false);
        if (countryToggle) {
          countryToggle.focus();
        }
      }
    });
  }

  countryOptions.forEach((option) => {
    option.addEventListener('click', () => {
      const value = option.getAttribute('data-country-value') || '';
      if (countryValue) {
        countryValue.value = value;
      }
      if (countryLabel) {
        countryLabel.textContent = value || defaultCountryLabel;
      }
      if (countryToggle) {
        countryToggle.classList.toggle('has-value', value !== '');
      }

      countryOptions.forEach((item) => {
        item.classList.toggle('is-selected', item === option);
        item.setAttribute('aria-selected', item === option ? 'true' : 'false');
      });

      if (countrySearch) {
        countrySearch.value = '';
      }
      filterCountryOptions();
      setCountryMenuState(false);
      if (countryToggle) {
        countryToggle.focus();
      }
    });
  });

  syncTypeState();
  syncVisaState();
  filterCountryOptions();
});
