document.addEventListener('DOMContentLoaded', () => {
  const form = document.querySelector('#trip-form');
  if (!form) return;

  const startInput = form.querySelector('#id_start_location');
  const endInput = form.querySelector('#id_end_location');
  const distanceInput = form.querySelector('#id_distance_miles');
  const startOdometerInput = form.querySelector('#id_start_odometer');
  const endOdometerInput = form.querySelector('#id_end_odometer');
  const useMapCheckbox = form.querySelector('#id_update_end_odometer_from_map');
  const statusBox = document.querySelector('#distance-status');
  const button = document.querySelector('#calculate-distance-btn');
  const endpoint = form.dataset.distanceEndpoint;
  const csrfToken = form.querySelector('[name=csrfmiddlewaretoken]')?.value;

  const setStatus = (message, mode = '') => {
    statusBox.textContent = message;
    statusBox.classList.remove('is-success', 'is-error');
    if (mode) statusBox.classList.add(mode);
  };

  const maybeUpdateEndOdometer = () => {
    if (!useMapCheckbox.checked) return;
    const startOdometer = parseFloat(startOdometerInput.value || '');
    const distanceMiles = parseFloat(distanceInput.value || '');
    if (!Number.isNaN(startOdometer) && !Number.isNaN(distanceMiles)) {
      endOdometerInput.value = (startOdometer + distanceMiles).toFixed(1);
    }
  };

  const calculateDistance = async () => {
    const startLocation = startInput.value.trim();
    const endLocation = endInput.value.trim();
    if (!startLocation || !endLocation) {
      setStatus('Enter both locations to calculate route mileage.');
      return;
    }

    button.disabled = true;
    setStatus('Calculating driving miles from Google Maps…');

    const body = new URLSearchParams({
      start_location: startLocation,
      end_location: endLocation,
      csrfmiddlewaretoken: csrfToken,
    });

    try {
      const response = await fetch(endpoint, {
        method: 'POST',
        headers: {
          'X-Requested-With': 'XMLHttpRequest',
          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
        },
        body: body.toString(),
      });
      const payload = await response.json();
      if (!response.ok || !payload.ok) {
        setStatus(payload.message || 'Mileage could not be calculated. Please refine the addresses.', 'is-error');
        return;
      }
      distanceInput.value = Number(payload.miles).toFixed(1);
      maybeUpdateEndOdometer();
      setStatus(`${payload.message} You can still override the miles before saving.`, 'is-success');
    } catch (error) {
      setStatus('Mileage could not be calculated right now. Please try again or enter miles manually.', 'is-error');
    } finally {
      button.disabled = false;
    }
  };

  button.addEventListener('click', calculateDistance);
  [startInput, endInput].forEach((input) => {
    input.addEventListener('blur', () => {
      if (startInput.value.trim() && endInput.value.trim()) calculateDistance();
    });
  });
  useMapCheckbox.addEventListener('change', maybeUpdateEndOdometer);
  startOdometerInput.addEventListener('input', maybeUpdateEndOdometer);
  distanceInput.addEventListener('input', maybeUpdateEndOdometer);
});
