import { ValidationHelpers, InputAdornment, HelpTooltip, __, sprintf } from '@vareoncalc/calculator-base';
import { initCompactTwoStep } from '../utils/compact-two-step.js';
import { 
  shouldShowMeasurementToggle, 
  getPreferredMeasurementMode,
  attachMeasurementToggleListener,
  cmToFeetInches,
  feetInchesToCm,
  normalizeFeetInches
} from '../utils/measurement.js';
import { applyThemedPanels } from '../utils/theme.js';

/**
 * BMI Calculator - "Health Vitals Dashboard"
 * 
 * Two-panel layout:
 * - Left Panel: "The Check-Up" (inputs)
 *   - Full-width unit toggle (Metric/Imperial)
 *   - Vitals Grid (Height + Weight side-by-side)
 * - Right Panel: "The Diagnosis" (results)
 *   - BMI Score + Category Badge
 *   - Color Spectrum Bar with position marker
 *   - Ideal Weight Range card with actionable advice
 */
export function mount(root) {
  let currentMode = getPreferredMeasurementMode('metric');
  const measurementToggleId = `bmi-unit-toggle-${Math.random().toString(36).slice(2, 9)}`;
  let twoStepInstance = null;
  const hostRoot = root.closest('.vareoncalc-root') || root;

  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 forceResultsStepFallback = () => {
    const twoStepRoot = root.querySelector('.vareoncalc-two-step');
    if (!twoStepRoot) {
      return;
    }
    const inputsStep = twoStepRoot.querySelector('[data-two-step-step="inputs"]');
    const resultsStep = twoStepRoot.querySelector('[data-two-step-step="results"]');
    if (inputsStep) {
      inputsStep.classList.remove('vareoncalc-two-step__step--active');
      inputsStep.setAttribute('aria-hidden', 'false');
    }
    if (resultsStep) {
      resultsStep.classList.add('vareoncalc-two-step__step--active');
      resultsStep.setAttribute('aria-hidden', 'false');
    }
    twoStepRoot.dataset.step = 'results';
    twoStepRoot.dataset.drawerOpen = 'false';
  };

  const showResultsStep = () => {
    let stepped = false;
    forEachTwoStepInstance((instance) => {
      try {
        if (typeof instance.setStep === 'function') {
          instance.setStep('results');
          stepped = true;
        }
        if (typeof instance.setDrawerOpen === 'function') {
          instance.setDrawerOpen(false);
        }
        if (typeof instance.refreshLayout === 'function') {
          instance.refreshLayout();
        }
      } catch (error) {
        console.error('BMI two-step results transition failed', error);
      }
    });
    if (!stepped) {
      forceResultsStepFallback();
    }
  };

  const refreshTwoStepLayout = () => {
    forEachTwoStepInstance((instance) => {
      if (typeof instance.refreshLayout === 'function') {
        instance.refreshLayout();
      }
    });
  };
  hostRoot._vareoncalcRefreshLayout = refreshTwoStepLayout;

  const 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="bmi-unit-toggle">
        <div class="vareoncalc-toggle vareoncalc-measurement-toggle bmi-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 bmi-icon-toggle__btn${metricActive}" data-mode="metric" aria-pressed="${isMetric}" title="${__( 'Metric (centimeters and kilograms)', 'vareon-calculator-suite-lite' )}">cm/kg</button>
            <button type="button" class="vareoncalc-toggle__option vareoncalc-measurement-toggle__btn bmi-icon-toggle__btn${imperialActive}" data-mode="imperial" aria-pressed="${!isMetric}" title="${__( 'Imperial (feet and pounds)', 'vareon-calculator-suite-lite' )}">ft/lb</button>
          </div>
        </div>
      </div>
    `;
  };

  const canProceedForInputs = (mode, containerEl) => {
    const isMetricMode = mode === 'metric';
    const weightMax = isMetricMode ? 500 : 1100;
    const weightInput = containerEl.querySelector('#w');
    const weightValue = parseFloat(weightInput?.value);
    if (!Number.isFinite(weightValue) || weightValue <= 0 || weightValue > weightMax) {
      return false;
    }
    if (isMetricMode) {
      const hCmInput = containerEl.querySelector('#h-cm');
      const heightValue = parseFloat(hCmInput?.value);
      if (!Number.isFinite(heightValue) || heightValue <= 0 || heightValue > 300) {
        return false;
      }
      return true;
    }
    const hFtInput = containerEl.querySelector('#h-ft');
    const hInInput = containerEl.querySelector('#h-in');
    const ftVal = parseFloat(hFtInput?.value) || 0;
    const inVal = parseFloat(hInInput?.value) || 0;
    if (ftVal === 0 && inVal === 0) {
      return false;
    }
    if (ftVal < 0 || ftVal > 8) {
      return false;
    }
    if (inVal < 0 || inVal >= 12) {
      return false;
    }
    const heightCm = feetInchesToCm(ftVal, inVal);
    if (heightCm < 30 || heightCm > 275) {
      return false;
    }
    return true;
  };
  function render() {
    destroyTwoStepInstance();
    const isMetric = currentMode === 'metric';
    const weightUnit = isMetric ? __( 'kg', 'vareon-calculator-suite-lite' ) : __( 'lbs', 'vareon-calculator-suite-lite' );
    const weightLabel = __( 'Weight', 'vareon-calculator-suite-lite' );
    const weightMax = isMetric ? 500 : 1100;
    const weightPlaceholder = isMetric ? '70' : '154';
    
    // Compact segmented control for unit toggle (mirrors the km/mi toggle styling).
    const toggleHTML = shouldShowMeasurementToggle() 
      ? getUnitSegmentedControlHTML()
      : '';
    
    // Height inputs based on mode
    const heightInputHTML = isMetric
      ? `
        <div class="vareoncalc-field">
          <label for="h-cm">${__( 'Height', 'vareon-calculator-suite-lite' )}</label>
          <input type="number" step="0.1" id="h-cm" data-suffix="${__( 'cm', 'vareon-calculator-suite-lite' )}" inputmode="decimal" min="1" max="300" placeholder="175">
        </div>
      `
      : `
        <div class="bmi-height-imperial">
          <label>${__( 'Height', 'vareon-calculator-suite-lite' )}</label>
          <div class="bmi-height-imperial__inputs">
            <div class="vareoncalc-field vareoncalc-field--compact">
              <input type="number" step="1" id="h-ft" data-suffix="${__( 'ft', 'vareon-calculator-suite-lite' )}" data-vareoncalc-mobile-label-shift="off" inputmode="numeric" min="0" max="8" placeholder="5" aria-label="${__( 'Height (ft)', 'vareon-calculator-suite-lite' )}">
            </div>
            <div class="vareoncalc-field vareoncalc-field--compact">
              <input type="number" step="0.1" id="h-in" data-suffix="${__( 'in', 'vareon-calculator-suite-lite' )}" data-vareoncalc-mobile-label-shift="off" inputmode="decimal" min="0" placeholder="11" aria-label="${__( 'Height (in)', 'vareon-calculator-suite-lite' )}">
            </div>
          </div>
        </div>
      `;
    
    root.innerHTML = `
      <div class="vareoncalc-two-step vareoncalc-bmi-dashboard" 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="vareoncalc-panel-input bmi-checkup">
              <!-- Vitals Grid -->
              <div class="bmi-vitals-section vareoncalc-section">
                <div class="bmi-vitals-section__header vareoncalc-section__header">
                  <div class="bmi-section-title vareoncalc-section__title">${__( 'Your Vitals', 'vareon-calculator-suite-lite' )}</div>
                  ${toggleHTML}
                </div>
                <div class="bmi-vitals-grid">
                  ${heightInputHTML}
                  <div class="vareoncalc-field">
                    <label for="w">${weightLabel}</label>
                    <input type="number" step="0.1" id="w" data-suffix="${weightUnit}" inputmode="decimal" min="1" max="${weightMax}" placeholder="${weightPlaceholder}">
                  </div>
                </div>
              </div>
              
              <button type="button" class="vareoncalc-btn" id="go" data-vareoncalc-primary="true" data-two-step-next>${__( 'Calculate BMI', 'vareon-calculator-suite-lite' )}</button>
            </div>
          </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 bmi-diagnosis bmi-diagnosis--placeholder" id="bmi-result">
              <div class="placeholder-icon">&#9878;</div>
              <div class="placeholder-text">${__( 'Enter your height and weight to see your health assessment', '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-out" id="out" style="display:none;"></div>
    `;
    
    InputAdornment.apply(root);
    HelpTooltip.apply(root);
    applyThemedPanels(root);
    
    const wInput = root.querySelector('#w');
    const hCmInput = root.querySelector('#h-cm');
    const hFtInput = root.querySelector('#h-ft');
    const hInInput = root.querySelector('#h-in');
    [wInput, hCmInput, hFtInput, hInInput].forEach((input) => {
      input?.closest('.vareoncalc-input-adorned')?.classList.add('vareoncalc-input-adorned--suffix-rail');
    });
    const button = root.querySelector('#go');
    const resultPanel = root.querySelector('#bmi-result');
    const canProceed = () => canProceedForInputs(currentMode, root);

    // Attach toggle listener if toggle exists
    if (shouldShowMeasurementToggle()) {
      attachMeasurementToggleListener(root, measurementToggleId, (newMode) => {
        // Capture current height in cm before re-render
        let oldHeightCm = 0;
        if (currentMode === 'metric') {
          const cmInput = root.querySelector('#h-cm');
          oldHeightCm = parseFloat(cmInput?.value) || 0;
        } else {
          const ftInput = root.querySelector('#h-ft');
          const inInput = root.querySelector('#h-in');
          const ft = parseFloat(ftInput?.value) || 0;
          const inc = parseFloat(inInput?.value) || 0;
          oldHeightCm = feetInchesToCm(ft, inc);
        }
        
        const oldWeight = parseFloat(wInput.value);
        
        currentMode = newMode;
        render();
        
        // Convert and restore height
        if (oldHeightCm > 0) {
          if (newMode === 'metric') {
            const newCmInput = root.querySelector('#h-cm');
            newCmInput.value = oldHeightCm.toFixed(1);
          } else {
            const { feet, inches } = cmToFeetInches(oldHeightCm);
            const newFtInput = root.querySelector('#h-ft');
            const newInInput = root.querySelector('#h-in');
            newFtInput.value = feet;
            newInInput.value = inches;
          }
        }
        
        // Convert and restore weight
        if (!isNaN(oldWeight) && oldWeight > 0) {
          const newWInput = root.querySelector('#w');
          if (newMode === 'metric') {
            // lbs to kg
            newWInput.value = (oldWeight * 0.45359237).toFixed(1);
          } else {
            // kg to lbs
            newWInput.value = (oldWeight / 0.45359237).toFixed(1);
          }
        }

        const rootNode = root.closest('.vareoncalc-root');
        if (
          rootNode &&
          typeof window !== 'undefined' &&
          typeof window.vareoncalcRefreshAutoCalc === 'function'
        ) {
          window.vareoncalcRefreshAutoCalc(rootNode);
        }
      });
    }

    // Real-time validation helper
    const validateInput = (input, min, max, name) => {
      const value = input.value;
      if (!value) {
        ValidationHelpers.clearError(input);
        return false;
      }
      
      const validation = ValidationHelpers.validateNumber(value, min, max, name);
      if (!validation.valid) {
        ValidationHelpers.showError(input, validation.message);
        return false;
      } else {
        ValidationHelpers.clearError(input);
        return true;
      }
    };

    // Attach real-time validation based on mode
    if (isMetric) {
      hCmInput.addEventListener('input', () => {
        validateInput(hCmInput, 0, 300, __( 'Height', 'vareon-calculator-suite-lite' ));
      });
    } else {
      hFtInput.addEventListener('input', () => {
        validateInput(hFtInput, 0, 8, __( 'Feet', 'vareon-calculator-suite-lite' ));
      });
      hInInput.addEventListener('input', () => {
        const ft = parseFloat(hFtInput.value) || 0;
        const inc = parseFloat(hInInput.value) || 0;
        // Auto-rollover: if inches >= 12, normalize into feet
        if (inc >= 12) {
          const { feet: newFt, inches: newIn } = normalizeFeetInches(ft, inc);
          hFtInput.value = newFt;
          hInInput.value = newIn;
          validateInput(hFtInput, 0, 8, __( 'Feet', 'vareon-calculator-suite-lite' ));
          ValidationHelpers.clearError(hInInput);
        } else if (inc < 0) {
          ValidationHelpers.showError(hInInput, __( 'Inches cannot be negative.', 'vareon-calculator-suite-lite' ));
        } else {
          ValidationHelpers.clearError(hInInput);
        }
      });
    }

    wInput.addEventListener('input', () => {
      validateInput(wInput, 0, weightMax, __( 'Weight', 'vareon-calculator-suite-lite' ));
    });

    button.addEventListener('click', () => {
      ValidationHelpers.clearAllErrors(root);

      const invalidInputs = [];
      const messages = [];
      const recordInvalid = (input, message, options = {}) => {
        if (!input) {
          return;
        }
        ValidationHelpers.markInvalid(input, options);
        invalidInputs.push(input);
        if (message) {
          messages.push(message);
        }
      };

      let height; // will be in cm after validation
      
      if (isMetric) {
        const hCmInput = root.querySelector('#h-cm');
        const heightValidation = ValidationHelpers.validateNumber(hCmInput.value, 0.1, 300, __( 'Height', 'vareon-calculator-suite-lite' ));
        if (!heightValidation.valid) {
          recordInvalid(hCmInput, heightValidation.message, {
            validator: () => {
              const result = ValidationHelpers.validateNumber(hCmInput.value, 0.1, 300, __( 'Height', 'vareon-calculator-suite-lite' ));
              return result.valid;
            },
          });
        } else {
          height = heightValidation.value;
        }
      } else {
        const hFtInput = root.querySelector('#h-ft');
        const hInInput = root.querySelector('#h-in');
        
        const ftVal = parseFloat(hFtInput.value) || 0;
        const inVal = parseFloat(hInInput.value) || 0;
        
        // Basic validation: at least some height entered
        if (ftVal === 0 && inVal === 0) {
          recordInvalid(hFtInput, __( 'Please enter a height.', 'vareon-calculator-suite-lite' ));
          recordInvalid(hInInput, null);
        }
        
        // Validate feet (0-8)
        if (ftVal < 0 || ftVal > 8) {
          recordInvalid(hFtInput, __( 'Feet must be between 0 and 8.', 'vareon-calculator-suite-lite' ), {
            validator: () => {
              const value = parseFloat(hFtInput.value) || 0;
              return value >= 0 && value <= 8;
            },
          });
        }
        
        // Validate inches (0-11.9)
        if (inVal < 0 || inVal >= 12) {
          recordInvalid(hInInput, __( 'Inches must be between 0 and 11.9.', 'vareon-calculator-suite-lite' ), {
            validator: () => {
              const value = parseFloat(hInInput.value) || 0;
              return value >= 0 && value < 12;
            },
          });
        }
        
        if (invalidInputs.length === 0) {
          // Convert ft+in to cm
          height = feetInchesToCm(ftVal, inVal);
          
          // Sanity check: reasonable height range (roughly 30cm - 275cm)
          if (height < 30 || height > 275) {
            const validator = () => {
              const ftValue = parseFloat(hFtInput.value) || 0;
              const inValue = parseFloat(hInInput.value) || 0;
              if (ftValue === 0 && inValue === 0) {
                return false;
              }
              if (ftValue < 0 || ftValue > 8 || inValue < 0 || inValue >= 12) {
                return false;
              }
              const cm = feetInchesToCm(ftValue, inValue);
              return cm >= 30 && cm <= 275;
            };
            recordInvalid(hFtInput, __( 'Height seems out of range. Please check your input.', 'vareon-calculator-suite-lite' ), { validator });
            recordInvalid(hInInput, null, { validator });
            height = null;
          }
        }
      }

      // Validate weight
      const weightValidation = ValidationHelpers.validateNumber(wInput.value, 0.1, weightMax, __( 'Weight', 'vareon-calculator-suite-lite' ));
      if (!weightValidation.valid) {
        recordInvalid(wInput, weightValidation.message, {
          validator: () => {
            const result = ValidationHelpers.validateNumber(wInput.value, 0.1, weightMax, __( 'Weight', 'vareon-calculator-suite-lite' ));
            return result.valid;
          },
        });
      }

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

      const heightM = height / 100;

      const weight = weightValidation.value;
      let weightKg = weight;

      // Convert weight to kg if imperial
      if (!isMetric) {
        weightKg = weight * 0.45359237;
      }

      ValidationHelpers.setButtonLoading(button, true);
      try {
        const bmi = weightKg / (heightM * heightM);

        if (!isFinite(bmi)) {
          ValidationHelpers.showResultError(resultPanel, __( 'Unable to calculate BMI.', 'vareon-calculator-suite-lite' ));
          resultPanel.className = 'vareoncalc-panel-result bmi-diagnosis';
          return;
        }

        // Calculate ideal weight range (BMI 18.5-25)
        const idealWeightMinKg = 18.5 * heightM * heightM;
        const idealWeightMaxKg = 25 * heightM * heightM;
        
        // Convert ideal weights to display units
        let idealWeightMin, idealWeightMax, weightUnit;
        if (isMetric) {
          idealWeightMin = Math.round(idealWeightMinKg);
          idealWeightMax = Math.round(idealWeightMaxKg);
          weightUnit = __( 'kg', 'vareon-calculator-suite-lite' );
        } else {
          idealWeightMin = Math.round(idealWeightMinKg / 0.45359237);
          idealWeightMax = Math.round(idealWeightMaxKg / 0.45359237);
          weightUnit = __( 'lbs', 'vareon-calculator-suite-lite' );
        }

        // Actionable delta messaging
        let actionText = '';
        let actionIcon = '';
        if (weightKg < idealWeightMinKg) {
          const gainNeededKg = idealWeightMinKg - weightKg;
          const gainDisplay = isMetric
            ? `${gainNeededKg.toFixed(1)}${weightUnit}`
            : `${(gainNeededKg / 0.45359237).toFixed(1)}${weightUnit}`;
          actionText = sprintf(
            __( 'Gain %1$s to reach healthy weight.', 'vareon-calculator-suite-lite' ),
            `<strong>${gainDisplay}</strong>`
          );
          actionIcon = '&#128200;';
        } else if (weightKg > idealWeightMaxKg) {
          const loseNeededKg = weightKg - idealWeightMaxKg;
          const loseDisplay = isMetric
            ? `${loseNeededKg.toFixed(1)}${weightUnit}`
            : `${(loseNeededKg / 0.45359237).toFixed(1)}${weightUnit}`;
          actionText = sprintf(
            __( 'Lose %1$s to reach healthy weight.', 'vareon-calculator-suite-lite' ),
            `<strong>${loseDisplay}</strong>`
          );
          actionIcon = '&#128201;';
        } else {
          actionText = __( 'You are in the healthy zone. Great job!', 'vareon-calculator-suite-lite' );
          actionIcon = '&#10024;';
        }

        // Determine category and messaging
        let category, categoryClass, advice, adviceClass;
        if (bmi < 18.5) {
          category = __( 'Underweight', 'vareon-calculator-suite-lite' );
          categoryClass = 'bmi-category--underweight';
          advice = __( 'Fuel your body. Focus on nutrient-dense foods to build strength and resilience.', 'vareon-calculator-suite-lite' );
          adviceClass = 'bmi-advice--action';
        } else if (bmi < 25) {
          category = __( 'Normal Weight', 'vareon-calculator-suite-lite' );
          categoryClass = 'bmi-category--normal';
          advice = __( 'Maintenance is key. Continue balancing activity and nutrition to steward your health.', 'vareon-calculator-suite-lite' );
          adviceClass = 'bmi-advice--positive';
        } else if (bmi < 30) {
          category = __( 'Overweight', 'vareon-calculator-suite-lite' );
          categoryClass = 'bmi-category--overweight';
          advice = __( 'Small changes add up. Focus on sustainable habits rather than drastic measures.', 'vareon-calculator-suite-lite' );
          adviceClass = 'bmi-advice--action';
        } else if (bmi < 35) {
          category = __( 'Obese (Class I)', 'vareon-calculator-suite-lite' );
          categoryClass = 'bmi-category--obese-1';
          advice = __( 'Prioritize your health. Consult a professional to create a safe plan for reducing strain on your body.', 'vareon-calculator-suite-lite' );
          adviceClass = 'bmi-advice--action';
        } else if (bmi < 40) {
          category = __( 'Obese (Class II)', 'vareon-calculator-suite-lite' );
          categoryClass = 'bmi-category--obese-2';
          advice = __( 'Prioritize your health. Consult a professional to create a safe plan for reducing strain on your body.', 'vareon-calculator-suite-lite' );
          adviceClass = 'bmi-advice--action';
        } else {
          category = __( 'Severe Obesity (Class III)', 'vareon-calculator-suite-lite' );
          categoryClass = 'bmi-category--obese-3';
          advice = __( 'Prioritize your health. Consult a professional to create a safe plan for reducing strain on your body.', 'vareon-calculator-suite-lite' );
          adviceClass = 'bmi-advice--action';
        }

        // Map BMI to equal-width category zones so marker and color bands stay synchronized.
        const underMin = 15;
        const underMax = 18.5;
        const normalMax = 25;
        const overMax = 30;
        const obeseMax = 40;
        let markerPosition;

        if (bmi <= underMax) {
          const underRatio = (bmi - underMin) / (underMax - underMin);
          markerPosition = Math.max(0, Math.min(25, underRatio * 25));
        } else if (bmi <= normalMax) {
          markerPosition = 25 + ((bmi - underMax) / (normalMax - underMax)) * 25;
        } else if (bmi <= overMax) {
          markerPosition = 50 + ((bmi - normalMax) / (overMax - normalMax)) * 25;
        } else {
          const obeseRatio = (bmi - overMax) / (obeseMax - overMax);
          markerPosition = 75 + Math.max(0, Math.min(25, obeseRatio * 25));
        }

        if (!Number.isFinite(markerPosition)) {
          markerPosition = 50;
        }

        let coachHeadline = __( 'Build steady momentum', 'vareon-calculator-suite-lite' );
        if (bmi >= 18.5 && bmi < 25) {
          coachHeadline = __( 'Maintain your great momentum', 'vareon-calculator-suite-lite' );
        } else if (bmi >= 30) {
          coachHeadline = __( 'Start with consistent wins', 'vareon-calculator-suite-lite' );
        }

        // Remove placeholder state and render results
        resultPanel.className = 'vareoncalc-panel-result bmi-results bmi-results--fitness';
        resultPanel.innerHTML = `
          <div class="bmi-results__hero ${categoryClass}">
            <div class="bmi-hero__score-label">${__( 'BMI Score', 'vareon-calculator-suite-lite' )}</div>
            <div class="bmi-hero__score">${bmi.toFixed(1)}</div>
            <div class="bmi-hero__category">${category}</div>
            <div class="bmi-hero__spectrum" aria-hidden="true">
              <div class="bmi-spectrum__track">
                <div class="bmi-spectrum__marker" style="left: ${markerPosition}%;"></div>
              </div>
              <div class="bmi-spectrum__labels">
                <div class="bmi-spectrum__zone">
                  <span class="bmi-spectrum__zone-name">${__( 'Underweight', 'vareon-calculator-suite-lite' )}</span>
                  <span class="bmi-spectrum__zone-range">&lt;18.5</span>
                </div>
                <div class="bmi-spectrum__zone">
                  <span class="bmi-spectrum__zone-name">${__( 'Healthy', 'vareon-calculator-suite-lite' )}</span>
                  <span class="bmi-spectrum__zone-range">18.5-25</span>
                </div>
                <div class="bmi-spectrum__zone">
                  <span class="bmi-spectrum__zone-name">${__( 'Overweight', 'vareon-calculator-suite-lite' )}</span>
                  <span class="bmi-spectrum__zone-range">25-30</span>
                </div>
                <div class="bmi-spectrum__zone">
                  <span class="bmi-spectrum__zone-name">${__( 'Obese', 'vareon-calculator-suite-lite' )}</span>
                  <span class="bmi-spectrum__zone-range">&gt;30</span>
                </div>
              </div>
            </div>
          </div>

          <div class="bmi-results__insights">
            <div class="bmi-coach-card bmi-coach-card--range">
              <div class="bmi-insight__label">${__( 'Healthy Weight Range', 'vareon-calculator-suite-lite' )}</div>
              <div class="bmi-insight__value-row">
                <svg class="bmi-insight__svg-icon" viewBox="0 0 20 20" fill="none" width="20" height="20"><path d="M10 2a1 1 0 011 1v1.07A7.002 7.002 0 0117 11a7 7 0 01-14 0 7.002 7.002 0 016-6.93V3a1 1 0 011-1zm0 4a5 5 0 100 10 5 5 0 000-10zm-.707 2.293a1 1 0 011.414 0l2 2a1 1 0 01-1.414 1.414L10 10.414l-1.293 1.293a1 1 0 01-1.414-1.414l2-2z" fill="currentColor"/></svg>
                <span class="bmi-insight__value">${idealWeightMin}-${idealWeightMax} ${weightUnit}</span>
              </div>
            </div>
            <div class="bmi-coach-card bmi-coach-card--target">
              <div class="bmi-insight__label">${__( 'Coach Target', 'vareon-calculator-suite-lite' )}</div>
              <div class="bmi-insight bmi-insight--action">
                <svg class="bmi-insight__svg-icon" viewBox="0 0 20 20" fill="none" width="20" height="20"><circle cx="10" cy="10" r="8" stroke="currentColor" stroke-width="1.5"/><circle cx="10" cy="10" r="5" stroke="currentColor" stroke-width="1.5"/><circle cx="10" cy="10" r="2" fill="currentColor"/></svg>
                <div class="bmi-insight__text">${actionText}</div>
              </div>
            </div>
          </div>

          <div class="bmi-results__advice ${adviceClass}">
            <div class="bmi-coach-advice__title">${coachHeadline}: ${advice}</div>
          </div>

          <div class="bmi-results__note">
            ${__( 'BMI does not account for muscle mass or bone density.', 'vareon-calculator-suite-lite' )}
          </div>
        `;

        applyThemedPanels(resultPanel);
      } catch (error) {
        console.error('BMI calculation failed', error);
        ValidationHelpers.showResultError(resultPanel, __( 'Unable to calculate BMI.', 'vareon-calculator-suite-lite' ));
        resultPanel.className = 'vareoncalc-panel-result bmi-diagnosis';
      } finally {
        ValidationHelpers.setButtonLoading(button, false);
        showResultsStep();
      }
    });

    twoStepInstance = initCompactTwoStep(root, { canProceed });
    refreshTwoStepLayout();
  }
  
  render();
}

