import { ValidationHelpers, InputAdornment, HelpTooltip, __ } from '@vareoncalc/calculator-base';
import { setupAutoCalc } from '../utils/behavior.js';
import { initCompactTwoStep } from '../utils/compact-two-step.js';

/**
 * Percentage Calculator
 * Calculate percentages with multiple modes
 * Compact two-step layout with Blackboard results panel
 */

export function mount(container) {
  const layout = (window.VAREONCALC_CFG && window.VAREONCALC_CFG.layout) || 'compact';
  const isWide = layout === 'wide';

  const modes = {
    'percent-of': __('What is X% of Y?', 'vareon-calculator-suite-lite'),
    'is-what-percent': __('X is what % of Y?', 'vareon-calculator-suite-lite'),
    'percent-change': __('% increase/decrease from X to Y', 'vareon-calculator-suite-lite'),
    'percent-increase': __('Increase/Decrease X by Y%', 'vareon-calculator-suite-lite'),
    'reverse-percent': __('Find original value (Reverse %)', 'vareon-calculator-suite-lite'),
    'find-whole': __('X is Y% of what?', 'vareon-calculator-suite-lite'),
    'ratio': __('Ratio A:B Calculator', 'vareon-calculator-suite-lite')
  };

  const configuredModes = (window.VAREONCALC_CFG && window.VAREONCALC_CFG.calculatorOptions &&
    window.VAREONCALC_CFG.calculatorOptions['percentage'] &&
    window.VAREONCALC_CFG.calculatorOptions['percentage'].enabled_modes) || null;

  const fallbackModes = ['percent-of', 'is-what-percent', 'percent-change', 'percent-increase', 'reverse-percent', 'find-whole'];
  const enabledModes = [];

  (configuredModes && configuredModes.length ? configuredModes : fallbackModes).forEach(mode => {
    if (modes[mode] && enabledModes.indexOf(mode) === -1) {
      enabledModes.push(mode);
    }
  });

  if (!enabledModes.length) {
    enabledModes.push('percent-of');
  }

  // Build mode options dynamically
  let modeOptions = '';
  enabledModes.forEach(mode => {
    if (modes[mode]) {
      modeOptions += `<option value="${mode}">${modes[mode]}</option>`;
    }
  });

  // Hide mode selector if only one mode enabled
  const showModeSelector = enabledModes.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="percentage-form">
            <div class="percentage-section vareoncalc-section">
              <div class="percentage-section__header vareoncalc-section__header">
                <div class="percentage-section__title vareoncalc-section__title">${__('Calculation type', 'vareon-calculator-suite-lite')}</div>
              </div>
              ${showModeSelector ? `
              <div class="percentage-field">
                <label for="calc-type">${HelpTooltip.create(
    __('Choose which percentage formula to solve. The variable fields below update based on this selection.', 'vareon-calculator-suite-lite'),
    __('I want to calculate...', 'vareon-calculator-suite-lite')
  )}</label>
                <select id="calc-type">
                  ${modeOptions}
                </select>
              </div>
              ` : `
              <div class="percentage-field percentage-field--static">
                <span class="percentage-field__label">${HelpTooltip.create(
    __('This calculator mode is preselected by your site settings.', 'vareon-calculator-suite-lite'),
    __('I want to calculate...', 'vareon-calculator-suite-lite')
  )}</span>
                <div class="percentage-static">${modes[enabledModes[0]]}</div>
                <input type="hidden" id="calc-type" value="${enabledModes[0]}">
              </div>
              `}
            </div>

            <div class="percentage-section vareoncalc-section">
              <div class="percentage-section__header vareoncalc-section__header">
                <div class="percentage-section__title vareoncalc-section__title">${__('Enter values', 'vareon-calculator-suite-lite')}</div>
              </div>
              <div class="vareoncalc-sentence-builder">
                <div class="percentage-field">
                  <label id="label-1" for="value-1">${__('Percentage', 'vareon-calculator-suite-lite')}</label>
                  <input type="number" id="value-1" data-suffix="%" placeholder="15" step="0.01">
                </div>
                <span class="vareoncalc-sentence-connector" id="connector-text">${__('% of', 'vareon-calculator-suite-lite')}</span>
                <div class="percentage-field">
                  <label id="label-2" for="value-2">${__('Value', 'vareon-calculator-suite-lite')}</label>
                  <input type="number" id="value-2" placeholder="100" step="0.01">
                </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-blackboard vareoncalc-blackboard--placeholder" id="result-panel">
            <div class="placeholder-icon">&#128221;</div>
            <div class="placeholder-text">${__('Enter values to see the answer and formula', '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>
  `;

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

  const calcTypeSelect = container.querySelector('#calc-type');
  const label1 = container.querySelector('#label-1');
  const label2 = container.querySelector('#label-2');
  const connectorText = container.querySelector('#connector-text');
  const value1Input = container.querySelector('#value-1');
  const value2Input = container.querySelector('#value-2');
  const btn = container.querySelector('#calc-btn');
  const resultPanel = container.querySelector('#result-panel');
  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 setInputSuffixRail = (input, suffix) => {
    if (!input) {
      return;
    }
    InputAdornment.setSuffix(input, suffix);
    const wrapper = input.closest('.vareoncalc-input-adorned');
    if (wrapper) {
      wrapper.classList.toggle('vareoncalc-input-adorned--suffix-rail', Boolean(suffix));
    }
  };

  const setVariableTooltipLabel = (labelEl, labelText, tooltipText) => {
    if (!labelEl) {
      return;
    }
    labelEl.textContent = '';

    const tooltip = document.createElement('span');
    tooltip.className = 'vareoncalc-tooltip';
    tooltip.setAttribute('data-tooltip', tooltipText);
    tooltip.setAttribute('data-tooltip-trigger', 'text');
    tooltip.setAttribute('tabindex', '0');
    tooltip.setAttribute('role', 'note');
    tooltip.setAttribute('aria-label', `${labelText}: ${tooltipText}`);
    tooltip.textContent = labelText;
    labelEl.appendChild(tooltip);
  };

  // Reset result panel to placeholder state
  function resetResultPanel() {
    if (resultPanel) {
      resultPanel.className = 'vareoncalc-panel-result vareoncalc-blackboard vareoncalc-blackboard--placeholder';
      resultPanel.innerHTML = `
        <div class="placeholder-icon">&#128221;</div>
        <div class="placeholder-text">${__('Enter values to see the answer and formula', 'vareon-calculator-suite-lite')}</div>
      `;
    }
    refreshTwoStepLayout();
  }

  // Update labels, suffixes, and connector based on calculation type
  function updateLabels() {
    const calcType = calcTypeSelect.value;

    if (calcType === 'percent-of') {
      setVariableTooltipLabel(
        label1,
        __('Percentage', 'vareon-calculator-suite-lite'),
        __('Percent rate to apply to the base value (for example, 15 means 15%).', 'vareon-calculator-suite-lite')
      );
      setVariableTooltipLabel(
        label2,
        __('Value', 'vareon-calculator-suite-lite'),
        __('Base value you are taking the percentage of.', 'vareon-calculator-suite-lite')
      );
      setInputSuffixRail(value1Input, '%');
      setInputSuffixRail(value2Input, '');
      if (connectorText) connectorText.textContent = __('% of', 'vareon-calculator-suite-lite');
      value1Input.placeholder = '15';
      value1Input.setAttribute('aria-label', __('Percentage value', 'vareon-calculator-suite-lite'));
      value2Input.placeholder = '100';
      value2Input.setAttribute('aria-label', __('Base value', 'vareon-calculator-suite-lite'));
    } else if (calcType === 'is-what-percent') {
      setVariableTooltipLabel(
        label1,
        __('Part Value', 'vareon-calculator-suite-lite'),
        __('Known part amount that belongs to the total.', 'vareon-calculator-suite-lite')
      );
      setVariableTooltipLabel(
        label2,
        __('Total Value', 'vareon-calculator-suite-lite'),
        __('Whole amount used as the denominator when finding the percent.', 'vareon-calculator-suite-lite')
      );
      setInputSuffixRail(value1Input, '');
      setInputSuffixRail(value2Input, '');
      if (connectorText) connectorText.textContent = __('is what % of', 'vareon-calculator-suite-lite');
      value1Input.placeholder = '25';
      value1Input.setAttribute('aria-label', __('Part value', 'vareon-calculator-suite-lite'));
      value2Input.placeholder = '200';
      value2Input.setAttribute('aria-label', __('Total value', 'vareon-calculator-suite-lite'));
    } else if (calcType === 'percent-change') {
      setVariableTooltipLabel(
        label1,
        __('Original Value', 'vareon-calculator-suite-lite'),
        __('Starting value before the change.', 'vareon-calculator-suite-lite')
      );
      setVariableTooltipLabel(
        label2,
        __('New Value', 'vareon-calculator-suite-lite'),
        __('Ending value after the change.', 'vareon-calculator-suite-lite')
      );
      setInputSuffixRail(value1Input, '');
      setInputSuffixRail(value2Input, '');
      if (connectorText) connectorText.textContent = __('\u2192', 'vareon-calculator-suite-lite');
      value1Input.placeholder = '100';
      value1Input.setAttribute('aria-label', __('Original value', 'vareon-calculator-suite-lite'));
      value2Input.placeholder = '120';
      value2Input.setAttribute('aria-label', __('New value', 'vareon-calculator-suite-lite'));
    } else if (calcType === 'percent-increase') {
      setVariableTooltipLabel(
        label1,
        __('Original Value', 'vareon-calculator-suite-lite'),
        __('Starting value before applying an increase or decrease.', 'vareon-calculator-suite-lite')
      );
      setVariableTooltipLabel(
        label2,
        __('Change', 'vareon-calculator-suite-lite'),
        __('Signed percent change to apply to the original value.', 'vareon-calculator-suite-lite')
      );
      setInputSuffixRail(value1Input, '');
      setInputSuffixRail(value2Input, '%');
      if (connectorText) connectorText.textContent = __('\u00B1', 'vareon-calculator-suite-lite');
      value1Input.placeholder = '100';
      value1Input.setAttribute('aria-label', __('Original value', 'vareon-calculator-suite-lite'));
      value2Input.placeholder = '10';
      value2Input.setAttribute('aria-label', __('Percentage', 'vareon-calculator-suite-lite'));
    } else if (calcType === 'reverse-percent') {
      setVariableTooltipLabel(
        label1,
        __('Final Value', 'vareon-calculator-suite-lite'),
        __('Amount after a percentage change has already been applied.', 'vareon-calculator-suite-lite')
      );
      setVariableTooltipLabel(
        label2,
        __('Percent Included', 'vareon-calculator-suite-lite'),
        __('Percent change already included in the final value.', 'vareon-calculator-suite-lite')
      );
      setInputSuffixRail(value1Input, '');
      setInputSuffixRail(value2Input, '%');
      if (connectorText) connectorText.textContent = __('includes', 'vareon-calculator-suite-lite');
      value1Input.placeholder = '120';
      value1Input.setAttribute('aria-label', __('Final value', 'vareon-calculator-suite-lite'));
      value2Input.placeholder = '20';
      value2Input.setAttribute('aria-label', __('Included percentage', 'vareon-calculator-suite-lite'));
    } else if (calcType === 'find-whole') {
      setVariableTooltipLabel(
        label1,
        __('Part Value', 'vareon-calculator-suite-lite'),
        __('Known part of the whole amount.', 'vareon-calculator-suite-lite')
      );
      setVariableTooltipLabel(
        label2,
        __('Percentage', 'vareon-calculator-suite-lite'),
        __('Percent that the part represents of the total whole.', 'vareon-calculator-suite-lite')
      );
      setInputSuffixRail(value1Input, '');
      setInputSuffixRail(value2Input, '%');
      if (connectorText) connectorText.textContent = __('is', 'vareon-calculator-suite-lite');
      value1Input.placeholder = '50';
      value1Input.setAttribute('aria-label', __('Part value', 'vareon-calculator-suite-lite'));
      value2Input.placeholder = '20';
      value2Input.setAttribute('aria-label', __('Percentage of total', 'vareon-calculator-suite-lite'));
    } else if (calcType === 'ratio') {
      setVariableTooltipLabel(
        label1,
        __('Value A', 'vareon-calculator-suite-lite'),
        __('First quantity in the ratio.', 'vareon-calculator-suite-lite')
      );
      setVariableTooltipLabel(
        label2,
        __('Value B', 'vareon-calculator-suite-lite'),
        __('Second quantity in the ratio.', 'vareon-calculator-suite-lite')
      );
      setInputSuffixRail(value1Input, '');
      setInputSuffixRail(value2Input, '');
      if (connectorText) connectorText.textContent = ':';
      value1Input.placeholder = '15';
      value1Input.setAttribute('aria-label', __('First ratio value', 'vareon-calculator-suite-lite'));
      value2Input.placeholder = '25';
      value2Input.setAttribute('aria-label', __('Second ratio value', 'vareon-calculator-suite-lite'));
    }

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

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

  if (calcTypeSelect && calcTypeSelect.tagName === 'SELECT') {
    calcTypeSelect.addEventListener('change', () => {
      updateLabels();
      handleInputChange();
    });
  }

  [value1Input, value2Input].forEach(input => {
    if (!input) return;
    input.addEventListener('input', handleInputChange);
    input.addEventListener('change', handleInputChange);
  });

  // Initialize labels on page load
  updateLabels();

  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 blockStep = (message, input = null) => {
      if (input) {
        ValidationHelpers.markInvalid(input);
      }
      ValidationHelpers.showToast(container, message);
      if (event) {
        event.preventDefault();
        event.stopImmediatePropagation();
      }
    };

    const calcType = calcTypeSelect.value;
    const value1 = parseFloat(value1Input.value);
    const value2 = parseFloat(value2Input.value);

    // Validation
    if (isNaN(value1) || value1Input.value === '') {
      recordInvalid(value1Input, __('Please enter the first value.', 'vareon-calculator-suite-lite'));
    }

    if (isNaN(value2) || value2Input.value === '') {
      recordInvalid(value2Input, __('Please enter the second value.', 'vareon-calculator-suite-lite'));
    }

    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 resultValue, explanation, formula, formulaExplanation, displayValue;

    if (calcType === 'percent-of') {
      // What is X% of Y?
      resultValue = (value1 / 100) * value2;
      displayValue = resultValue.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
      formula = `(${value1} &times; ${value2}) &divide; 100 = ${resultValue.toFixed(2)}`;
      explanation = `${value1}% ${__('of', 'vareon-calculator-suite-lite')} ${value2} ${__('is', 'vareon-calculator-suite-lite')} ${displayValue}`;
      formulaExplanation = __('Multiply the percentage by the value and divide by 100', 'vareon-calculator-suite-lite');

      renderBlackboard({
        headline: displayValue,
        label: explanation,
        formula: formula,
        formulaNote: formulaExplanation,
        icon: '='
      });
      return;

    } else if (calcType === 'is-what-percent') {
      // X is what % of Y?
      if (value2 === 0) {
        ValidationHelpers.markInvalid(value2Input, {
          validator: () => {
            const current = parseFloat(value2Input.value);
            return Number.isFinite(current) && current > 0;
          },
        });
        ValidationHelpers.showToast(container, __('Cannot divide by zero. Total value must be greater than 0.', 'vareon-calculator-suite-lite'));
        if (event) {
          event.preventDefault();
          event.stopImmediatePropagation();
        }
        return;
      }
      resultValue = (value1 / value2) * 100;
      displayValue = resultValue.toFixed(2) + '%';
      formula = `(${value1} &divide; ${value2}) &times; 100 = ${resultValue.toFixed(2)}%`;
      explanation = `${value1} ${__('is', 'vareon-calculator-suite-lite')} ${resultValue.toFixed(2)}% ${__('of', 'vareon-calculator-suite-lite')} ${value2}`;
      formulaExplanation = __('Divide the part by the total and multiply by 100', 'vareon-calculator-suite-lite');

      renderBlackboard({
        headline: displayValue,
        label: explanation,
        formula: formula,
        formulaNote: formulaExplanation,
        icon: '%'
      });
      return;

    } else if (calcType === 'percent-change') {
      // % increase/decrease from X to Y
      if (value1 === 0) {
        if (value2 === 0) {
          renderBlackboard({
            headline: __('No Change (0%)', 'vareon-calculator-suite-lite'),
            label: __('Start and end values are both zero.', 'vareon-calculator-suite-lite'),
            formula: __('0 \u2192 0 = 0%', 'vareon-calculator-suite-lite'),
            formulaNote: __('No change occurs when both values are zero.', 'vareon-calculator-suite-lite'),
            icon: '0'
          });
          return;
        }

        const infiniteLabel = value2 > 0
          ? __('Infinite Increase', 'vareon-calculator-suite-lite')
          : __('Infinite Decrease', 'vareon-calculator-suite-lite');
        const changeColor = value2 > 0 ? 'positive' : 'negative';

        renderBlackboard({
          headline: infiniteLabel,
          headlineClass: changeColor,
          label: __('Change from zero is undefined.', 'vareon-calculator-suite-lite'),
          formula: `(${value2} - 0) &divide; 0 = ${__('Infinite', 'vareon-calculator-suite-lite')}`,
          formulaNote: __('Percentage change from zero is not finite.', 'vareon-calculator-suite-lite'),
          icon: value2 > 0 ? '&#8593;' : '&#8595;',
          breakdown: [
            { label: __('Original Value', 'vareon-calculator-suite-lite'), value: '0' },
            { label: __('New Value', 'vareon-calculator-suite-lite'), value: value2.toLocaleString(), highlight: changeColor }
          ]
        });
        return;
      }
      resultValue = ((value2 - value1) / Math.abs(value1)) * 100;
      const changeType = resultValue >= 0 ? __('increase', 'vareon-calculator-suite-lite') : __('decrease', 'vareon-calculator-suite-lite');
      const changeColor = resultValue >= 0 ? 'positive' : 'negative';
      displayValue = (resultValue >= 0 ? '+' : '') + resultValue.toFixed(2) + '%';
      formula = `((${value2} - ${value1}) &divide; ${Math.abs(value1)}) &times; 100 = ${resultValue.toFixed(2)}%`;
      explanation = `${Math.abs(resultValue).toFixed(2)}% ${changeType} ${__('from', 'vareon-calculator-suite-lite')} ${value1} ${__('to', 'vareon-calculator-suite-lite')} ${value2}`;
      formulaExplanation = __('Subtract original from new, divide by original, multiply by 100', 'vareon-calculator-suite-lite');

      renderBlackboard({
        headline: displayValue,
        headlineClass: changeColor,
        label: changeType.charAt(0).toUpperCase() + changeType.slice(1),
        formula: formula,
        formulaNote: formulaExplanation,
        icon: resultValue >= 0 ? '&#8593;' : '&#8595;',
        breakdown: [
          { label: __('Original Value', 'vareon-calculator-suite-lite'), value: value1.toLocaleString() },
          { label: __('New Value', 'vareon-calculator-suite-lite'), value: value2.toLocaleString() },
          { label: __('Difference', 'vareon-calculator-suite-lite'), value: (resultValue >= 0 ? '+' : '') + (value2 - value1).toLocaleString(), highlight: changeColor }
        ]
      });
      return;

    } else if (calcType === 'percent-increase') {
      const per = Math.abs(value2);
      const changeAmount = value1 * (per / 100);
      const increasedValue = value1 + changeAmount;
      const decreasedValue = value1 - changeAmount;
      const changeStr = changeAmount.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });

      formula = `${value1} &plusmn; (${value1} &times; ${per}/100) = &plusmn;${changeAmount.toFixed(2)}`;
      formulaExplanation = `${value1} ${__('increased and decreased by', 'vareon-calculator-suite-lite')} ${per}%`;

      renderBlackboard({
        headline: '&plusmn;' + changeStr,
        label: __('Change Amount', 'vareon-calculator-suite-lite'),
        formula: formula,
        formulaNote: formulaExplanation,
        icon: '&plusmn;',
        breakdown: [
          { label: __('Original Value', 'vareon-calculator-suite-lite'), value: value1.toLocaleString() },
          { label: `+${per}% ${__('Increase', 'vareon-calculator-suite-lite')}`, value: increasedValue.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }), highlight: 'positive', bold: true },
          { label: `-${per}% ${__('Decrease', 'vareon-calculator-suite-lite')}`, value: decreasedValue.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }), highlight: 'negative', bold: true }
        ]
      });
      return;

    } else if (calcType === 'reverse-percent') {
      const percentDecimal = value2 / 100;
      const divisor = 1 + percentDecimal;
      if (divisor === 0) {
        blockStep(__('Percentage results in division by zero.', 'vareon-calculator-suite-lite'), value2Input);
        return;
      }

      const originalValue = value1 / divisor;
      const includedAmount = value1 - originalValue;
      displayValue = originalValue.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
      formula = `${value1} &divide; (1 + ${percentDecimal}) = ${originalValue.toFixed(2)}`;
      formulaExplanation = __('Divide the final amount by 1 + the percentage.', 'vareon-calculator-suite-lite');

      renderBlackboard({
        headline: displayValue,
        label: __('Original Value', 'vareon-calculator-suite-lite'),
        formula: formula,
        formulaNote: formulaExplanation,
        icon: '&#8617;',
        breakdown: [
          { label: __('Final Value', 'vareon-calculator-suite-lite'), value: value1.toLocaleString() },
          { label: __('Included Change', 'vareon-calculator-suite-lite'), value: includedAmount.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 }) },
          { label: __('Original Value', 'vareon-calculator-suite-lite'), value: displayValue, bold: true }
        ]
      });
      return;

    } else if (calcType === 'find-whole') {
      if (value2 === 0) {
        blockStep(__('Percentage must be greater than 0.', 'vareon-calculator-suite-lite'), value2Input);
        return;
      }
      resultValue = value1 / (value2 / 100);
      displayValue = resultValue.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
      formula = `${value1} &divide; (${value2} &divide; 100) = ${resultValue.toFixed(2)}`;
      formulaExplanation = __('Divide the part by the percentage (as a decimal).', 'vareon-calculator-suite-lite');

      renderBlackboard({
        headline: displayValue,
        label: __('The Total Amount', 'vareon-calculator-suite-lite'),
        formula: formula,
        formulaNote: formulaExplanation,
        icon: '&sum;',
        breakdown: [
          { label: __('Part Value', 'vareon-calculator-suite-lite'), value: value1.toLocaleString() },
          { label: __('Percentage', 'vareon-calculator-suite-lite'), value: value2.toLocaleString() + '%' },
          { label: __('Whole Value', 'vareon-calculator-suite-lite'), value: displayValue, bold: true }
        ]
      });
      return;

    } else if (calcType === 'ratio') {
      // Ratio calculator - find GCD and simplify
      function gcd(a, b) {
        a = Math.abs(Math.round(a));
        b = Math.abs(Math.round(b));
        while (b !== 0) {
          const temp = b;
          b = a % b;
          a = temp;
        }
        return a;
      }

      const divisor = gcd(value1, value2);
      const simplifiedA = Math.round(value1) / divisor;
      const simplifiedB = Math.round(value2) / divisor;
      const total = value1 + value2;
      const percentA = (value1 / total) * 100;
      const percentB = (value2 / total) * 100;
      const decimalRatio = value1 / value2;

      displayValue = `${simplifiedA}:${simplifiedB}`;

      renderBlackboardRatio({
        simplified: displayValue,
        original: `${value1}:${value2}`,
        decimal: decimalRatio.toFixed(4),
        percentA: percentA.toFixed(1),
        percentB: percentB.toFixed(1),
        total: total.toLocaleString(),
        simplifiedA,
        simplifiedB
      });
      return;
    }
  });

  // Render the "Blackboard" result panel
  function renderBlackboard(data) {
    if (!resultPanel) return;

    resultPanel.className = 'vareoncalc-panel-result vareoncalc-blackboard';

    let breakdownHtml = '';
    if (data.breakdown && data.breakdown.length) {
      breakdownHtml = `
        <div class="blackboard-breakdown">
          ${data.breakdown.map(item => `
            <div class="breakdown-row${item.bold ? ' breakdown-row--bold' : ''}">
              <span class="breakdown-label">${item.label}</span>
              <span class="breakdown-value${item.highlight ? ' breakdown-value--' + item.highlight : ''}">${item.value}</span>
            </div>
          `).join('')}
        </div>
      `;
    }

    resultPanel.innerHTML = `
      <div class="blackboard-headline">
        <div class="blackboard-answer${data.headlineClass ? ' blackboard-answer--' + data.headlineClass : ''}">${data.headline}</div>
        <div class="blackboard-label">${data.label}</div>
      </div>
      ${breakdownHtml}
      <div class="blackboard-formula-card">
        <div class="formula-header">
          <span class="formula-icon">${data.icon || "&#128221;"}</span>
          <span class="formula-title">${__('The Math', 'vareon-calculator-suite-lite')}</span>
        </div>
        <code class="formula-expression">${data.formula}</code>
        <div class="formula-explanation">${data.formulaNote}</div>
      </div>
    `;
    showResultsStep();
  }

  // Render special ratio blackboard
  function renderBlackboardRatio(data) {
    if (!resultPanel) return;

    resultPanel.className = 'vareoncalc-panel-result vareoncalc-blackboard';

    resultPanel.innerHTML = `
      <div class="blackboard-headline">
        <div class="blackboard-answer blackboard-answer--ratio">${data.simplified}</div>
        <div class="blackboard-label">${__('Simplified Ratio', 'vareon-calculator-suite-lite')}</div>
      </div>
      <div class="blackboard-breakdown">
        <div class="breakdown-row">
          <span class="breakdown-label">${__('Original Ratio', 'vareon-calculator-suite-lite')}</span>
          <span class="breakdown-value">${data.original}</span>
        </div>
        <div class="breakdown-row">
          <span class="breakdown-label">${__('Decimal (A/B)', 'vareon-calculator-suite-lite')}</span>
          <span class="breakdown-value">${data.decimal}</span>
        </div>
      </div>
      <div class="blackboard-percentages">
        <div class="percentage-header">${__('Part-to-Whole', 'vareon-calculator-suite-lite')}</div>
        <div class="percentage-bars" role="img" aria-label="${__('Part-to-whole bars for A and B values', 'vareon-calculator-suite-lite')}">
          <div class="percentage-bar">
            <div class="bar-label">${__('A', 'vareon-calculator-suite-lite')}</div>
            <div class="bar-track">
              <div class="bar-fill bar-fill--a" style="width: ${data.percentA}%"></div>
            </div>
            <div class="bar-value">${data.percentA}%</div>
          </div>
          <div class="percentage-bar">
            <div class="bar-label">${__('B', 'vareon-calculator-suite-lite')}</div>
            <div class="bar-track">
              <div class="bar-fill bar-fill--b" style="width: ${data.percentB}%"></div>
            </div>
            <div class="bar-value">${data.percentB}%</div>
          </div>
        </div>
        <div class="percentage-total">
          <span>${__('Combined Total', 'vareon-calculator-suite-lite')}</span>
          <span class="total-value">${data.total}</span>
        </div>
      </div>
      <div class="blackboard-tip">
        <span class="tip-icon">&#128161;</span>
        <span class="tip-text">${data.simplifiedA}:${data.simplifiedB} ${__('means for every', 'vareon-calculator-suite-lite')} ${data.simplifiedA} ${__('of A, there are', 'vareon-calculator-suite-lite')} ${data.simplifiedB} ${__('of B', 'vareon-calculator-suite-lite')}</span>
      </div>
    `;
    showResultsStep();
  }

  // Validation function for auto-calc
  const validateAll = () => {
    const v1 = parseFloat(value1Input.value);
    const v2 = parseFloat(value2Input.value);
    const calcType = calcTypeSelect.value;

    if (!value1Input.value || isNaN(v1)) return false;
    if (!value2Input.value || isNaN(v2)) return false;
    if (calcType === 'is-what-percent' && v2 === 0) return false;
    if (calcType === 'find-whole' && v2 === 0) return false;
    if (calcType === 'reverse-percent' && (1 + (v2 / 100)) === 0) return false;

    return true;
  };
  // Setup auto-calculation (respects accessibility setting)
  setupAutoCalc(container, btn, [value1Input, value2Input, calcTypeSelect], validateAll);

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