document.addEventListener('DOMContentLoaded', () => {
  const stateMap = window.PROCUREMENT_STATE_MAP || {};
  const phoneCodes = window.PROCUREMENT_PHONE_CODES || {};

  const heroSlides = Array.from(document.querySelectorAll('.hero-slide'));
  const heroDots = Array.from(document.querySelectorAll('.hero-dot'));
  if (heroSlides.length > 1) {
    let index = 0;
    const setSlide = (nextIndex) => {
      heroSlides.forEach((slide, slideIndex) => {
        slide.classList.toggle('active', slideIndex === nextIndex);
      });
      heroDots.forEach((dot, dotIndex) => {
        dot.classList.toggle('active', dotIndex === nextIndex);
      });
      index = nextIndex;
    };

    setSlide(0);
    window.setInterval(() => {
      setSlide((index + 1) % heroSlides.length);
    }, 5000);
  }

  function setFieldError(form, fieldName, message) {
    const field = form.querySelector(`[data-field="${fieldName}"]`);
    const error = form.querySelector(`[data-error-for="${fieldName}"]`);

    if (field) {
      field.classList.toggle('is-invalid', Boolean(message));
    }

    if (error) {
      error.textContent = message || '';
    }
  }

  function populateStates(select, countryName, selectedState = '') {
    if (!select) return;
    const states = stateMap[countryName];
    if (!Array.isArray(states) || states.length === 0) return;

    const current = selectedState || select.value;
    select.innerHTML = '<option value="">Select State</option>';
    states.forEach((state) => {
      const option = document.createElement('option');
      option.value = state;
      option.textContent = state;
      if (state === current) {
        option.selected = true;
      }
      select.appendChild(option);
    });
  }

  function syncCountryFields(countrySelect, stateSelect, phoneCodeSelect, datacenterLabel) {
    if (!countrySelect) return;

    const update = () => {
      const country = countrySelect.value;
      const existingState = stateSelect ? stateSelect.value : '';

      if (stateSelect) {
        populateStates(stateSelect, country, existingState);
      }

      if (phoneCodeSelect && phoneCodes[country]) {
        phoneCodeSelect.value = phoneCodes[country];
      }

      if (datacenterLabel) {
        datacenterLabel.textContent = `${country.toUpperCase()} data center.`;
      }
    };

    update();
    countrySelect.addEventListener('change', update);
  }

  const signupForm = document.querySelector('[data-procure-signup-form]');
  if (signupForm) {
    const company = signupForm.querySelector('[name="company_name"]');
    const email = signupForm.querySelector('[name="email"]');
    const password = signupForm.querySelector('[name="password"]');
    const phone = signupForm.querySelector('[name="phone"]');
    const terms = signupForm.querySelector('[name="terms"]');
    const countrySelect = signupForm.querySelector('#signupCountry');
    const stateSelect = signupForm.querySelector('#signupState');
    const phoneCodeSelect = signupForm.querySelector('#signupPhoneCode');
    const datacenterLabel = signupForm.querySelector('[data-datacenter]');

    syncCountryFields(countrySelect, stateSelect, phoneCodeSelect, datacenterLabel);

    signupForm.addEventListener('submit', (event) => {
      let invalid = false;

      const companyValue = company ? company.value.trim() : '';
      const emailValue = email ? email.value.trim() : '';
      const passwordValue = password ? password.value.trim() : '';
      const phoneValue = phone ? phone.value.trim() : '';
      const termsChecked = Boolean(terms && terms.checked);
      const countryValue = countrySelect ? countrySelect.value : '';
      const stateValue = stateSelect ? stateSelect.value : '';

      setFieldError(signupForm, 'company_name', '');
      setFieldError(signupForm, 'email', '');
      setFieldError(signupForm, 'password', '');
      setFieldError(signupForm, 'phone', '');
      setFieldError(signupForm, 'country', '');
      setFieldError(signupForm, 'state', '');
      setFieldError(signupForm, 'terms', '');

      if (!companyValue) {
        setFieldError(signupForm, 'company_name', 'Please enter your organization name');
        invalid = true;
      }

      if (!emailValue) {
        setFieldError(signupForm, 'email', 'Please enter your email id');
        invalid = true;
      } else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(emailValue)) {
        setFieldError(signupForm, 'email', 'Please enter your email id');
        invalid = true;
      }

      if (passwordValue.length < 8) {
        setFieldError(signupForm, 'password', 'Please enter a valid password');
        invalid = true;
      }

      if (!/^\d{10}$/.test(phoneValue)) {
        setFieldError(signupForm, 'phone', 'Please enter a valid mobile number');
        invalid = true;
      }

      if (!countryValue) {
        setFieldError(signupForm, 'country', 'Please select a country');
        invalid = true;
      }

      if (!stateValue) {
        setFieldError(signupForm, 'state', 'Please select a state');
        invalid = true;
      }

      if (!termsChecked) {
        setFieldError(signupForm, 'terms', 'Please read and accept the Terms of Service and Privacy Policy');
        invalid = true;
      }

      if (invalid) {
        event.preventDefault();
      }
    });

    [company, email, password, phone, countrySelect, stateSelect, terms].forEach((field) => {
      if (!field) return;
      field.addEventListener('input', () => {
        if (field.name) {
          setFieldError(signupForm, field.name, '');
        }
      });
      field.addEventListener('change', () => {
        if (field.name) {
          setFieldError(signupForm, field.name, '');
        }
      });
    });

    if (phone) {
      phone.addEventListener('input', () => {
        phone.value = phone.value.replace(/\D/g, '').slice(0, 10);
      });
    }
  }

  const orgForm = document.querySelector('[data-org-form]');
  if (orgForm) {
    const orgName = orgForm.querySelector('[name="organization_name"]');
    const industry = orgForm.querySelector('[name="industry"]');
    const terms = orgForm.querySelector('[name="terms"]');
    const countrySelect = orgForm.querySelector('#orgCountrySelect');
    const stateSelect = orgForm.querySelector('#orgStateSelect');
    syncCountryFields(countrySelect, stateSelect, null, null);

    orgForm.addEventListener('submit', (event) => {
      let invalid = false;

      const orgNameValue = orgName ? orgName.value.trim() : '';
      const industryValue = industry ? industry.value.trim() : '';
      const termsChecked = Boolean(terms && terms.checked);

      setFieldError(orgForm, 'organization_name', '');
      setFieldError(orgForm, 'industry', '');
      setFieldError(orgForm, 'terms', '');

      if (!orgNameValue) {
        setFieldError(orgForm, 'organization_name', 'Please enter your organization name');
        invalid = true;
      }

      if (!industryValue) {
        setFieldError(orgForm, 'industry', 'Please select an industry');
        invalid = true;
      }

      if (!termsChecked) {
        setFieldError(orgForm, 'terms', 'Please accept the terms of service and privacy policy');
        invalid = true;
      }

      if (invalid) {
        event.preventDefault();
      }
    });

    [orgName, industry, terms, countrySelect, stateSelect].forEach((field) => {
      if (!field) return;
      field.addEventListener('input', () => {
        if (field.name) {
          setFieldError(orgForm, field.name, '');
        }
      });
      field.addEventListener('change', () => {
        if (field.name) {
          setFieldError(orgForm, field.name, '');
        }
      });
    });
  }

  const otpInput = document.querySelector('.otp-input');
  if (otpInput) {
    otpInput.addEventListener('input', () => {
      otpInput.value = otpInput.value.replace(/\D/g, '').slice(0, 6);
    });
  }

  const pageModal = document.querySelector('[data-page-modal]');
  if (pageModal) {
    const modalTitle = pageModal.querySelector('#dashboardModalTitle');
    const openers = document.querySelectorAll('[data-modal-open]');
    const closeTargets = pageModal.querySelectorAll('[data-page-modal-close]');

    const openModal = (title) => {
      if (modalTitle && title) {
        modalTitle.textContent = `${title} is not wired yet`;
      } else if (modalTitle) {
        modalTitle.textContent = 'Action unavailable in demo mode';
      }
      pageModal.classList.add('is-visible');
      pageModal.setAttribute('aria-hidden', 'false');
    };

    const closeModal = () => {
      pageModal.classList.remove('is-visible');
      pageModal.setAttribute('aria-hidden', 'true');
    };

    openers.forEach((opener) => {
      opener.addEventListener('click', () => openModal(opener.getAttribute('data-modal-open')));
    });

    closeTargets.forEach((target) => {
      target.addEventListener('click', closeModal);
    });
  }

  const quickAdd = document.querySelector('[data-quick-add]');
  if (quickAdd) {
    const toggle = quickAdd.querySelector('[data-quick-add-toggle]');
    const menu = quickAdd.querySelector('[data-quick-add-menu]');

    const closeQuickAdd = () => {
      quickAdd.classList.remove('is-open');
      toggle?.setAttribute('aria-expanded', 'false');
      menu?.setAttribute('aria-hidden', 'true');
    };

    const openQuickAdd = () => {
      quickAdd.classList.add('is-open');
      toggle?.setAttribute('aria-expanded', 'true');
      menu?.setAttribute('aria-hidden', 'false');
    };

    toggle?.addEventListener('click', (event) => {
      event.stopPropagation();
      if (quickAdd.classList.contains('is-open')) {
        closeQuickAdd();
      } else {
        openQuickAdd();
      }
    });

    menu?.addEventListener('click', (event) => {
      const action = event.target.closest('a, button');
      if (action) {
        closeQuickAdd();
      }
    });

    document.addEventListener('click', (event) => {
      if (!quickAdd.contains(event.target)) {
        closeQuickAdd();
      }
    });

    document.addEventListener('keydown', (event) => {
      if (event.key === 'Escape') {
        closeQuickAdd();
      }
    });
  }

  const topbarPopovers = Array.from(document.querySelectorAll('[data-topbar-popover]'));
  if (topbarPopovers.length) {
    const setPopoverState = (popover, open) => {
      const toggle = popover.querySelector('[data-topbar-toggle]');
      const menu = popover.querySelector('[data-topbar-menu]');

      popover.classList.toggle('is-open', open);
      if (toggle) {
        toggle.setAttribute('aria-expanded', open ? 'true' : 'false');
      }
      if (menu) {
        menu.setAttribute('aria-hidden', open ? 'false' : 'true');
      }
    };

    const closeAllPopovers = () => {
      topbarPopovers.forEach((popover) => setPopoverState(popover, false));
    };

    topbarPopovers.forEach((popover) => {
      const toggle = popover.querySelector('[data-topbar-toggle]');
      const menu = popover.querySelector('[data-topbar-menu]');
      if (!toggle || !menu) return;

      toggle.addEventListener('click', (event) => {
        event.stopPropagation();
        const willOpen = !popover.classList.contains('is-open');
        closeAllPopovers();
        setPopoverState(popover, willOpen);
      });

      menu.addEventListener('click', (event) => {
        if (event.target.closest('a, button')) {
          setPopoverState(popover, false);
        }
      });
    });

    document.addEventListener('click', (event) => {
      if (!event.target.closest('[data-topbar-popover]')) {
        closeAllPopovers();
      }
    });

    document.addEventListener('keydown', (event) => {
      if (event.key === 'Escape') {
        closeAllPopovers();
      }
    });
  }

  const topbarDrawers = Array.from(document.querySelectorAll('[data-topbar-drawer]'));
  if (topbarDrawers.length) {
    const drawerTriggers = Array.from(document.querySelectorAll('[data-topbar-drawer-open]'));
    const appDrawer = topbarDrawers.find((drawer) => drawer.getAttribute('data-topbar-drawer') === 'apps');
    const appSearchInput = appDrawer ? appDrawer.querySelector('[data-app-search]') : null;
    const appSections = appDrawer ? Array.from(appDrawer.querySelectorAll('[data-app-section]')) : [];

    const filterAppDrawer = () => {
      if (!appDrawer || !appSearchInput) {
        return;
      }

      const query = appSearchInput.value.trim().toLowerCase();
      appSections.forEach((section) => {
        const items = Array.from(section.querySelectorAll('[data-app-item]'));
        let visibleCount = 0;

        items.forEach((item) => {
          const match = query === '' || item.textContent.toLowerCase().includes(query);
          item.hidden = !match;
          if (match) {
            visibleCount += 1;
          }
        });

        section.hidden = query !== '' && visibleCount === 0;
      });
    };

    const setDrawerState = (drawer, open) => {
      const triggerKey = drawer.getAttribute('data-topbar-drawer') || '';
      const triggers = Array.from(document.querySelectorAll(`[data-topbar-drawer-open="${triggerKey}"]`));
      drawer.classList.toggle('is-open', open);
      drawer.setAttribute('aria-hidden', open ? 'false' : 'true');
      triggers.forEach((trigger) => {
        trigger.setAttribute('aria-expanded', open ? 'true' : 'false');
      });
    };

    const syncBodyState = () => {
      document.body.classList.toggle('has-topbar-drawer-open', topbarDrawers.some((drawer) => drawer.classList.contains('is-open')));
    };

    const closeAllDrawers = () => {
      topbarDrawers.forEach((drawer) => setDrawerState(drawer, false));
      if (appSearchInput) {
        appSearchInput.value = '';
        filterAppDrawer();
      }
      syncBodyState();
    };

    const openDrawer = (drawerKey) => {
      const targetDrawer = topbarDrawers.find((drawer) => drawer.getAttribute('data-topbar-drawer') === drawerKey);
      if (!targetDrawer) {
        return;
      }

      topbarDrawers.forEach((drawer) => {
        setDrawerState(drawer, drawer === targetDrawer);
      });
      syncBodyState();
    };

    drawerTriggers.forEach((trigger) => {
      trigger.addEventListener('click', (event) => {
        event.stopPropagation();
        const drawerKey = trigger.getAttribute('data-topbar-drawer-open') || '';
        const targetDrawer = topbarDrawers.find((drawer) => drawer.getAttribute('data-topbar-drawer') === drawerKey);

        if (!targetDrawer) {
          return;
        }

        if (targetDrawer.classList.contains('is-open')) {
          closeAllDrawers();
        } else {
          openDrawer(drawerKey);
        }
      });
    });

    topbarDrawers.forEach((drawer) => {
      const backdrop = drawer.querySelector('.topbar-drawer-backdrop');
      const closeButtons = Array.from(drawer.querySelectorAll('.topbar-drawer-close'));

      closeButtons.forEach((button) => {
        button.addEventListener('click', closeAllDrawers);
      });

      drawer.addEventListener('click', (event) => {
        const link = event.target.closest('a');
        if (link) {
          closeAllDrawers();
        }
      });

      if (backdrop) {
        backdrop.addEventListener('click', closeAllDrawers);
      }
    });

    if (appSearchInput) {
      appSearchInput.addEventListener('input', filterAppDrawer);
      filterAppDrawer();
    }

    document.addEventListener('click', (event) => {
      if (!event.target.closest('[data-topbar-drawer]') && !event.target.closest('[data-topbar-drawer-open]')) {
        closeAllDrawers();
      }
    });

    document.addEventListener('keydown', (event) => {
      if (event.key === 'Escape') {
        closeAllDrawers();
      }
    });
  }

  const advanceDrawer = document.querySelector('[data-advance-drawer]');
  if (advanceDrawer) {
    const advancePage = advanceDrawer.closest('[data-advance-page]') || document.querySelector('[data-advance-page]');
    const openButtons = Array.from(document.querySelectorAll('[data-advance-drawer-open]'));
    const closeButtons = Array.from(document.querySelectorAll('[data-advance-drawer-close]'));

    const openDrawer = () => {
      advanceDrawer.classList.add('is-open');
      advanceDrawer.setAttribute('aria-hidden', 'false');
      advancePage?.classList.add('drawer-open');
      advancePage?.setAttribute('aria-hidden', 'false');
    };

    const closeDrawer = () => {
      advanceDrawer.classList.remove('is-open');
      advanceDrawer.setAttribute('aria-hidden', 'true');
      advancePage?.classList.remove('drawer-open');
      advancePage?.setAttribute('aria-hidden', 'true');
    };

    openButtons.forEach((button) => {
      button.addEventListener('click', (event) => {
        event.stopPropagation();
        openDrawer();
      });
    });

    closeButtons.forEach((button) => {
      button.addEventListener('click', closeDrawer);
    });

    advancePage?.addEventListener('click', (event) => {
      if (event.target === advancePage && advanceDrawer.classList.contains('is-open')) {
        closeDrawer();
      }
    });

    document.addEventListener('keydown', (event) => {
      if (event.key === 'Escape' && advanceDrawer.classList.contains('is-open')) {
        closeDrawer();
      }
    });
  }

  const settingsOverlay = document.querySelector('[data-settings-overlay]');
  if (settingsOverlay) {
    const dialogs = Array.from(settingsOverlay.querySelectorAll('[data-settings-dialog]'));
    const openers = document.querySelectorAll('[data-settings-open]');
    const closeTargets = settingsOverlay.querySelectorAll('[data-settings-close]');
    const loyaltyDialog = settingsOverlay.querySelector('[data-settings-dialog="travel-loyalty"]');
    const loyaltyTypeSelect = loyaltyDialog?.querySelector('[data-loyalty-program-type-select]');
    const loyaltyNameSelect = loyaltyDialog?.querySelector('[data-loyalty-program-name]');
    let loyaltyProgramOptions = {};

    if (loyaltyNameSelect) {
      try {
        loyaltyProgramOptions = JSON.parse(loyaltyNameSelect.getAttribute('data-loyalty-program-options') || '{}');
      } catch (error) {
        loyaltyProgramOptions = {};
      }
    }

    const renderLoyaltyProgramNames = (programType, selectedValue = '') => {
      if (!loyaltyNameSelect) {
        return;
      }

      const options = Array.isArray(loyaltyProgramOptions?.[programType]) ? loyaltyProgramOptions[programType] : [];
      loyaltyNameSelect.innerHTML = '';

      const placeholder = document.createElement('option');
      placeholder.value = '';
      placeholder.textContent = 'Select';
      loyaltyNameSelect.appendChild(placeholder);

      options.forEach((option) => {
        if (option === 'Select') {
          return;
        }
        const item = document.createElement('option');
        item.value = option;
        item.textContent = option;
        if (option === selectedValue) {
          item.selected = true;
        }
        loyaltyNameSelect.appendChild(item);
      });

      if (!selectedValue) {
        loyaltyNameSelect.value = '';
      }
    };

    const setActiveDialog = (key) => {
      dialogs.forEach((dialog) => {
        dialog.classList.toggle('is-active', dialog.getAttribute('data-settings-dialog') === key);
      });
    };

    const openSettingsDialog = (key) => {
      setActiveDialog(key);
      settingsOverlay.classList.add('is-visible');
      settingsOverlay.setAttribute('aria-hidden', 'false');
      document.body.classList.add('settings-overlay-open');
    };

    const closeSettingsDialog = () => {
      settingsOverlay.classList.remove('is-visible');
      settingsOverlay.setAttribute('aria-hidden', 'true');
      document.body.classList.remove('settings-overlay-open');
      dialogs.forEach((dialog) => dialog.classList.remove('is-active'));
    };

    openers.forEach((opener) => {
      opener.addEventListener('click', () => {
        const dialogKey = opener.getAttribute('data-settings-open') || '';
        if (dialogKey === 'travel-loyalty' && loyaltyTypeSelect) {
          const programType = opener.getAttribute('data-loyalty-program-type') || loyaltyTypeSelect.value || 'frequent_flyer';
          loyaltyTypeSelect.value = programType;
          renderLoyaltyProgramNames(programType);
        }
        openSettingsDialog(dialogKey);
      });
    });

    closeTargets.forEach((target) => {
      target.addEventListener('click', closeSettingsDialog);
    });

    settingsOverlay.addEventListener('click', (event) => {
      if (event.target === settingsOverlay) {
        closeSettingsDialog();
      }
    });

    if (loyaltyTypeSelect) {
      loyaltyTypeSelect.addEventListener('change', () => {
        renderLoyaltyProgramNames(loyaltyTypeSelect.value);
      });
      renderLoyaltyProgramNames(loyaltyTypeSelect.value || 'frequent_flyer', loyaltyNameSelect?.value || '');
    }
  }

  const loyaltyDropdown = document.querySelector('[data-loyalty-dropdown]');
  if (loyaltyDropdown) {
    const toggle = loyaltyDropdown.querySelector('[data-loyalty-toggle]');
    const menu = loyaltyDropdown.querySelector('[data-loyalty-menu]');

    const closeLoyaltyMenu = () => {
      menu?.classList.remove('is-open');
      toggle?.setAttribute('aria-expanded', 'false');
    };

    toggle?.addEventListener('click', (event) => {
      event.stopPropagation();
      const isOpen = menu?.classList.toggle('is-open');
      toggle.setAttribute('aria-expanded', String(!!isOpen));
    });

    document.addEventListener('click', (event) => {
      if (!loyaltyDropdown.contains(event.target)) {
        closeLoyaltyMenu();
      }
    });

    menu?.addEventListener('click', (event) => {
      const action = event.target.closest('[data-settings-open]');
      if (action) {
        closeLoyaltyMenu();
      }
    });
  }

  const cardsDropdown = document.querySelector('[data-cards-dropdown]');
  if (cardsDropdown) {
    const toggle = cardsDropdown.querySelector('[data-cards-toggle]');
    const menu = cardsDropdown.querySelector('[data-cards-menu]');

    const closeCardsMenu = () => {
      menu?.classList.remove('is-open');
      toggle?.setAttribute('aria-expanded', 'false');
    };

    toggle?.addEventListener('click', (event) => {
      event.stopPropagation();
      const isOpen = menu?.classList.toggle('is-open');
      toggle.setAttribute('aria-expanded', String(!!isOpen));
    });

    document.addEventListener('click', (event) => {
      if (!cardsDropdown.contains(event.target)) {
        closeCardsMenu();
      }
    });

    menu?.addEventListener('click', closeCardsMenu);
  }

  const budgetSelect = document.querySelector('[data-budget-select]');
  if (budgetSelect) {
    const trigger = budgetSelect.querySelector('[data-budget-toggle]');
    const menu = budgetSelect.querySelector('[data-budget-menu]');

    const closeBudgetMenu = () => {
      menu?.classList.remove('is-open');
      trigger?.setAttribute('aria-expanded', 'false');
    };

    trigger?.addEventListener('click', (event) => {
      event.stopPropagation();
      const open = menu?.classList.toggle('is-open');
      trigger.setAttribute('aria-expanded', open ? 'true' : 'false');
    });

    menu?.addEventListener('click', (event) => {
      const item = event.target.closest('.budget-menu-item');
      if (!item) return;
      const label = trigger?.querySelector('span');
      menu.querySelectorAll('.budget-menu-item').forEach((button) => {
        button.classList.toggle('is-active', button === item);
      });
      if (label) {
        label.textContent = `Budget Period : ${item.textContent.trim()}`;
      }
      closeBudgetMenu();
    });

    document.addEventListener('click', closeBudgetMenu);
  }

  const reportTabs = Array.from(document.querySelectorAll('[data-report-tab]'));
  const reportPanels = Array.from(document.querySelectorAll('[data-report-panel]'));
  if (reportTabs.length && reportPanels.length) {
    const activateTab = (key) => {
      reportTabs.forEach((tab) => {
        tab.classList.toggle('is-active', tab.getAttribute('data-report-tab') === key);
      });
      reportPanels.forEach((panel) => {
        panel.classList.toggle('is-active', panel.getAttribute('data-report-panel') === key);
      });
    };

    reportTabs.forEach((tab) => {
      tab.addEventListener('click', () => activateTab(tab.getAttribute('data-report-tab') || 'recent'));
    });

    activateTab('recent');
  }

  const approvalTabs = Array.from(document.querySelectorAll('[data-approval-tab]'));
  const approvalPanels = Array.from(document.querySelectorAll('[data-approval-panel]'));
  if (approvalTabs.length && approvalPanels.length) {
    const activateApprovalTab = (key) => {
      approvalTabs.forEach((tab) => {
        tab.classList.toggle('is-active', tab.getAttribute('data-approval-tab') === key);
      });
      approvalPanels.forEach((panel) => {
        panel.classList.toggle('is-active', panel.getAttribute('data-approval-panel') === key);
      });
    };

    approvalTabs.forEach((tab) => {
      tab.addEventListener('click', () => activateApprovalTab(tab.getAttribute('data-approval-tab') || 'pending'));
    });

    activateApprovalTab('pending');
  }

  const tripCreateForm = document.querySelector('[data-trip-create-form]');
  if (tripCreateForm) {
    const tripTypeInputs = Array.from(tripCreateForm.querySelectorAll('[data-trip-type-input]'));
    const tripTypeCards = Array.from(tripCreateForm.querySelectorAll('[data-trip-type-option]'));
    const tripNameInput = tripCreateForm.querySelector('[data-trip-name]');
    const tripDestinationInput = tripCreateForm.querySelector('[data-trip-destination]');
    const tripPurposeInput = tripCreateForm.querySelector('[data-trip-purpose]');
    const tripStartInput = tripCreateForm.querySelector('[data-trip-start]');
    const tripEndInput = tripCreateForm.querySelector('[data-trip-end]');
    const tripStatusInput = tripCreateForm.querySelector('[data-trip-status]');
    const tripDestinationHint = tripCreateForm.querySelector('[data-trip-destination-hint]');
    const tripCoverInput = tripCreateForm.querySelector('[data-trip-cover-input]');
    const tripCoverPreview = document.querySelector('[data-trip-cover-preview]');
    const tripCoverPlaceholder = document.querySelector('[data-trip-cover-placeholder]');
    const tripSummaryType = document.querySelector('[data-trip-summary-type]');
    const tripSummaryName = document.querySelector('[data-trip-summary-name]');
    const tripSummaryDestination = document.querySelector('[data-trip-summary-destination]');
    const tripSummaryPurpose = document.querySelector('[data-trip-summary-purpose]');
    const tripSummaryDates = document.querySelector('[data-trip-summary-dates]');
    const tripSummaryStatus = document.querySelector('[data-trip-summary-status]');
    let coverPreviewUrl = '';

    const formatTripDate = (value) => {
      const date = String(value || '').trim();
      if (!date) {
        return 'Not set';
      }

      const parts = date.split('-');
      if (parts.length === 3) {
        return `${parts[2]}/${parts[1]}/${parts[0]}`;
      }

      return date;
    };

    const setCoverPreview = (src) => {
      if (!tripCoverPreview || !tripCoverPlaceholder) {
        return;
      }

      if (src) {
        tripCoverPreview.src = src;
        tripCoverPreview.classList.remove('is-hidden');
        tripCoverPlaceholder.classList.add('is-hidden');
      } else {
        tripCoverPreview.removeAttribute('src');
        tripCoverPreview.classList.add('is-hidden');
        tripCoverPlaceholder.classList.remove('is-hidden');
      }
    };

    const setTravelType = (value) => {
      const normalized = String(value || 'domestic').toLowerCase() === 'international' ? 'international' : 'domestic';

      tripTypeCards.forEach((card) => {
        card.classList.toggle('is-selected', card.getAttribute('data-trip-type-option') === normalized);
      });

      if (tripSummaryType) {
        tripSummaryType.textContent = normalized === 'international' ? 'International' : 'Domestic';
      }

      if (tripDestinationHint) {
        tripDestinationHint.textContent = normalized === 'international'
          ? 'Add the city and country you will visit.'
          : 'Enter the city or location for this trip.';
      }

      if (tripDestinationInput) {
        tripDestinationInput.placeholder = normalized === 'international' ? 'City, country' : 'City, state or country';
      }

      return normalized;
    };

    const syncSummary = () => {
      const travelType = setTravelType((tripTypeInputs.find((input) => input.checked) || tripTypeInputs[0])?.value || 'domestic');
      const tripName = tripNameInput ? tripNameInput.value.trim() : '';
      const destination = tripDestinationInput ? tripDestinationInput.value.trim() : '';
      const purpose = tripPurposeInput ? tripPurposeInput.value.trim() : '';
      const startDate = tripStartInput ? formatTripDate(tripStartInput.value) : 'Not set';
      const endDate = tripEndInput ? formatTripDate(tripEndInput.value) : 'Not set';

      if (tripSummaryName) {
        tripSummaryName.textContent = tripName || 'New Trip';
      }

      if (tripSummaryDestination) {
        tripSummaryDestination.textContent = destination || 'Destination pending';
      }

      if (tripSummaryPurpose) {
        tripSummaryPurpose.textContent = purpose || 'Business purpose not set yet';
      }

      if (tripSummaryDates) {
        tripSummaryDates.textContent = startDate === 'Not set' && endDate === 'Not set' ? 'Not set' : `${startDate} - ${endDate}`;
      }

      if (tripSummaryStatus && tripStatusInput) {
        const value = tripStatusInput.value || 'planned';
        tripSummaryStatus.textContent = value.charAt(0).toUpperCase() + value.slice(1);
      }

      return travelType;
    };

    tripTypeInputs.forEach((input) => {
      input.addEventListener('change', syncSummary);
    });

    [tripNameInput, tripDestinationInput, tripPurposeInput, tripStartInput, tripEndInput, tripStatusInput].forEach((field) => {
      if (!field) {
        return;
      }
      field.addEventListener('input', syncSummary);
      field.addEventListener('change', syncSummary);
    });

    tripCoverInput?.addEventListener('change', () => {
      if (coverPreviewUrl) {
        URL.revokeObjectURL(coverPreviewUrl);
        coverPreviewUrl = '';
      }

      const file = tripCoverInput.files && tripCoverInput.files[0];
      if (!file) {
        setCoverPreview('');
        return;
      }

      coverPreviewUrl = URL.createObjectURL(file);
      setCoverPreview(coverPreviewUrl);
    });

    setTravelType((tripTypeInputs.find((input) => input.checked) || tripTypeInputs[0])?.value || 'domestic');
    syncSummary();
  }

  const settingsTabs = Array.from(document.querySelectorAll('[data-settings-tab]'));
  const settingsPanels = Array.from(document.querySelectorAll('[data-settings-panel]'));
  const travelTabs = Array.from(document.querySelectorAll('[data-travel-subtab]'));
  const travelPanels = Array.from(document.querySelectorAll('[data-travel-subpanel]'));

  if (settingsTabs.length && settingsPanels.length) {
    const normalizeSettingsTab = (value) => {
      const normalized = String(value || '').toLowerCase();
      if (normalized === 'preferences' || normalized === 'userpreferences' || normalized === 'user_preferences') {
        return 'preferences';
      }
      if (normalized === 'travel' || normalized === 'traveldetails' || normalized === 'travel_details') {
        return 'travel';
      }
      if (normalized === 'budgets' || normalized === 'budget') {
        return 'budgets';
      }
      return 'basic';
    };

    const normalizeTravelTab = (value) => {
      const normalized = String(value || '').toLowerCase();
      if (normalized === 'loyalty' || normalized === 'loyaltyprograms' || normalized === 'loyalty_programs') {
        return 'loyalty';
      }
      if (normalized === 'documents' || normalized === 'traveldocuments' || normalized === 'travel_documents') {
        return 'documents';
      }
      return 'profile';
    };

    const applyUrlState = (settingsKey, travelKey) => {
      const url = new URL(window.location.href);
      url.searchParams.set('navType', settingsKey === 'basic' ? 'basic' : settingsKey === 'preferences' ? 'userPreferences' : settingsKey === 'travel' ? 'travelDetails' : 'budgets');

      if (settingsKey === 'travel') {
        url.searchParams.set('travelTab', travelKey);
      } else {
        url.searchParams.delete('travelTab');
      }

      window.history.replaceState({}, '', `${url.pathname}?${url.searchParams.toString()}${url.hash}`);
    };

    const activateTravelTab = (travelKey) => {
      travelTabs.forEach((tab) => {
        tab.classList.toggle('is-active', tab.getAttribute('data-travel-subtab') === travelKey);
      });

      travelPanels.forEach((panel) => {
        panel.classList.toggle('is-active', panel.getAttribute('data-travel-subpanel') === travelKey);
      });
    };

    const activateSettingsTab = (tabKey, travelKey = 'profile', updateUrl = true) => {
      const normalizedTab = normalizeSettingsTab(tabKey);
      const normalizedTravel = normalizeTravelTab(travelKey);

      settingsTabs.forEach((tab) => {
        tab.classList.toggle('is-active', tab.getAttribute('data-settings-tab') === normalizedTab);
      });

      settingsPanels.forEach((panel) => {
        panel.classList.toggle('is-active', panel.getAttribute('data-settings-panel') === normalizedTab);
      });

      if (normalizedTab === 'travel' && travelTabs.length && travelPanels.length) {
        activateTravelTab(normalizedTravel);
      }

      if (updateUrl) {
        applyUrlState(normalizedTab, normalizedTravel);
      }
    };

    const currentUrl = new URL(window.location.href);
    activateSettingsTab(
      currentUrl.searchParams.get('navType') || currentUrl.searchParams.get('tab') || 'basic',
      currentUrl.searchParams.get('travelTab') || 'profile',
      false
    );

    settingsTabs.forEach((tab) => {
      tab.addEventListener('click', () => {
        activateSettingsTab(tab.getAttribute('data-settings-tab') || 'basic', tab.getAttribute('data-travel-tab') || 'profile');
      });
    });

    travelTabs.forEach((tab) => {
      tab.addEventListener('click', () => {
        activateSettingsTab('travel', tab.getAttribute('data-travel-subtab') || 'profile');
      });
    });
  }
});
