import { ValidationHelpers, InputAdornment, HelpTooltip, __ } from '@vareoncalc/calculator-base';
import { initCompactTwoStep } from '../utils/compact-two-step.js';
import { 
  shouldShowMeasurementToggle, 
  getPreferredMeasurementMode,
  attachMeasurementToggleListener,
  convertDistance,
  convertFuelEfficiency,
  convertVolume
} from '../utils/measurement.js';
import { getFormattingConfig, formatCurrency, formatCurrencyHtmlIntegerHover, escapeHtml } from '../utils/formatting.js';

/**
 * Fuel Cost Calculator - Trip Budget Planner
 * Calculate fuel costs for a trip based on distance, consumption, and price.
 * Features: Unit toggle, round trip option, cost comparison bar chart, split cost calculator.
 */
export function mount(container) {
  const layout = (window.VAREONCALC_CFG && window.VAREONCALC_CFG.layout) || 'compact';
  const isWide = layout === 'wide';
  
  // Add layout class to container
  if (isWide) {
    container.parentElement.classList.add('layout-wide');
  }
  
  // Get initial mode based on admin settings and user preference
  let currentMode = getPreferredMeasurementMode('imperial');
  let isRoundTrip = false;
  let currentPassengers = 1;
  let lastCalculation = null;
  const measurementToggleId = `fuel-unit-toggle-${Math.random().toString(36).slice(2, 9)}`;
  let twoStepInstance = null;

  const fmtCost = (v) => formatCurrencyHtmlIntegerHover(v, { integerThreshold: Infinity });

  const formatFuelVolumeForDisplay = (amount, unitLabel) => {
    const threshold = 100;
    const full = `${amount.toFixed(1)} ${unitLabel}`;
    if (!Number.isFinite(amount) || Math.abs(amount) < threshold) {
      return escapeHtml(full);
    }
    const rounded = Math.round(amount);
    const compact = `${rounded} ${unitLabel}`;
    const fullEsc = escapeHtml(full);
    const compactEsc = escapeHtml(compact);
    return `<span class="fuel-volume-hover" title="${fullEsc}" aria-label="${fullEsc}">${compactEsc}</span>`;
  };

  const forEachTwoStepInstance = (handler) => {
    if (!twoStepInstance) {
      return;
    }
    if (Array.isArray(twoStepInstance)) {
      twoStepInstance.forEach(instance => {
        if (instance) {
          handler(instance);
        }
      });
      return;
    }
    handler(twoStepInstance);
  };

  const destroyTwoStepInstance = () => {
    forEachTwoStepInstance((instance) => {
      if (instance && typeof instance.destroy === 'function') {
        instance.destroy();
      }
    });
    twoStepInstance = null;
  };

  const showResultsStep = () => {
    forEachTwoStepInstance((instance) => {
      if (typeof instance.setStep === 'function') {
        instance.setStep('results');
      }
      if (typeof instance.setDrawerOpen === 'function') {
        instance.setDrawerOpen(false);
      }
      if (typeof instance.refreshLayout === 'function') {
        instance.refreshLayout();
      }
    });
  };

  const refreshTwoStepLayout = () => {
    forEachTwoStepInstance((instance) => {
      if (typeof instance.refreshLayout === 'function') {
        instance.refreshLayout();
      }
    });
  };
  
  /**
   * Build shared measurement toggle markup for unit switching.
   */
  function getUnitSegmentedControlHTML() {
    const isMetric = currentMode === 'metric';
    const metricActive = isMetric ? ' is-active vareoncalc-measurement-toggle__btn--active' : '';
    const imperialActive = !isMetric ? ' is-active vareoncalc-measurement-toggle__btn--active' : '';
    const ariaLabel = __('Measurement system', 'vareon-calculator-suite-lite');
    return `
      <div class="fuel-unit-toggle">
        <div class="vareoncalc-toggle vareoncalc-measurement-toggle fuel-icon-toggle" id="${measurementToggleId}" data-active="${currentMode}" data-mode="${currentMode}" role="group" aria-label="${ariaLabel}">
          <div class="vareoncalc-toggle__track">
            <button type="button" class="vareoncalc-toggle__option vareoncalc-measurement-toggle__btn fuel-icon-toggle__btn${metricActive}" data-mode="metric" aria-pressed="${isMetric}" title="${__('Metric (kilometers)', 'vareon-calculator-suite-lite')}">km</button>
            <button type="button" class="vareoncalc-toggle__option vareoncalc-measurement-toggle__btn fuel-icon-toggle__btn${imperialActive}" data-mode="imperial" aria-pressed="${!isMetric}" title="${__('Imperial (miles)', 'vareon-calculator-suite-lite')}">mi</button>
          </div>
        </div>
      </div>
    `;
  }
  
  
  const canProceedForInputs = (distanceInput, consumptionInput, priceInput) => {
    const distance = parseFloat(distanceInput?.value);
    const consumption = parseFloat(consumptionInput?.value);
    const fuelPrice = parseFloat(priceInput?.value);
    if (!Number.isFinite(distance) || distance <= 0) return false;
    if (!Number.isFinite(consumption) || consumption <= 0) return false;
    if (!Number.isFinite(fuelPrice) || fuelPrice <= 0) return false;
    return true;
  };

  const updatePassengerSliderFill = (slider) => {
    if (!(slider instanceof HTMLInputElement)) {
      return;
    }

    const min = parseFloat(slider.min || '0');
    const max = parseFloat(slider.max || '100');
    const value = parseFloat(slider.value || '0');
    if (!Number.isFinite(min) || !Number.isFinite(max) || !Number.isFinite(value) || max <= min) {
      slider.style.setProperty('--fuel-slider-percent', '0%');
      return;
    }

    const clamped = Math.min(max, Math.max(min, value));
    const percent = ((clamped - min) / (max - min)) * 100;
    slider.style.setProperty('--fuel-slider-percent', `${percent.toFixed(2)}%`);
  };
  
  function render() {
    destroyTwoStepInstance();
    const isMetric = currentMode === 'metric';
    
    // Get current formatting config for dynamic currency symbol
    const formatting = getFormattingConfig();
    
    // Labels and placeholders based on mode
    const distanceUnit = isMetric ? __( 'km', 'vareon-calculator-suite-lite' ) : __( 'mi', 'vareon-calculator-suite-lite' );
    const consumptionUnit = isMetric ? __( 'L/100km', 'vareon-calculator-suite-lite' ) : __( 'MPG', 'vareon-calculator-suite-lite' );
    const fuelPriceUnit = isMetric ? __( 'L', 'vareon-calculator-suite-lite' ) : __( 'gal', 'vareon-calculator-suite-lite' );
    const currencySymbol = escapeHtml(formatting.currencySymbol || '$');
    const distancePlaceholder = isMetric ? __( 'e.g.', 'vareon-calculator-suite-lite' ) + ' 400' : __( 'e.g.', 'vareon-calculator-suite-lite' ) + ' 250';
    const consumptionPlaceholder = isMetric ? __( 'e.g.', 'vareon-calculator-suite-lite' ) + ' 8' : __( 'e.g.', 'vareon-calculator-suite-lite' ) + ' 30';
    const pricePlaceholder = isMetric ? __( 'e.g.', 'vareon-calculator-suite-lite' ) + ' 1.50' : __( 'e.g.', 'vareon-calculator-suite-lite' ) + ' 3.50';
    const consumptionHelp = isMetric
      ? __( 'Lower is better. (L/100km)', 'vareon-calculator-suite-lite' )
      : __( 'Higher is better. (MPG)', 'vareon-calculator-suite-lite' );
    const fuelPriceSuffix = `${currencySymbol}/${fuelPriceUnit}`;
    
    // Build segmented controls in the trip setup header
    const unitControlHTML = shouldShowMeasurementToggle() ? getUnitSegmentedControlHTML() : '';
    const tripMode = isRoundTrip ? 'roundtrip' : 'oneway';
    const oneWayActive = tripMode === 'oneway';
    const roundTripActive = tripMode === 'roundtrip';
    
    const inputPanel = `
      <div class="fuel-panel fuel-panel--input">
        <div class="fuel-trip-section vareoncalc-section">
          <div class="fuel-trip-section__header vareoncalc-section__header">
            <div class="fuel-trip-section__title vareoncalc-section__title">${__( 'Trip Setup', 'vareon-calculator-suite-lite' )}</div>
            <div class="fuel-trip-section__controls">
              ${unitControlHTML}
              <div class="vareoncalc-toggle vareoncalc-measurement-toggle fuel-trip-mode-toggle fuel-icon-toggle" data-fuel-trip-mode-toggle data-mode="${tripMode}" data-active="${tripMode}" role="group" aria-label="${__( 'Trip type', 'vareon-calculator-suite-lite' )}">
                <input type="radio" name="fuel-trip-mode" id="one-way" value="oneway" class="vareoncalc-visually-hidden" ${oneWayActive ? 'checked' : ''}>
                <input type="radio" name="fuel-trip-mode" id="round-trip" value="roundtrip" class="vareoncalc-visually-hidden" ${roundTripActive ? 'checked' : ''}>
                <div class="vareoncalc-toggle__track">
                  <button type="button" class="vareoncalc-toggle__option vareoncalc-measurement-toggle__btn fuel-trip-mode-toggle__btn fuel-icon-toggle__btn fuel-trip-mode-toggle__btn--oneway${oneWayActive ? ' is-active vareoncalc-measurement-toggle__btn--active' : ''}" data-fuel-trip-mode-option="oneway" aria-pressed="${oneWayActive ? 'true' : 'false'}" title="${__( 'One Way', 'vareon-calculator-suite-lite' )}">
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></svg>
                  </button>
                  <button type="button" class="vareoncalc-toggle__option vareoncalc-measurement-toggle__btn fuel-trip-mode-toggle__btn fuel-icon-toggle__btn fuel-trip-mode-toggle__btn--roundtrip${roundTripActive ? ' is-active vareoncalc-measurement-toggle__btn--active' : ''}" data-fuel-trip-mode-option="roundtrip" aria-pressed="${roundTripActive ? 'true' : 'false'}" title="${__( 'Round Trip', 'vareon-calculator-suite-lite' )}">
                    <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m17 2 4 4-4 4"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><path d="m7 22-4-4 4-4"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/></svg>
                  </button>
                </div>
              </div>
            </div>
          </div>
          <div class="fuel-distance-row">
            <div class="vareoncalc-field fuel-distance-field">
              <label id="label-distance" for="distance">${__( 'Trip Distance', 'vareon-calculator-suite-lite' )}</label>
              <input type="number" inputmode="decimal" id="distance" data-suffix="${distanceUnit}" placeholder="${distancePlaceholder}" min="0" step="0.1">
            </div>
          </div>
        </div>
        
        <div class="fuel-economics-section vareoncalc-section">
          <div class="fuel-economics-section__header vareoncalc-section__header vareoncalc-section__title">${__( 'Vehicle Economics', 'vareon-calculator-suite-lite' )}</div>
          <div class="vareoncalc-field-row">
            <div class="vareoncalc-field">
              <label id="label-consumption" for="consumption" data-help="${consumptionHelp}">${isMetric ? __( 'Consumption', 'vareon-calculator-suite-lite' ) : __( 'Fuel Economy', 'vareon-calculator-suite-lite' )}</label>
              <input type="number" inputmode="decimal" id="consumption" data-suffix="${consumptionUnit}" placeholder="${consumptionPlaceholder}" min="0.1" step="0.1">
            </div>
            <div class="vareoncalc-field">
              <label id="label-price" for="fuel-price">${__( 'Fuel Price', 'vareon-calculator-suite-lite' )}</label>
              <input type="number" inputmode="decimal" id="fuel-price" data-suffix="${fuelPriceSuffix}" data-suffix-family="compound" placeholder="${pricePlaceholder}" min="0" step="0.01">
            </div>
          </div>
        </div>

        <button type="button" class="vareoncalc-btn" id="calc-btn" data-two-step-next>${__( 'Calculate Fuel Cost', 'vareon-calculator-suite-lite' )}</button>
      </div>
    `;
    
    const resultPanel = `
      <div class="fuel-panel fuel-panel--result">
        <div class="fuel-result-content" id="result">
          <div class="fuel-result-placeholder">
            <svg class="fuel-result-placeholder__icon" width="48" height="48" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
              <path d="M3 3v18h18"/>
              <path d="M18 17l-6-6-4 4-3-3"/>
            </svg>
            <p class="fuel-result-placeholder__text">${__( 'Enter your trip details to see the cost breakdown', 'vareon-calculator-suite-lite' )}</p>
          </div>
        </div>
      </div>
    `;

    container.innerHTML = `
      <div class="vareoncalc-two-step" data-two-step data-two-step-mode="blind">
        <div class="vareoncalc-two-step__step vareoncalc-two-step__step--inputs" data-two-step-step="inputs">
          <div class="vareoncalc-two-step__inputs-body">
            ${inputPanel}
          </div>
        </div>
        <div class="vareoncalc-two-step__step vareoncalc-two-step__step--results" data-two-step-step="results" aria-hidden="true">
          <div class="vareoncalc-two-step__results">
            ${resultPanel}
          </div>
        </div>
        <button type="button" class="vareoncalc-two-step__blind-handle" data-two-step-toggle>
          <span class="vareoncalc-two-step__blind-handle-grip" aria-hidden="true"></span>
          <span>${__( 'Edit inputs', 'vareon-calculator-suite-lite' )}</span>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m18 15-6-6-6 6"/></svg>
        </button>
      </div>
    `;
    
    InputAdornment.apply(container);
    HelpTooltip.apply(container);
    
    const distanceInput = container.querySelector('#distance');
    const consumptionInput = container.querySelector('#consumption');
    const priceInput = container.querySelector('#fuel-price');
    const tripModeToggle = container.querySelector('[data-fuel-trip-mode-toggle]');
    const oneWayOption = container.querySelector('[data-fuel-trip-mode-option="oneway"]');
    const roundTripOption = container.querySelector('[data-fuel-trip-mode-option="roundtrip"]');
    const oneWayInput = container.querySelector('#one-way');
    const roundTripInput = container.querySelector('#round-trip');
    const btn = container.querySelector('#calc-btn');
    const result = container.querySelector('#result');
    [distanceInput, consumptionInput, priceInput].forEach((input) => {
      input?.closest('.vareoncalc-input-adorned')?.classList.add('vareoncalc-input-adorned--suffix-rail');
    });
    const consumptionRail = consumptionInput?.closest('.vareoncalc-input-adorned');
    consumptionRail?.classList.add('fuel-consumption-rail');
    consumptionRail?.classList.add(isMetric ? 'fuel-consumption-rail--metric' : 'fuel-consumption-rail--imperial');
    const canProceed = () => canProceedForInputs(distanceInput, consumptionInput, priceInput);

    // Attach shared measurement toggle listener for unit switching.
    if (shouldShowMeasurementToggle()) {
      attachMeasurementToggleListener(container, measurementToggleId, (newMode) => {
        if (newMode === currentMode) return;

        // Save current values for conversion.
        const oldDistance = parseFloat(distanceInput.value);
        const oldConsumption = parseFloat(consumptionInput.value);
        const oldPrice = parseFloat(priceInput.value);
        const litersPerGallon = convertVolume(1, 'gallons', 'liters');

        currentMode = newMode;
        render();

        // Convert and restore values.
        const newDistanceInput = container.querySelector('#distance');
        const newConsumptionInput = container.querySelector('#consumption');
        const newPriceInput = container.querySelector('#fuel-price');

        if (!isNaN(oldDistance) && oldDistance > 0) {
          const convertedDistance = newMode === 'metric'
            ? convertDistance(oldDistance, 'miles', 'km')
            : convertDistance(oldDistance, 'km', 'miles');
          newDistanceInput.value = convertedDistance.toFixed(1);
        }

        if (!isNaN(oldConsumption) && oldConsumption > 0) {
          const convertedConsumption = newMode === 'metric'
            ? convertFuelEfficiency(oldConsumption, 'mpg', 'l_per_100km')
            : convertFuelEfficiency(oldConsumption, 'l_per_100km', 'mpg');
          newConsumptionInput.value = convertedConsumption.toFixed(1);
        }

        if (!isNaN(oldPrice) && oldPrice > 0) {
          if (newMode === 'metric') {
            newPriceInput.value = (oldPrice / litersPerGallon).toFixed(2);
          } else {
            newPriceInput.value = (oldPrice * litersPerGallon).toFixed(2);
          }
        }
      });
    }

    const setTripMode = (mode, shouldRecalculate = true) => {
      const normalizedMode = mode === 'roundtrip' ? 'roundtrip' : 'oneway';
      const roundTripSelected = normalizedMode === 'roundtrip';
      isRoundTrip = roundTripSelected;

      if (tripModeToggle instanceof HTMLElement) {
        tripModeToggle.setAttribute('data-mode', normalizedMode);
        tripModeToggle.setAttribute('data-active', normalizedMode);
      }

      if (oneWayOption instanceof HTMLElement) {
        oneWayOption.classList.toggle('is-active', !roundTripSelected);
        oneWayOption.classList.toggle('vareoncalc-measurement-toggle__btn--active', !roundTripSelected);
        oneWayOption.setAttribute('aria-pressed', !roundTripSelected ? 'true' : 'false');
      }
      if (roundTripOption instanceof HTMLElement) {
        roundTripOption.classList.toggle('is-active', roundTripSelected);
        roundTripOption.classList.toggle('vareoncalc-measurement-toggle__btn--active', roundTripSelected);
        roundTripOption.setAttribute('aria-pressed', roundTripSelected ? 'true' : 'false');
      }
      if (oneWayInput instanceof HTMLInputElement) {
        oneWayInput.checked = !roundTripSelected;
      }
      if (roundTripInput instanceof HTMLInputElement) {
        roundTripInput.checked = roundTripSelected;
      }

      if (shouldRecalculate && lastCalculation) {
        runCalculation({ revealResults: false });
      }
    };

    if (tripModeToggle instanceof HTMLElement) {
      tripModeToggle.addEventListener('click', (event) => {
        if (!(event.target instanceof Element)) {
          return;
        }
        const selectedOption = event.target.closest('[data-fuel-trip-mode-option]');
        if (!(selectedOption instanceof HTMLButtonElement)) {
          return;
        }
        const nextMode = selectedOption.getAttribute('data-fuel-trip-mode-option') === 'roundtrip' ? 'roundtrip' : 'oneway';
        const currentMode = isRoundTrip ? 'roundtrip' : 'oneway';
        if (nextMode === currentMode) {
          return;
        }
        setTripMode(nextMode);
      });
    }

    const handleTripModeInputChange = (event) => {
      const target = event.target;
      if (!(target instanceof HTMLInputElement) || !target.checked) {
        return;
      }
      setTripMode(target.id === 'round-trip' ? 'roundtrip' : 'oneway');
    };
    if (oneWayInput instanceof HTMLInputElement) {
      oneWayInput.addEventListener('change', handleTripModeInputChange);
    }
    if (roundTripInput instanceof HTMLInputElement) {
      roundTripInput.addEventListener('change', handleTripModeInputChange);
    }

    const runCalculation = ({ event = null, revealResults = true } = {}) => {
      ValidationHelpers.clearAllErrors(container);

      const invalidInputs = [];
      const messages = [];
      const recordInvalid = (input, message, options = {}) => {
        if (!input) {
          return;
        }
        ValidationHelpers.markInvalid(input, options);
        invalidInputs.push(input);
        if (message) {
          messages.push(message);
        }
      };
      
      const distance = parseFloat(distanceInput.value);
      const consumption = parseFloat(consumptionInput.value);
      const fuelPrice = parseFloat(priceInput.value);
      const isMetricCalc = currentMode === 'metric';

      // Validation
      if (!Number.isFinite(distance) || distance <= 0) {
        recordInvalid(
          distanceInput,
          __( 'Please enter a valid trip distance.', 'vareon-calculator-suite-lite' ),
          {
            validator: () => {
              const value = parseFloat(distanceInput.value);
              return Number.isFinite(value) && value > 0;
            },
          }
        );
      }

      if (!Number.isFinite(consumption) || consumption <= 0) {
        recordInvalid(
          consumptionInput,
          __( 'Please enter a valid fuel consumption.', 'vareon-calculator-suite-lite' ),
          {
            validator: () => {
              const value = parseFloat(consumptionInput.value);
              return Number.isFinite(value) && value > 0;
            },
          }
        );
      }

      if (!Number.isFinite(fuelPrice) || fuelPrice <= 0) {
        recordInvalid(
          priceInput,
          __( 'Please enter a valid fuel price.', 'vareon-calculator-suite-lite' ),
          {
            validator: () => {
              const value = parseFloat(priceInput.value);
              return Number.isFinite(value) && value > 0;
            },
          }
        );
      }

      if (invalidInputs.length > 0) {
        const message = messages.length === 1
          ? messages[0]
          : __( 'Please fix the highlighted fields.', 'vareon-calculator-suite-lite' );
        ValidationHelpers.showToast(container, message);
        if (event) {
          event.preventDefault();
          event.stopImmediatePropagation();
        }
        return false;
      }

      // Calculate one-way fuel needed and cost
      let oneWayFuel, oneWayCost;
      
      if (isMetricCalc) {
        oneWayFuel = (distance / 100) * consumption;
        oneWayCost = oneWayFuel * fuelPrice;
      } else {
        oneWayFuel = distance / consumption;
        oneWayCost = oneWayFuel * fuelPrice;
      }
      
      // Calculate round trip values
      const roundTripFuel = oneWayFuel * 2;
      const roundTripCost = oneWayCost * 2;
      
      // Determine displayed cost based on round trip checkbox
      const displayedCost = isRoundTrip ? roundTripCost : oneWayCost;
      const displayedFuel = isRoundTrip ? roundTripFuel : oneWayFuel;

      const fuelLabel = isMetricCalc ? __( 'Liters', 'vareon-calculator-suite-lite' ) : __( 'Gallons', 'vareon-calculator-suite-lite' );
      
      // Store calculation for re-use
      lastCalculation = { oneWayCost, roundTripCost, displayedCost, displayedFuel };

      const formattingConfig = getFormattingConfig();
      const symbol = escapeHtml(formattingConfig.currencySymbol || '$');
      const isCommutable = distance < (isMetricCalc ? 100 : 60);
      let annualHtml = '';

      if (isCommutable) {
        const dailyCost = isRoundTrip ? displayedCost : displayedCost * 2;
        const annualCost = dailyCost * 240;
        const annualAmount = Math.round(annualCost).toLocaleString();

        annualHtml = `
          <div class="fuel-annual-insight">
            <div class="fuel-annual-insight__icon" aria-hidden="true">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                <rect x="3" y="4" width="18" height="18" rx="2" ry="2"/>
                <line x1="16" y1="2" x2="16" y2="6"/>
                <line x1="8" y1="2" x2="8" y2="6"/>
                <line x1="3" y1="10" x2="21" y2="10"/>
              </svg>
            </div>
            <div class="fuel-annual-insight__text">
              ${__( 'Do this trip daily?', 'vareon-calculator-suite-lite' )}
              <span class="fuel-annual-insight__amount">~${symbol}${annualAmount} / ${__( 'year', 'vareon-calculator-suite-lite' )}</span>
            </div>
          </div>
        `;
      }

      const totalDistance = isRoundTrip ? distance * 2 : distance;
      const safePassengers = Number.isFinite(currentPassengers) && currentPassengers > 0 ? currentPassengers : 1;
      const initCostPerPerson = displayedCost / safePassengers;

      const oneWayBarHeight = roundTripCost > 0 ? ((oneWayCost / roundTripCost) * 100).toFixed(1) : 50;

      result.innerHTML = `
        <div class="fuel-detailed-results">
          <div class="fuel-detailed-results__title">${__( 'Fuel Calculator Detailed Results', 'vareon-calculator-suite-lite' )}</div>

          <div class="fuel-detail-card fuel-detail-card--hero">
            <div class="fuel-detail-card__cost-label">${__( 'Total Estimated Cost', 'vareon-calculator-suite-lite' )}</div>
            <div class="fuel-detail-card__cost-amount">${fmtCost(displayedCost)}</div>
            <div class="fuel-detail-card__metrics">
              <div class="fuel-detail-card__fuel-stat">
                <div class="fuel-detail-card__fuel-stat-icon" aria-hidden="true">
                  <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22a7 7 0 0 0 7-7c0-2-1-3.9-3-5.5s-3.5-4-4-6.5c-.5 2.5-2 4.9-4 6.5C6 11.1 5 13 5 15a7 7 0 0 0 7 7z"/></svg>
                </div>
                <div class="fuel-detail-card__fuel-stat-body">
                  <span class="fuel-detail-card__fuel-stat-label">${__( 'Fuel required', 'vareon-calculator-suite-lite' )}</span>
                  <span class="fuel-detail-card__fuel-stat-value">${formatFuelVolumeForDisplay(displayedFuel, fuelLabel)}</span>
                </div>
              </div>
              ${isRoundTrip ? `
              <div class="fuel-detail-card__trip-mode" role="status">
                <svg class="fuel-detail-card__trip-mode-icon" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.25" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="m17 2 4 4-4 4"/><path d="M3 11V9a4 4 0 0 1 4-4h14"/><path d="m7 22-4-4 4-4"/><path d="M21 13v2a4 4 0 0 1-4 4H3"/></svg>
                <span class="fuel-detail-card__trip-mode-text">${__( 'Round trip', 'vareon-calculator-suite-lite' )}</span>
              </div>` : ''}
            </div>
          </div>

          <div class="fuel-detail-card fuel-detail-card--breakdown">
            <div class="fuel-detail-card__section-title">${__( 'Trip Breakdown', 'vareon-calculator-suite-lite' )}</div>
            <div class="fuel-breakdown-grid">
              <div class="fuel-breakdown-item">
                <div class="fuel-breakdown-item__icon" aria-hidden="true">
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 22V5a2 2 0 0 1 2-2h5a2 2 0 0 1 2 2v17"/><path d="M4 9h9"/><path d="M13 7h2l2 2v7a2 2 0 0 1-2 2h-2"/><path d="M4 22h10"/></svg>
                </div>
                <div class="fuel-breakdown-item__label">${__( 'Fuel Efficiency', 'vareon-calculator-suite-lite' )}</div>
                <div class="fuel-breakdown-item__value">${consumption} ${consumptionUnit}</div>
              </div>
              <div class="fuel-breakdown-item">
                <div class="fuel-breakdown-item__icon" aria-hidden="true">
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/></svg>
                </div>
                <div class="fuel-breakdown-item__label">${__( 'Total Distance', 'vareon-calculator-suite-lite' )}</div>
                <div class="fuel-breakdown-item__value">${totalDistance} ${distanceUnit}</div>
              </div>
              <div class="fuel-breakdown-item">
                <div class="fuel-breakdown-item__icon" aria-hidden="true">
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="1" x2="12" y2="23"/><path d="M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"/></svg>
                </div>
                <div class="fuel-breakdown-item__label">${isMetricCalc ? __( 'Price per Liter', 'vareon-calculator-suite-lite' ) : __( 'Price per Gallon', 'vareon-calculator-suite-lite' )}</div>
                <div class="fuel-breakdown-item__value">${formatCurrency(fuelPrice)}/${fuelPriceUnit}</div>
              </div>
            </div>
          </div>

          <div class="fuel-detail-card fuel-detail-card--splitting">
            <div class="fuel-detail-card__section-title">${__( 'Cost Splitting', 'vareon-calculator-suite-lite' )}</div>
            <input type="range"
                   class="fuel-detail-slider"
                   data-fuel-passenger-slider
                   min="1"
                   max="6"
                   value="${safePassengers}"
                   aria-label="${__( 'Total people in car', 'vareon-calculator-suite-lite' )}">
            <div class="fuel-detail-slider__label" data-fuel-split-label>${safePassengers <= 1
                ? __( 'No split', 'vareon-calculator-suite-lite' )
                : `${__( 'Split', 'vareon-calculator-suite-lite' )} <strong>${safePassengers}</strong> ${__( 'ways', 'vareon-calculator-suite-lite' )}`
              }</div>
          </div>

          <div class="fuel-detail-bottom-row">
            <div class="fuel-detail-card fuel-detail-card--perperson">
              <div class="fuel-detail-card__section-title">${__( 'Cost Per Person', 'vareon-calculator-suite-lite' )}</div>
              <div class="fuel-detail-card__perperson-wrap">
                <div class="fuel-detail-card__perperson-amount" data-fuel-per-person-value>${fmtCost(initCostPerPerson)}</div>
              </div>
            </div>
            <div class="fuel-detail-card fuel-detail-card--comparison">
              <div class="fuel-detail-card__section-title">${__( 'Trip Comparison', 'vareon-calculator-suite-lite' )}</div>
              <div class="fuel-comparison__columns">
                <div class="fuel-comparison__column">
                  <span class="fuel-comparison__column-value">${fmtCost(oneWayCost)}</span>
                  <div class="fuel-comparison__column-bar-wrap">
                    <div class="fuel-comparison__column-bar fuel-comparison__column-bar--oneway" style="height: ${oneWayBarHeight}%"></div>
                  </div>
                  <span class="fuel-comparison__column-label">${__( 'One Way', 'vareon-calculator-suite-lite' )}</span>
                </div>
                <div class="fuel-comparison__column">
                  <span class="fuel-comparison__column-value">${fmtCost(roundTripCost)}</span>
                  <div class="fuel-comparison__column-bar-wrap">
                    <div class="fuel-comparison__column-bar fuel-comparison__column-bar--roundtrip" style="height: 100%"></div>
                  </div>
                  <span class="fuel-comparison__column-label">${__( 'Round Trip', 'vareon-calculator-suite-lite' )}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        ${annualHtml}
      `;

      const passengerSlider = result.querySelector('[data-fuel-passenger-slider]');
      const splitLabel = result.querySelector('[data-fuel-split-label]');
      const costPerPersonEl = result.querySelector('[data-fuel-per-person-value]');

      const updatePassengerComparison = () => {
        updatePassengerSliderFill(passengerSlider);
        const perPerson = displayedCost / currentPassengers;
        if (splitLabel) {
          splitLabel.innerHTML = currentPassengers <= 1
            ? __( 'No split', 'vareon-calculator-suite-lite' )
            : `${__( 'Split', 'vareon-calculator-suite-lite' )} <strong>${currentPassengers}</strong> ${__( 'ways', 'vareon-calculator-suite-lite' )}`;
        }
        if (costPerPersonEl) {
          costPerPersonEl.innerHTML = fmtCost(perPerson);
        }
      };

      if (passengerSlider) {
        passengerSlider.addEventListener('input', (e) => {
          currentPassengers = parseInt(e.target.value, 10);
          if (!Number.isFinite(currentPassengers) || currentPassengers < 1) {
            currentPassengers = 1;
          }
          updatePassengerComparison();
          refreshTwoStepLayout();
        });
      }
      updatePassengerComparison();
      refreshTwoStepLayout();
      if (revealResults) {
        showResultsStep();
      }

      return true;
    };

    btn.addEventListener('click', (event) => {
      runCalculation({ event, revealResults: true });
    });

    twoStepInstance = initCompactTwoStep(container, { canProceed });
    if (twoStepInstance && typeof twoStepInstance.refreshLayout === 'function') {
      twoStepInstance.refreshLayout();
    }
  }
  
  render();
}
