import { formatCurrencyHtml, formatNumber, getFormattingConfig, escapeHtml } from '../utils/formatting.js';
import { ValidationHelpers, InputAdornment, HelpTooltip, __, sprintf } from '@vareoncalc/calculator-base';
import { initCompactTwoStep } from '../utils/compact-two-step.js';

/**
 * Discount Calculator
 * Calculate discounts with percentage or fixed amount
 */

export function mount(container) {
  const formatting = getFormattingConfig();
  const rawCurrencySymbol = formatting.currencySymbol || '$';
  const currencySymbol = escapeHtml(rawCurrencySymbol);
  const percentDecimals = typeof formatting.percentDecimals === 'number' ? formatting.percentDecimals : 1;
  const layout = (window.VAREONCALC_CFG && window.VAREONCALC_CFG.layout) || 'compact';
  const isWide = layout === 'wide';

  // Get enabled discount types from config
  const configuredTypes = (window.VAREONCALC_CFG && window.VAREONCALC_CFG.calculatorOptions &&
    window.VAREONCALC_CFG.calculatorOptions['discount'] &&
    window.VAREONCALC_CFG.calculatorOptions['discount'].enabled_types) || null;

  const fallbackTypes = ['percentage', 'amount'];
  const normalizedTypes = [];

  (configuredTypes && configuredTypes.length ? configuredTypes : fallbackTypes).forEach(type => {
    let normalized = type === 'fixed-amount' ? 'amount' : type;
    if (normalized !== 'percentage' && normalized !== 'amount') {
      return;
    }
    if (normalizedTypes.indexOf(normalized) === -1) {
      normalizedTypes.push(normalized);
    }
  });

  if (!normalizedTypes.length) {
    normalizedTypes.push('percentage');
  }
  const defaultType = normalizedTypes[0];

  const amountLabel = __('Fixed Amount', 'vareon-calculator-suite-lite');
  const types = {
    percentage: __('Percentage', 'vareon-calculator-suite-lite'),
    amount: amountLabel
  };

  // Build type options dynamically
  let typeOptions = '';
  normalizedTypes.forEach(type => {
    if (types[type]) {
      typeOptions += `<option value="${type}">${types[type]}</option>`;
    }
  });

  // Hide type selector if only one type enabled
  const showTypeSelector = normalizedTypes.length > 1;

  // Add layout class to container
  if (isWide) {
    container.parentElement.classList.add('layout-wide');
  }

  // Build the form: compact two-step layout (inputs -> results + edit drawer)
  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">
          <div class="discount-form">
          <div class="discount-section vareoncalc-section">
            <div class="discount-section__header vareoncalc-section__header">
              <div class="discount-section__title vareoncalc-section__title">${__('Price Mode', 'vareon-calculator-suite-lite')}</div>
            </div>
            <div class="discount-grid discount-grid--price" id="discount-mode-row">
              <div class="discount-field discount-price-field">
                <div class="discount-price-field__label-row">
                  <label id="price-label" for="original-price">${__('Original Price', 'vareon-calculator-suite-lite')}</label>
                  <div class="discount-mode-toggle">
                    <div class="vareoncalc-toggle vareoncalc-measurement-toggle discount-mode-toggle__control" data-discount-mode-toggle data-mode="original" data-active="original" role="group" aria-label="${__('Price mode', 'vareon-calculator-suite-lite')}">
                      <input type="radio" name="discount-price-mode" id="discount-mode-original" value="original" class="vareoncalc-visually-hidden" checked>
                      <input type="radio" name="discount-price-mode" id="discount-mode-final" value="final" class="vareoncalc-visually-hidden">
                      <div class="vareoncalc-toggle__track">
                        <div class="vareoncalc-toggle__indicator" aria-hidden="true"></div>
                        <button type="button" class="vareoncalc-toggle__option vareoncalc-measurement-toggle__btn discount-mode-toggle__btn discount-mode-toggle__btn--original is-active vareoncalc-measurement-toggle__btn--active" data-discount-mode-option="original" aria-pressed="true" tabindex="0">
                          ${__('Original', 'vareon-calculator-suite-lite')}
                        </button>
                        <button type="button" class="vareoncalc-toggle__option vareoncalc-measurement-toggle__btn discount-mode-toggle__btn discount-mode-toggle__btn--final" data-discount-mode-option="final" aria-pressed="false" tabindex="-1">
                          ${__('Final', 'vareon-calculator-suite-lite')}
                        </button>
                      </div>
                    </div>
                  </div>
                </div>
              <input type="number" id="original-price" class="discount-price-input" data-suffix="${currencySymbol}" data-suffix-family="currency" placeholder="100.00" min="0" step="0.01">
              </div>
            </div>
          </div>

          <div class="discount-section vareoncalc-section">
            <div class="discount-section__header vareoncalc-section__header">
              <div class="discount-section__title vareoncalc-section__title">${__('Discount Details', 'vareon-calculator-suite-lite')}</div>
            </div>
            <div class="discount-grid discount-grid--discount">
              ${showTypeSelector ? `
              <div class="discount-field">
                <label for="discount-type">${__('Discount Type', 'vareon-calculator-suite-lite')}</label>
                <select id="discount-type">
                  ${typeOptions}
                </select>
              </div>
              ` : `
              <div class="discount-field discount-field--static">
                <span class="discount-field__label">${__('Discount Type', 'vareon-calculator-suite-lite')}</span>
                <div class="discount-static">${types[defaultType]}</div>
                <input type="hidden" id="discount-type" value="${defaultType}">
              </div>
              `}
              <div class="discount-field">
                <label id="discount-label" for="discount-value">${__('Discount', 'vareon-calculator-suite-lite')}</label>
                <input type="number" id="discount-value" data-suffix="%" placeholder="20" min="0" step="0.01" required aria-required="true">
              </div>
            </div>
          </div>

          <div class="discount-section vareoncalc-section discount-section--advanced vareoncalc-disclosure vareoncalc-disclosure--optional">
            <div class="discount-section__header vareoncalc-section__header vareoncalc-disclosure__header">
              <div class="discount-section__title vareoncalc-section__title vareoncalc-disclosure__title">${__('Optional Details', 'vareon-calculator-suite-lite')}</div>
              <div class="discount-advanced-toggle">
                <button
                  type="button"
                  class="discount-advanced-accordion vareoncalc-disclosure__toggle vareoncalc-disclosure__toggle--compact"
                  id="discount-advanced-accordion"
                  aria-expanded="false"
                  aria-controls="discount-advanced"
                  aria-label="${__('Toggle more options', 'vareon-calculator-suite-lite')}"
                >
                  <span class="discount-advanced-accordion__text">${__('Show more options', 'vareon-calculator-suite-lite')}</span>
                  <span class="discount-advanced-accordion__icon vareoncalc-disclosure__icon" aria-hidden="true">></span>
                </button>
              </div>
            </div>

            <div class="discount-advanced vareoncalc-disclosure__content" id="discount-advanced" hidden>
              <div class="discount-grid discount-grid--advanced">
                <div class="discount-field discount-field--wide" id="extra-discount-row">
                  <label for="extra-discount-rate">${__('Additional Discount', 'vareon-calculator-suite-lite')}</label>
                  <input type="number" id="extra-discount-rate" data-suffix="%" placeholder="10" min="0" step="0.01">
                </div>
                <div class="discount-field">
                  <label for="sales-tax">${__('Sales Tax', 'vareon-calculator-suite-lite')}</label>
                  <input type="number" id="sales-tax" data-suffix="%" placeholder="8.5" min="0" step="0.01">
                </div>
                <div class="discount-field">
                  <label for="quantity">${__('Quantity', 'vareon-calculator-suite-lite')}</label>
                  <input type="number" id="quantity" placeholder="1" min="1" step="1">
                </div>
              </div>
            </div>
          </div>
          </div>

          <button type="button" class="vareoncalc-btn" id="calc-btn" data-two-step-next>${__('See results', 'vareon-calculator-suite-lite')}</button>
        </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">
          <div class="vareoncalc-panel-result vareoncalc-panel-result--placeholder" id="result-panel">
            <div class="placeholder-icon">&#127991;</div>
            <div class="placeholder-text">${__('Enter a price and discount to see your savings', 'vareon-calculator-suite-lite')}</div>
          </div>
        </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>
    <div class="vareoncalc-visually-hidden" id="discount-status" role="status" aria-live="polite" aria-atomic="true"></div>
  `;

  InputAdornment.apply(container);
  HelpTooltip.apply(container);

  const originalPriceInput = container.querySelector('#original-price');
  const priceLabel = container.querySelector('#price-label');
  const discountTypeSelect = container.querySelector('#discount-type');
  const discountLabel = container.querySelector('#discount-label');
  const discountValueInput = container.querySelector('#discount-value');
  const priceModeRow = container.querySelector('#discount-mode-row');
  const priceModeToggle = container.querySelector('[data-discount-mode-toggle]');
  const priceModeOriginalOption = container.querySelector('[data-discount-mode-option="original"]');
  const priceModeFinalOption = container.querySelector('[data-discount-mode-option="final"]');
  const priceModeOriginalInput = container.querySelector('#discount-mode-original');
  const priceModeFinalInput = container.querySelector('#discount-mode-final');
  const advancedAccordion = container.querySelector('#discount-advanced-accordion');
  const advancedAccordionText = container.querySelector('.discount-advanced-accordion__text');
  const advancedOptions = container.querySelector('#discount-advanced');
  const extraDiscountRateInput = container.querySelector('#extra-discount-rate');
  const salesTaxInput = container.querySelector('#sales-tax');
  const quantityInput = container.querySelector('#quantity');
  [originalPriceInput, discountValueInput, extraDiscountRateInput, salesTaxInput].forEach((input) => {
    input?.closest('.vareoncalc-input-adorned')?.classList.add('vareoncalc-input-adorned--suffix-rail');
  });
  const btn = container.querySelector('#calc-btn');
  const resultPanel = container.querySelector('#result-panel');
  const statusAnnouncer = container.querySelector('#discount-status');
  let twoStepInstance = null;
  const forEachTwoStepInstance = (handler) => {
    if (!twoStepInstance) {
      return;
    }
    if (Array.isArray(twoStepInstance)) {
      twoStepInstance.forEach(instance => {
        if (instance) {
          handler(instance);
        }
      });
      return;
    }
    handler(twoStepInstance);
  };
  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();
      }
    });
  };
  const currencyPlaceholder = formatNumber(100, {
    decimals: formatting.currencyDecimals,
    maxDecimals: formatting.currencyDecimals,
    forceDecimals: formatting.currencyDecimals > 0,
  });
  originalPriceInput.placeholder = currencyPlaceholder;
  const percentPlaceholder = formatNumber(8.5, {
    decimals: percentDecimals,
    maxDecimals: percentDecimals,
    forceDecimals: percentDecimals > 0,
  });
  if (salesTaxInput) {
    salesTaxInput.placeholder = percentPlaceholder;
  }
  if (extraDiscountRateInput) {
    extraDiscountRateInput.placeholder = formatNumber(10, {
      decimals: percentDecimals,
      maxDecimals: percentDecimals,
      forceDecimals: percentDecimals > 0,
    });
    extraDiscountRateInput.max = '100';
  }

  // Reset result panel to placeholder state
  function resetResultPanel() {
    if (resultPanel) {
      resultPanel.className = 'vareoncalc-panel-result vareoncalc-panel-result--placeholder';
      resultPanel.innerHTML = `
        <div class="placeholder-icon">&#127991;</div>
        <div class="placeholder-text">${__('Enter a price and discount to see your savings', 'vareon-calculator-suite-lite')}</div>
      `;
    }
  }

  const announceStatus = message => {
    if (statusAnnouncer) {
      statusAnnouncer.textContent = message || '';
    }
  };

  const resetResult = () => {
    resetResultPanel();
  };

  const canProceed = () => {
    const isReverse = isReverseMode();
    const inputPrice = Number(originalPriceInput.value);
    if (!Number.isFinite(inputPrice) || inputPrice <= 0) return false;

    const discountType = discountTypeSelect.value;
    const discountRaw = (discountValueInput.value || '').trim();
    if (discountRaw === '') return false;
    const discountValue = Number(discountRaw);
    if (!Number.isFinite(discountValue) || discountValue < 0) return false;

    if (discountType === 'percentage') {
      if (discountValue > 100) return false;
      if (isReverse && discountValue >= 100) return false;
    }

    if (discountType === 'amount' && !isReverse && discountValue > inputPrice) return false;

    const salesTaxRaw = salesTaxInput?.value ?? '';
    const quantityRaw = quantityInput?.value ?? '';
    const extraRateRaw = extraDiscountRateInput?.value ?? '';
    const salesTaxRate = salesTaxRaw === '' ? 0 : Number(salesTaxRaw);
    const quantityValue = quantityRaw === '' ? 1 : Number(quantityRaw);
    const extraDiscountRate = extraRateRaw === '' ? 0 : Number(extraRateRaw);

    if (salesTaxRaw !== '' && (!Number.isFinite(salesTaxRate) || salesTaxRate < 0 || salesTaxRate > 100)) return false;
    if (quantityRaw !== '' && (!Number.isFinite(quantityValue) || quantityValue <= 0)) return false;
    if (!Number.isFinite(extraDiscountRate) || extraDiscountRate < 0 || extraDiscountRate > 100) return false;
    if (isReverse && extraDiscountRate >= 100) return false;

    return true;
  };

  const handleInputChange = () => {
    ValidationHelpers.clearAllErrors(container);
    resetResult();
  };

  const isReverseMode = () => !!priceModeFinalInput?.checked;
  const isAdvancedEnabled = () => advancedAccordion?.getAttribute('aria-expanded') === 'true';

  const updatePriceModeVisuals = () => {
    if (!priceModeToggle) {
      return;
    }
    const mode = isReverseMode() ? 'final' : 'original';
    priceModeToggle.setAttribute('data-mode', mode);
    priceModeToggle.setAttribute('data-active', mode);
    if (priceModeRow) {
      priceModeRow.classList.toggle('discount-mode-row--reverse', mode === 'final');
    }
    if (priceModeOriginalOption) {
      priceModeOriginalOption.setAttribute('aria-pressed', mode === 'original');
      priceModeOriginalOption.classList.toggle('is-active', mode === 'original');
      priceModeOriginalOption.classList.toggle('vareoncalc-measurement-toggle__btn--active', mode === 'original');
      priceModeOriginalOption.setAttribute('tabindex', mode === 'original' ? '0' : '-1');
    }
    if (priceModeFinalOption) {
      priceModeFinalOption.setAttribute('aria-pressed', mode === 'final');
      priceModeFinalOption.classList.toggle('is-active', mode === 'final');
      priceModeFinalOption.classList.toggle('vareoncalc-measurement-toggle__btn--active', mode === 'final');
      priceModeFinalOption.setAttribute('tabindex', mode === 'final' ? '0' : '-1');
    }
  };

  const updatePriceLabel = () => {
    const isReverse = isReverseMode();
    const labelText = isReverse
      ? __('Final Price', 'vareon-calculator-suite-lite')
      : __('Original Price', 'vareon-calculator-suite-lite');
    if (priceLabel) {
      priceLabel.textContent = labelText;
    }
    InputAdornment.setSuffix(originalPriceInput, currencySymbol);
    originalPriceInput.setAttribute('aria-label', labelText);
    announceStatus(
      isReverse
        ? __('Reverse mode enabled. Enter final price to estimate original price.', 'vareon-calculator-suite-lite')
        : __('Reverse mode disabled. Enter original price to calculate discount.', 'vareon-calculator-suite-lite')
    );
  };

  const setAdvancedEnabled = (enabled) => {
    if (!advancedOptions || !extraDiscountRateInput) {
      return;
    }
    const isEnabled = !!enabled;
    if (advancedAccordion) {
      advancedAccordion.setAttribute('aria-expanded', isEnabled ? 'true' : 'false');
    }
    if (advancedAccordionText) {
      advancedAccordionText.textContent = isEnabled
        ? __('Hide options', 'vareon-calculator-suite-lite')
        : __('Show more options', 'vareon-calculator-suite-lite');
    }
    advancedOptions.hidden = !isEnabled;
    extraDiscountRateInput.disabled = !isEnabled;
    if (salesTaxInput) salesTaxInput.disabled = !isEnabled;
    if (quantityInput) quantityInput.disabled = !isEnabled;

    refreshTwoStepLayout();
    announceStatus(
      isEnabled
        ? __('Optional details expanded.', 'vareon-calculator-suite-lite')
        : __('Optional details collapsed.', 'vareon-calculator-suite-lite')
    );
  };

  const setupPriceModeToggle = () => {
    if (!priceModeToggle || !priceModeOriginalInput || !priceModeFinalInput) {
      return;
    }

    const handleSwitch = () => {
      const nextMode = isReverseMode() ? 'original' : 'final';
      if (nextMode === 'final') {
        priceModeFinalInput.checked = true;
        priceModeOriginalInput.checked = false;
      } else {
        priceModeOriginalInput.checked = true;
        priceModeFinalInput.checked = false;
      }
      updatePriceModeVisuals();
      updatePriceLabel();
      handleInputChange();
    };

    priceModeToggle.addEventListener('click', event => {
      const control = event.target.closest('button[data-discount-mode-option]');
      if (control) {
        const nextMode = control.dataset.discountModeOption;
        if (nextMode === 'final') {
          priceModeFinalInput.checked = true;
          priceModeOriginalInput.checked = false;
        } else {
          priceModeOriginalInput.checked = true;
          priceModeFinalInput.checked = false;
        }
        updatePriceModeVisuals();
        updatePriceLabel();
        handleInputChange();
        return;
      }

      handleSwitch();
    });
  };

  const setupAdvancedAccordion = () => {
    if (!advancedAccordion) {
      return;
    }
    advancedAccordion.addEventListener('click', () => {
      setAdvancedEnabled(!isAdvancedEnabled());
      handleInputChange();
    });
  };

  // Update suffix and placeholder based on discount type
  function updateDiscountLabel() {
    const discountType = discountTypeSelect.value;

    if (discountType === 'percentage') {
      discountLabel.textContent = __('Discount', 'vareon-calculator-suite-lite');
      InputAdornment.setSuffix(discountValueInput, '%');
      discountValueInput.setAttribute('aria-label', __('Discount percentage', 'vareon-calculator-suite-lite'));
      discountValueInput.placeholder = formatNumber(20, {
        decimals: percentDecimals,
        maxDecimals: percentDecimals,
        forceDecimals: percentDecimals > 0,
      });
      discountValueInput.max = '100';
      announceStatus(__('Discount input set to percentage.', 'vareon-calculator-suite-lite'));
    } else {
      discountLabel.textContent = __('Discount Amount', 'vareon-calculator-suite-lite');
      InputAdornment.setSuffix(discountValueInput, currencySymbol);
      discountValueInput.setAttribute('aria-label', __('Discount amount', 'vareon-calculator-suite-lite'));
      discountValueInput.placeholder = formatNumber(15, {
        decimals: formatting.currencyDecimals,
        maxDecimals: formatting.currencyDecimals,
        forceDecimals: formatting.currencyDecimals > 0,
      });
      discountValueInput.removeAttribute('max');
      announceStatus(__('Discount input set to fixed amount.', 'vareon-calculator-suite-lite'));
    }

    // Clear result when type changes
    resetResult();
  }

  discountTypeSelect.addEventListener('change', () => {
    updateDiscountLabel();
    handleInputChange();
  });
  [originalPriceInput, discountValueInput, extraDiscountRateInput, salesTaxInput, quantityInput].forEach(input => {
    if (!input) return;
    input.addEventListener('input', handleInputChange);
    input.addEventListener('change', handleInputChange);
  });

  // Initialize labels on page load
  updateDiscountLabel();
  updatePriceModeVisuals();
  updatePriceLabel();
  setAdvancedEnabled(false);
  setupPriceModeToggle();
  setupAdvancedAccordion();

  btn.addEventListener('click', (event) => {
    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 isReverse = isReverseMode();
    const inputPrice = Number(originalPriceInput.value);
    const discountType = discountTypeSelect.value;
    const discountRaw = (discountValueInput.value || '').trim();
    const discountValue = discountRaw === '' ? Number.NaN : Number(discountRaw);
    const salesTaxRaw = salesTaxInput?.value ?? '';
    const quantityRaw = quantityInput?.value ?? '';
    const salesTaxRate = salesTaxRaw === '' ? 0 : Number(salesTaxRaw);
    const quantityValue = quantityRaw === '' ? 1 : Number(quantityRaw);
    const extraRateRaw = extraDiscountRateInput?.value ?? '';
    const extraDiscountRate = extraRateRaw === '' ? 0 : Number(extraRateRaw);
    const extraDiscountEnabled = Number.isFinite(extraDiscountRate) && extraDiscountRate > 0;

    const priceErrorMessage = isReverse
      ? __('Please enter a valid final price.', 'vareon-calculator-suite-lite')
      : __('Please enter a valid original price.', 'vareon-calculator-suite-lite');

    const discountValidator = () => {
      const price = Number(originalPriceInput.value);
      const rawValue = (discountValueInput.value || '').trim();
      if (rawValue === '') {
        return false;
      }
      const value = Number(rawValue);
      if (!Number.isFinite(value) || value < 0) {
        return false;
      }
      if (discountTypeSelect.value === 'percentage') {
        if (value > 100) {
          return false;
        }
        if (isReverseMode() && value >= 100) {
          return false;
        }
      }
      if (discountTypeSelect.value === 'amount' && !isReverseMode()) {
        if (!Number.isFinite(price) || price <= 0) {
          return false;
        }
        if (value > price) {
          return false;
        }
      }
      return true;
    };
    const priceValidator = () => {
      const price = Number(originalPriceInput.value);
      if (!Number.isFinite(price) || price <= 0) {
        return false;
      }
      if (discountTypeSelect.value === 'amount' && !isReverseMode()) {
        const value = Number(discountValueInput.value);
        if (Number.isFinite(value) && value > price) {
          return false;
        }
      }
      return true;
    };

    // Validation
    if (!Number.isFinite(inputPrice) || inputPrice <= 0) {
      recordInvalid(originalPriceInput, priceErrorMessage, { validator: priceValidator });
    }

    if (discountRaw === '') {
      recordInvalid(discountValueInput, __('Please enter a discount value.', 'vareon-calculator-suite-lite'), { validator: discountValidator });
    } else if (!Number.isFinite(discountValue) || discountValue < 0) {
      recordInvalid(discountValueInput, __('Please enter a valid discount value.', 'vareon-calculator-suite-lite'), { validator: discountValidator });
    }

    if (discountType === 'percentage') {
      if (discountValue > 100) {
        recordInvalid(discountValueInput, __('Discount percentage cannot exceed 100%.', 'vareon-calculator-suite-lite'), { validator: discountValidator });
      }
      if (isReverse && discountValue >= 100) {
        recordInvalid(discountValueInput, __('Discount percentage must be less than 100% in reverse mode.', 'vareon-calculator-suite-lite'), { validator: discountValidator });
      }
    }

    if (discountType === 'amount' && !isReverse && discountValue > inputPrice) {
      recordInvalid(discountValueInput, __('Discount amount cannot exceed original price.', 'vareon-calculator-suite-lite'), { validator: discountValidator });
      recordInvalid(originalPriceInput, null, { validator: priceValidator });
    }

    if (extraRateRaw !== '' && (!Number.isFinite(extraDiscountRate) || extraDiscountRate < 0 || extraDiscountRate > 100)) {
      recordInvalid(extraDiscountRateInput, __('Please enter a valid additional discount rate.', 'vareon-calculator-suite-lite'), {
        allowEmpty: true,
        validator: () => {
          const raw = extraDiscountRateInput?.value ?? '';
          if (raw === '') {
            return true;
          }
          const value = Number(raw);
          if (!Number.isFinite(value) || value < 0 || value > 100) {
            return false;
          }
          if (isReverseMode() && value >= 100) {
            return false;
          }
          return true;
        },
      });
    }
    if (extraRateRaw !== '' && isReverse && extraDiscountRate >= 100) {
      recordInvalid(extraDiscountRateInput, __('Additional discount must be less than 100% in reverse mode.', 'vareon-calculator-suite-lite'), {
        allowEmpty: true,
        validator: () => {
          const raw = extraDiscountRateInput?.value ?? '';
          if (raw === '') {
            return true;
          }
          const value = Number(raw);
          return Number.isFinite(value) && value >= 0 && value < 100;
        },
      });
    }

    if (salesTaxRaw !== '' && (!Number.isFinite(salesTaxRate) || salesTaxRate < 0 || salesTaxRate > 100)) {
      recordInvalid(salesTaxInput, __('Please enter a valid sales tax rate.', 'vareon-calculator-suite-lite'), {
        allowEmpty: true,
        validator: () => {
          const raw = salesTaxInput?.value ?? '';
          if (raw === '') {
            return true;
          }
          const value = Number(raw);
          return Number.isFinite(value) && value >= 0 && value <= 100;
        },
      });
    }

    if (quantityRaw !== '' && (!Number.isFinite(quantityValue) || quantityValue <= 0)) {
      recordInvalid(quantityInput, __('Please enter a valid quantity.', 'vareon-calculator-suite-lite'), {
        allowEmpty: true,
        validator: () => {
          const raw = quantityInput?.value ?? '';
          if (raw === '') {
            return true;
          }
          const value = Number(raw);
          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;
    }

    let originalPrice = inputPrice;
    let finalPerItem = inputPrice;
    let discountAmount = 0;
    let extraDiscountAmount = 0;
    let discountPercent = 0;
    let priceAfterPrimary = 0;

    if (isReverse) {
      if (discountType === 'percentage') {
        const primaryFactor = 1 - (discountValue / 100);
        const extraFactor = extraDiscountEnabled ? (1 - (extraDiscountRate / 100)) : 1;
        const denominator = primaryFactor * extraFactor;
        if (denominator <= 0) {
          [discountValueInput, extraDiscountRateInput].filter(Boolean).forEach(input => {
            ValidationHelpers.markInvalid(input, { validator: discountValidator });
          });
          ValidationHelpers.showToast(container, __('Discount percentages must be less than 100% in reverse mode.', 'vareon-calculator-suite-lite'));
          return;
        }
        originalPrice = inputPrice / denominator;
        discountAmount = (originalPrice * discountValue) / 100;
        priceAfterPrimary = originalPrice - discountAmount;
        extraDiscountAmount = extraDiscountEnabled ? (priceAfterPrimary * extraDiscountRate) / 100 : 0;
        discountPercent = discountValue;
        finalPerItem = inputPrice;
      } else {
        if (extraDiscountEnabled) {
          const extraFactor = 1 - (extraDiscountRate / 100);
          if (extraFactor <= 0) {
            ValidationHelpers.markInvalid(extraDiscountRateInput, {
              allowEmpty: true,
              validator: () => {
                const raw = extraDiscountRateInput?.value ?? '';
                if (raw === '') {
                  return true;
                }
                const value = Number(raw);
                return Number.isFinite(value) && value >= 0 && value < 100;
              },
            });
            ValidationHelpers.showToast(container, __('Additional discount must be less than 100% in reverse mode.', 'vareon-calculator-suite-lite'));
            return;
          }
          originalPrice = (inputPrice / extraFactor) + discountValue;
        } else {
          originalPrice = inputPrice + discountValue;
        }
        discountAmount = discountValue;
        priceAfterPrimary = originalPrice - discountAmount;
        extraDiscountAmount = extraDiscountEnabled ? (priceAfterPrimary * extraDiscountRate) / 100 : 0;
        discountPercent = originalPrice > 0 ? (discountAmount / originalPrice) * 100 : 0;
        finalPerItem = inputPrice;
      }
    } else {
      if (discountType === 'percentage') {
        discountAmount = (inputPrice * discountValue) / 100;
        priceAfterPrimary = inputPrice - discountAmount;
        discountPercent = discountValue;
      } else {
        discountAmount = discountValue;
        priceAfterPrimary = inputPrice - discountAmount;
        discountPercent = inputPrice > 0 ? (discountAmount / inputPrice) * 100 : 0;
      }
      extraDiscountAmount = extraDiscountEnabled ? (priceAfterPrimary * extraDiscountRate) / 100 : 0;
      originalPrice = inputPrice;
      finalPerItem = priceAfterPrimary - extraDiscountAmount;
    }

    const totalPreTax = finalPerItem * quantityValue;
    const taxAmount = salesTaxRate > 0 ? (totalPreTax * salesTaxRate) / 100 : 0;
    const totalAtRegister = totalPreTax + taxAmount;
    const savingsAmount = (originalPrice - finalPerItem) * quantityValue;
    const savingsPercent = originalPrice > 0 ? ((originalPrice - finalPerItem) / originalPrice) * 100 : 0;

    const withGrouping = { useGrouping: true };
    const formattedFinalPerItem = formatCurrencyHtml(finalPerItem, withGrouping);
    const formattedOriginalPrice = formatCurrencyHtml(originalPrice, withGrouping);
    const formattedDiscountAmount = formatCurrencyHtml(discountAmount, withGrouping);
    const formattedExtraDiscountAmount = formatCurrencyHtml(extraDiscountAmount, withGrouping);
    const formattedSubtotal = formatCurrencyHtml(totalPreTax, withGrouping);
    const formattedTaxAmount = formatCurrencyHtml(taxAmount, withGrouping);
    const formattedTotalAtRegister = formatCurrencyHtml(totalAtRegister, withGrouping);
    const formattedSavingsAmount = formatCurrencyHtml(savingsAmount, withGrouping);
    const formattedSavingsPercent = formatNumber(savingsPercent, {
      decimals: percentDecimals,
      maxDecimals: percentDecimals,
      trimTrailingZeros: true,
      useGrouping: true,
    });
    const formattedDiscountPercent = formatNumber(discountPercent, {
      decimals: percentDecimals,
      maxDecimals: percentDecimals,
      trimTrailingZeros: true,
      useGrouping: true,
    });
    const formattedExtraDiscountRate = formatNumber(extraDiscountRate, {
      decimals: percentDecimals,
      maxDecimals: percentDecimals,
      trimTrailingZeros: true,
      useGrouping: true,
    });
    const formattedTaxRate = formatNumber(salesTaxRate, {
      decimals: percentDecimals,
      maxDecimals: percentDecimals,
      trimTrailingZeros: true,
      useGrouping: true,
    });
    const formattedQuantity = formatNumber(quantityValue, {
      decimals: 0,
      maxDecimals: 0,
      trimTrailingZeros: true,
      useGrouping: true,
    });
    const discountPercentLabel = discountType === 'percentage' ? `(${formattedDiscountPercent}%)` : '';
    const savingsPercentLabel = `${formattedSavingsPercent}%`;
    const discountLabelText = discountPercentLabel
      ? `${__('Discount', 'vareon-calculator-suite-lite')} ${discountPercentLabel}`
      : __('Discount', 'vareon-calculator-suite-lite');
    const extraDiscountLabelText = `${__('Additional Discount', 'vareon-calculator-suite-lite')} (${formattedExtraDiscountRate}%)`;
    const showExtraDiscountRow = extraDiscountEnabled && extraDiscountRate > 0;
    const showTotalHeadline = salesTaxRate > 0 || quantityValue > 1;
    const headlineValue = showTotalHeadline ? formattedTotalAtRegister : formattedFinalPerItem;
    const headlineLabel = showTotalHeadline
      ? __('Total at Register', 'vareon-calculator-suite-lite')
      : __('Final Price', 'vareon-calculator-suite-lite');
    const finalPriceLabel = showTotalHeadline
      ? __('Final Price (per item)', 'vareon-calculator-suite-lite')
      : __('Final Price', 'vareon-calculator-suite-lite');
    const taxRowLabel = `${__('Sales Tax', 'vareon-calculator-suite-lite')} (${formattedTaxRate}%)`;

    const perItemRows = [
      `<div class="vareoncalc-receipt-row">
          <span class="receipt-label">${__('Original Price', 'vareon-calculator-suite-lite')}</span>
          <span class="receipt-value">${formattedOriginalPrice}</span>
        </div>`,
      `<div class="vareoncalc-receipt-row">
          <span class="receipt-label">${discountLabelText}</span>
          <span class="receipt-value receipt-value--discount"><span class="receipt-sign" aria-hidden="true">\u2212</span>${formattedDiscountAmount}</span>
        </div>`
    ];

    if (showExtraDiscountRow) {
      perItemRows.push(
        `<div class="vareoncalc-receipt-row">
          <span class="receipt-label">${extraDiscountLabelText}</span>
          <span class="receipt-value receipt-value--discount"><span class="receipt-sign" aria-hidden="true">\u2212</span>${formattedExtraDiscountAmount}</span>
        </div>`
      );
    }

    perItemRows.push(
      `<div class="vareoncalc-receipt-row vareoncalc-receipt-row--final">
          <span class="receipt-label">${finalPriceLabel}</span>
          <span class="receipt-value">${formattedFinalPerItem}</span>
        </div>`
    );

    const cartRows = [];
    if (showTotalHeadline) {
      if (quantityValue > 1) {
        cartRows.push(
          `<div class="vareoncalc-receipt-row">
            <span class="receipt-label">${__('Quantity', 'vareon-calculator-suite-lite')}</span>
            <span class="receipt-value">${formattedQuantity}</span>
          </div>`
        );
      }

      cartRows.push(
        `<div class="vareoncalc-receipt-row">
          <span class="receipt-label">${__('Subtotal', 'vareon-calculator-suite-lite')}</span>
          <span class="receipt-value">${formattedSubtotal}</span>
        </div>`
      );

      if (salesTaxRate > 0) {
        cartRows.push(
          `<div class="vareoncalc-receipt-row">
            <span class="receipt-label">${taxRowLabel}</span>
            <span class="receipt-value">${formattedTaxAmount}</span>
          </div>`
        );
      }
    }

    let breakdownHtml = `<div class="vareoncalc-receipt-group">${perItemRows.join('')}</div>`;
    if (cartRows.length) {
      breakdownHtml += `<div class="vareoncalc-receipt-group">${cartRows.join('')}</div>`;
    }

    if (resultPanel) {
      resultPanel.className = 'vareoncalc-panel-result';
      resultPanel.innerHTML = `
        <div class="vareoncalc-receipt-headline vareoncalc-receipt-headline--discount">
          <div class="receipt-price">${headlineValue}</div>
          <div class="receipt-label">${headlineLabel}</div>
        </div>
        <div class="vareoncalc-receipt-breakdown">
          ${breakdownHtml}
        </div>
        <div class="vareoncalc-receipt-savings">
          <svg class="savings-icon" viewBox="0 0 24 24" width="24" height="24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M19 5c-1.5 0-2.8 1.4-3 2-3.5-1.4-11-.3-11 5 0 1.8 0 3 2 4.5V20h4v-2h3v2h4v-4c1-.5 1.7-1 2-2h2v-4h-2c0-1-.5-1.5-1-2"/><path d="M2 9.5c1 0 2 1 2 2.5"/><circle cx="15" cy="11" r="1" fill="currentColor" stroke="none"/><path d="M9 5l1-2 1.5 2"/></svg>
          <span class="savings-text">${__('You Save', 'vareon-calculator-suite-lite')} ${formattedSavingsAmount} (${savingsPercentLabel} ${__('off', 'vareon-calculator-suite-lite')})</span>
        </div>
      `;
    }

    showResultsStep();
  });

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