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

export function mount(root) {
  const formatting = getFormattingConfig();
  const currencySymbol = escapeHtml(formatting.currencySymbol || '$');
  const uid = `vareoncalc-loan-${Math.random().toString(36).slice(2, 9)}`;
  const ids = {
    amount: `${uid}-amount`,
    apr: `${uid}-apr`,
    term: `${uid}-term`,
    extraPayment: `${uid}-extra`,
    termWarning: `${uid}-term-warning`,
    resultPanel: `${uid}-result-panel`,
    resultPlaceholder: `${uid}-result-placeholder`,
    resultContent: `${uid}-result-content`,
    resultError: `${uid}-result-error`,
    monthlyPayment: `${uid}-monthly-payment`,
    breakdownPrincipal: `${uid}-breakdown-principal`,
    breakdownInterest: `${uid}-breakdown-interest`,
    breakdownTotal: `${uid}-breakdown-total`,
    costPerDollar: `${uid}-cost-per-dollar`,
    savingsBox: `${uid}-savings-box`,
    savingsText: `${uid}-savings-text`,
    calcButton: `${uid}-calculate`,
  };
  const termLabelContent = sprintf(
    /* translators: %s: loan term unit toggle (mo/yr) */
    __( 'Term (%s)', 'vareon-calculator-suite-lite' ),
    '<span class="vareoncalc-term-units" role="group" aria-label="' + __( 'Term unit', 'vareon-calculator-suite-lite' ) + '">' +
      '<button type="button" class="vareoncalc-term-unit" data-unit="months" aria-pressed="false">' + __( 'Mo', 'vareon-calculator-suite-lite' ) + '</button>' +
      '<span class="vareoncalc-term-unit-divider" aria-hidden="true">/</span>' +
      '<button type="button" class="vareoncalc-term-unit is-active" data-unit="years" aria-pressed="true">' + __( 'Yr', 'vareon-calculator-suite-lite' ) + '</button>' +
    '</span>'
  );

  // Financial Advisor Dashboard Layout
  // Compact two-step flow: inputs -> cost analysis
  root.innerHTML = `
    <div class="vareoncalc-two-step vareoncalc-loan-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">
          <!-- LEFT PANEL: The Terms -->
          <div class="vareoncalc-panel-input">
            <div class="vareoncalc-section loan-section">
              <div class="vareoncalc-section__header">
                <div class="vareoncalc-section__title">${__( 'Loan Terms', 'vareon-calculator-suite-lite' )}</div>
              </div>

              <!-- Loan Amount: Full width hero input with right-rail currency suffix -->
              <div class="vareoncalc-field vareoncalc-field--hero">
                <label for="${ids.amount}">${__( 'Loan Amount', 'vareon-calculator-suite-lite' )}</label>
                <input type="number" id="${ids.amount}" class="vareoncalc-input" data-field="amount" data-suffix="${currencySymbol}" data-suffix-family="currency" placeholder="${__( 'e.g.', 'vareon-calculator-suite-lite' )} 25000" inputmode="numeric" min="1" step="1000">
              </div>

              <!-- APR + Term: Side-by-side (the loan conditions) -->
              <div class="vareoncalc-field-row">
                <div class="vareoncalc-field">
                  <label for="${ids.apr}" data-help="${__( 'Annual Percentage Rate - the yearly interest rate charged by your lender, including fees.', 'vareon-calculator-suite-lite' )}">${__( 'APR', 'vareon-calculator-suite-lite' )}</label>
                  <input type="number" id="${ids.apr}" class="vareoncalc-input" data-field="apr" data-suffix="%" placeholder="${__( 'e.g.', 'vareon-calculator-suite-lite' )} 6.5" step="0.01" inputmode="decimal" min="0" max="99.99">
                </div>
                <div class="vareoncalc-field">
                  <div class="vareoncalc-field-header">
                    <label for="${ids.term}" data-role="term-label">${termLabelContent}</label>
                  </div>
                  <input type="number" id="${ids.term}" class="vareoncalc-input" data-field="term" data-suffix="${__( 'yr', 'vareon-calculator-suite-lite' )}" placeholder="${__( 'e.g.', 'vareon-calculator-suite-lite' )} 5" inputmode="numeric" min="1" max="100" step="1" aria-describedby="${ids.termWarning}">
                  <div class="vareoncalc-term-warning" id="${ids.termWarning}" data-role="term-warning" role="status" aria-live="polite" style="display: none;"></div>
                </div>
              </div>
            </div>

            <div class="vareoncalc-section loan-section">
              <div class="vareoncalc-section__header">
                <div class="vareoncalc-section__title">${__( 'Payment Strategy', 'vareon-calculator-suite-lite' )}</div>
              </div>
              <div class="vareoncalc-field">
                <label for="${ids.extraPayment}">${__( 'Extra Monthly Payment', 'vareon-calculator-suite-lite' )}</label>
                <input type="number" id="${ids.extraPayment}" class="vareoncalc-input" data-field="extra-payment" data-suffix="${currencySymbol}" data-suffix-family="currency" placeholder="${__( 'e.g.', 'vareon-calculator-suite-lite' )} 50" inputmode="decimal" min="0" step="0.01">
              </div>
            </div>

            <!-- Calculate Button -->
            <button type="button" class="vareoncalc-btn" id="${ids.calcButton}" data-action="calculate" data-two-step-next>${__( 'Calculate Repayment', '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">
          <!-- RIGHT PANEL: The Cost Analysis -->
          <div class="vareoncalc-panel-result vareoncalc-loan-result" id="${ids.resultPanel}" data-role="result-panel">
            <!-- Placeholder state (before calculation) -->
            <div class="vareoncalc-loan-result__placeholder" id="${ids.resultPlaceholder}" data-role="result-placeholder">
              <div class="placeholder-icon">&#128176;</div>
              <div class="placeholder-text">${__( 'Enter loan details to see your cost breakdown', 'vareon-calculator-suite-lite' )}</div>
            </div>
            <div id="${ids.resultError}" data-role="result-error" style="display: none;"></div>

            <!-- Results (hidden initially) -->
            <div class="vareoncalc-loan-result__content" id="${ids.resultContent}" data-role="result-content" style="display: none;">
              <!-- Monthly Payment Hero -->
              <div class="loan-result-headline">
                <div class="loan-monthly-amount" id="${ids.monthlyPayment}" data-result="monthly-payment"></div>
                <div class="loan-monthly-label">${__( 'Monthly Payment', 'vareon-calculator-suite-lite' )}</div>
              </div>

              <!-- Loan Details + Impact Grid -->
              <div class="loan-info-grid">
                <div class="loan-detail-card loan-detail-card--details">
                  <div class="loan-detail-card__title">${__( 'Loan Details', 'vareon-calculator-suite-lite' )}</div>
                  <div class="loan-breakdown-row">
                    <span class="breakdown-label">${__( 'Loan Amount (Principal)', 'vareon-calculator-suite-lite' )}</span>
                    <span class="breakdown-value" id="${ids.breakdownPrincipal}" data-result="breakdown-principal"></span>
                  </div>
                  <div class="loan-breakdown-row loan-breakdown-row--interest">
                    <span class="breakdown-label">${__( 'Total Interest', 'vareon-calculator-suite-lite' )}</span>
                    <span class="breakdown-value breakdown-value--interest" id="${ids.breakdownInterest}" data-result="breakdown-interest"></span>
                  </div>
                  <div class="loan-breakdown-row loan-breakdown-row--total">
                    <span class="breakdown-label">${__( 'Total Cost', 'vareon-calculator-suite-lite' )}</span>
                    <span class="breakdown-value breakdown-value--total" id="${ids.breakdownTotal}" data-result="breakdown-total"></span>
                  </div>
                </div>
                <div class="loan-detail-card loan-detail-card--impact" id="${ids.savingsBox}" data-result="savings-box" style="display: none;">
                  <div class="loan-detail-card__title">${__( 'Impact', 'vareon-calculator-suite-lite' )}</div>
                  <div class="loan-impact__badge">
                    <span class="loan-impact__badge-value" data-result="savings-extra"></span>
                  </div>
                  <div class="loan-impact__stats">
                    <div class="loan-impact__stat">
                      <div class="loan-impact__stat-icon loan-impact__stat-icon--savings" aria-hidden="true">
                        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 0 1 0 4H8"/><path d="M12 18V6"/></svg>
                      </div>
                      <div class="loan-impact__stat-body">
                        <span class="loan-impact__stat-value" data-result="savings-amount"></span>
                        <span class="loan-impact__stat-label">${__( 'Interest Saved', 'vareon-calculator-suite-lite' )}</span>
                      </div>
                    </div>
                    <div class="loan-impact__stat">
                      <div class="loan-impact__stat-icon loan-impact__stat-icon--time" aria-hidden="true">
                        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="4" width="18" height="18" rx="2" ry="2"/><line x1="16" y1="2" x2="16" y2="6"/><line x1="8" y1="2" x2="8" y2="6"/><line x1="3" y1="10" x2="21" y2="10"/></svg>
                      </div>
                      <div class="loan-impact__stat-body">
                        <span class="loan-impact__stat-value" data-result="savings-time"></span>
                        <span class="loan-impact__stat-label">${__( 'Paid Off Sooner', 'vareon-calculator-suite-lite' )}</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>

              <!-- Cost of Money -->
              <div class="loan-cost-metric">
                <div class="loan-cost-metric__header">${__( 'Cost of Money', 'vareon-calculator-suite-lite' )}</div>
                <div class="loan-cost-metric__visual">
                  <div class="loan-cost-metric__unit">
                    <div class="loan-cost-metric__icon loan-cost-metric__icon--borrow" aria-hidden="true">
                      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 0 1 0 4H8"/><path d="M12 18V6"/></svg>
                    </div>
                    <span class="loan-cost-metric__amount" data-result="cost-borrowed"></span>
                    <span class="loan-cost-metric__caption">${__( 'Borrowed', 'vareon-calculator-suite-lite' )}</span>
                  </div>
                  <div class="loan-cost-metric__arrow" aria-hidden="true">
                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M5 12h14"/><path d="m12 5 7 7-7 7"/></svg>
                  </div>
                  <div class="loan-cost-metric__unit loan-cost-metric__unit--payback">
                    <div class="loan-cost-metric__icon loan-cost-metric__icon--payback" aria-hidden="true">
                      <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 0 1 0 4H8"/><path d="M12 18V6"/></svg>
                    </div>
                    <span class="loan-cost-metric__amount" id="${ids.costPerDollar}" data-result="cost-per-dollar"></span>
                    <span class="loan-cost-metric__caption">${__( 'Paid back', 'vareon-calculator-suite-lite' )}</span>
                  </div>
                </div>
              </div>

              <!-- Donut Chart: Principal vs Interest -->
              <div class="loan-donut" role="img" aria-label="${__( 'Principal vs interest breakdown', 'vareon-calculator-suite-lite' )}">
                <div class="loan-donut__header">${__( 'Principal vs Interest', 'vareon-calculator-suite-lite' )}</div>
                <div class="loan-donut__wrap">
                  <svg class="loan-donut__svg" viewBox="0 0 200 200">
                    <circle class="loan-donut__track" cx="100" cy="100" r="80" fill="none" stroke-width="28"/>
                    <circle class="loan-donut__segment loan-donut__segment--principal" data-result="donut-principal" cx="100" cy="100" r="80" fill="none" stroke-width="28" stroke-dasharray="502.65 0" transform="rotate(-90 100 100)"/>
                    <circle class="loan-donut__segment loan-donut__segment--interest" data-result="donut-interest" cx="100" cy="100" r="80" fill="none" stroke-width="28" stroke-dasharray="0 502.65" stroke-dashoffset="0" transform="rotate(-90 100 100)"/>
                  </svg>
                  <div class="loan-donut__legend">
                    <div class="loan-donut__legend-item loan-donut__legend-item--principal">
                      <span class="loan-donut__legend-color"></span>
                      <span class="loan-donut__legend-label">${__( 'Principal', 'vareon-calculator-suite-lite' )}</span>
                      <span class="loan-donut__legend-pct" data-result="legend-principal-pct">100%</span>
                    </div>
                    <div class="loan-donut__legend-item loan-donut__legend-item--interest">
                      <span class="loan-donut__legend-color"></span>
                      <span class="loan-donut__legend-label">${__( 'Interest', 'vareon-calculator-suite-lite' )}</span>
                      <span class="loan-donut__legend-pct" data-result="legend-interest-pct">0%</span>
                    </div>
                  </div>
                </div>
              </div>
            </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(root);
  HelpTooltip.apply(root);

  const amtInput = root.querySelector('[data-field="amount"]');
  const aprInput = root.querySelector('[data-field="apr"]');
  const yrsInput = root.querySelector('[data-field="term"]');
  const button = root.querySelector('[data-action="calculate"]');
  
  // Result elements
  const resultPlaceholder = root.querySelector('[data-role="result-placeholder"]');
  const resultContent = root.querySelector('[data-role="result-content"]');
  const resultError = root.querySelector('[data-role="result-error"]');
  const monthlyPaymentEl = root.querySelector('[data-result="monthly-payment"]');
  const breakdownPrincipal = root.querySelector('[data-result="breakdown-principal"]');
  const breakdownInterest = root.querySelector('[data-result="breakdown-interest"]');
  const breakdownTotal = root.querySelector('[data-result="breakdown-total"]');
  const costBorrowedEl = root.querySelector('[data-result="cost-borrowed"]');
  const costPerDollarEl = root.querySelector('[data-result="cost-per-dollar"]');
  const infoGrid = root.querySelector('.loan-info-grid');
  const savingsBox = root.querySelector('[data-result="savings-box"]');
  const savingsExtraEl = root.querySelector('[data-result="savings-extra"]');
  const savingsAmountEl = root.querySelector('[data-result="savings-amount"]');
  const savingsTimeEl = root.querySelector('[data-result="savings-time"]');
  const donutPrincipal = root.querySelector('[data-result="donut-principal"]');
  const donutInterest = root.querySelector('[data-result="donut-interest"]');
  const legendPrincipalPct = root.querySelector('[data-result="legend-principal-pct"]');
  const legendInterestPct = root.querySelector('[data-result="legend-interest-pct"]');
  const termWarning = root.querySelector('[data-role="term-warning"]');
  const extraPaymentInput = root.querySelector('[data-field="extra-payment"]');
  const termUnitButtons = root.querySelectorAll('.vareoncalc-term-unit');
  [amtInput, aprInput, yrsInput, extraPaymentInput].forEach((input) => {
    input?.closest('.vareoncalc-input-adorned')?.classList.add('vareoncalc-input-adorned--suffix-rail', 'vareoncalc-loan-input-rail');
  });

  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();
      }
    });
  };

  let currentTermUnit = 'years';

  const updateTermWarning = () => {
    const termValue = Number(yrsInput.value);
    if (!yrsInput.value || isNaN(termValue)) {
      termWarning.style.display = 'none';
      termWarning.textContent = '';
      return;
    }

    if (currentTermUnit === 'years' && termValue > 30) {
      termWarning.textContent = __( 'Did you mean months? A term over 30 years is uncommon.', 'vareon-calculator-suite-lite' );
      termWarning.style.display = 'block';
      return;
    }

    if (currentTermUnit === 'months' && termValue > 360) {
      termWarning.textContent = __( 'Did you mean years? 360 months is 30 years.', 'vareon-calculator-suite-lite' );
      termWarning.style.display = 'block';
      return;
    }

    termWarning.style.display = 'none';
    termWarning.textContent = '';
  };

  const setTermUnit = (unit) => {
    if (!unit) return;
    currentTermUnit = unit;
    termUnitButtons.forEach(button => {
      const isActive = button.dataset.unit === unit;
      button.classList.toggle('is-active', isActive);
      button.setAttribute('aria-pressed', isActive ? 'true' : 'false');
    });

    yrsInput.max = unit === 'months' ? '1200' : '100';
    yrsInput.min = '1';
    yrsInput.step = '1';
    yrsInput.placeholder = unit === 'months'
      ? `${__( 'e.g.', 'vareon-calculator-suite-lite' )} 60`
      : `${__( 'e.g.', 'vareon-calculator-suite-lite' )} 5`;
    InputAdornment.setSuffix(
      yrsInput,
      unit === 'months'
        ? __( 'mo', 'vareon-calculator-suite-lite' )
        : __( 'yr', 'vareon-calculator-suite-lite' )
    );

    updateTermWarning();
  };

  const computeExtraPaymentImpact = ({ principal, annualRate, baseMonthlyPayment, extraPayment, basePayments }) => {
    if (!extraPayment || extraPayment <= 0) return null;

    const payment = baseMonthlyPayment + extraPayment;
    if (!Number.isFinite(payment) || payment <= 0) return null;

    const monthlyRate = annualRate / 12;
    let balance = principal;
    let totalInterest = 0;
    let months = 0;
    const maxMonths = Math.max(12, Math.ceil(basePayments * 2) + 12);

    while (balance > 0 && months < maxMonths) {
      const interest = balance * monthlyRate;
      let principalPayment = payment - interest;
      if (principalPayment <= 0) {
        return null;
      }
      if (principalPayment > balance) {
        principalPayment = balance;
      }
      balance -= principalPayment;
      totalInterest += interest;
      months += 1;
    }

    if (balance > 0) {
      return null;
    }

    return {
      months,
      totalInterest,
      totalPayment: principal + totalInterest,
    };
  };

  // Validation function for auto-calc (returns true if all inputs are valid, without showing errors)
  const validateAll = () => {
    const amt = Number(amtInput.value);
    const apr = Number(aprInput.value);
    const termValue = Number(yrsInput.value);
    const extraPayment = Number(extraPaymentInput.value);
    
    if (!amtInput.value || isNaN(amt) || amt <= 0) return false;
    if (aprInput.value === '' || isNaN(apr) || apr < 0 || apr > 99.99) return false;
    if (!yrsInput.value || isNaN(termValue) || termValue < 1) return false;

    const maxTerm = currentTermUnit === 'months' ? 1200 : 100;
    if (termValue > maxTerm) return false;

    if (extraPaymentInput.value !== '' && (isNaN(extraPayment) || extraPayment < 0)) return false;
    
    return true;
  };
  // Show error as toast and invalid input highlights
  const showError = (message, inputs = []) => {
    const targets = Array.isArray(inputs) ? inputs : (inputs ? [inputs] : []);
    targets.filter(Boolean).forEach(input => ValidationHelpers.markInvalid(input));
    ValidationHelpers.showToast(root, message);
  };

  // Clear error display
  const clearError = () => {
    if (resultError) {
      resultError.style.display = 'none';
      resultError.innerHTML = '';
    }
  };

  // The main calculation function
  const calculate = (event = null) => {
    ValidationHelpers.clearAllErrors(root);
    clearError();
    updateTermWarning();
    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) => {
      showError(message, input ? [input] : []);
      if (event) {
        event.preventDefault();
        event.stopImmediatePropagation();
      }
    };

    // Validate loan amount
    const amtValidation = ValidationHelpers.validateNumber(amtInput.value, 0.01, Infinity, __( 'Loan amount', 'vareon-calculator-suite-lite' ));
    if (!amtValidation.valid) {
      recordInvalid(amtInput, amtValidation.message);
    }

    // Validate APR
    const aprValue = Number(aprInput.value);
    if (aprInput.value === '' || isNaN(aprValue)) {
      recordInvalid(aprInput, __( 'APR is required.', 'vareon-calculator-suite-lite' ));
    }
    if (aprValue < 0) {
      recordInvalid(aprInput, __( 'APR cannot be negative.', 'vareon-calculator-suite-lite' ));
    }
    if (aprValue > 99.99) {
      recordInvalid(aprInput, __( 'APR must be less than 100%.', 'vareon-calculator-suite-lite' ));
    }

    // Validate term
    const termMin = 1;
    const termMax = currentTermUnit === 'months' ? 1200 : 100;
    const termValidation = ValidationHelpers.validateNumber(yrsInput.value, termMin, termMax, __( 'Term', 'vareon-calculator-suite-lite' ));
    if (!termValidation.valid) {
      recordInvalid(yrsInput, termValidation.message);
    }

    const extraPaymentValue = extraPaymentInput.value === '' ? 0 : Number(extraPaymentInput.value);
    if (extraPaymentInput.value !== '' && (isNaN(extraPaymentValue) || extraPaymentValue < 0)) {
      recordInvalid(
        extraPaymentInput,
        __( 'Extra payment must be zero or more.', 'vareon-calculator-suite-lite' ),
        {
          allowEmpty: true,
          validator: () => {
            const raw = extraPaymentInput.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(root, message);
      if (event) {
        event.preventDefault();
        event.stopImmediatePropagation();
      }
      return;
    }

    const principal = Number(amtInput.value);
    const annualRate = Number(aprInput.value) / 100; // Convert percentage to decimal
    const termValue = Number(yrsInput.value);
    const totalPayments = currentTermUnit === 'months' ? termValue : termValue * 12;

    // Calculate loan payment
    const monthlyRate = annualRate / 12;
    let monthlyPayment;

    if (monthlyRate === 0) {
      monthlyPayment = principal / totalPayments;
    } else {
      const rateExp = Math.pow(1 + monthlyRate, -totalPayments);
      if (!isFinite(rateExp)) {
        blockStep(__( 'Term is too large to calculate accurately.', 'vareon-calculator-suite-lite' ));
        return;
      }
      monthlyPayment = (principal * monthlyRate) / (1 - rateExp);
    }

    if (!isFinite(monthlyPayment)) {
      blockStep(__( 'Term is too large to calculate accurately.', 'vareon-calculator-suite-lite' ));
      return;
    }

    const totalPayment = monthlyPayment * totalPayments;
    const totalInterest = totalPayment - principal;
    const basePayments = Math.round(totalPayments);

    // Calculate percentages for visual bar
    const principalPercent = (principal / totalPayment) * 100;
    const interestPercent = (totalInterest / totalPayment) * 100;

    // Update the result display
    resultPlaceholder.style.display = 'none';
    resultContent.style.display = 'block';

    // Monthly payment (the big number)
    monthlyPaymentEl.innerHTML = formatCurrencyHtml(monthlyPayment);

    // Breakdown card
    breakdownPrincipal.innerHTML = formatCurrencyHtml(principal);
    breakdownInterest.innerHTML = formatCurrencyHtml(totalInterest);
    breakdownTotal.innerHTML = formatCurrencyHtml(totalPayment);

    // Cost-of-money metric (visual)
    costBorrowedEl.innerHTML = formatCurrencyHtml(1, { decimals: 0, maxDecimals: 0, minDecimals: 0 });
    costPerDollarEl.innerHTML = formatCurrencyHtml(totalPayment / principal, { decimals: 2, maxDecimals: 2, minDecimals: 2 });

    // Savings box (extra payment impact)
    const extraImpact = computeExtraPaymentImpact({
      principal,
      annualRate,
      baseMonthlyPayment: monthlyPayment,
      extraPayment: extraPaymentValue,
      basePayments,
    });
    const savings = extraImpact ? (totalInterest - extraImpact.totalInterest) : 0;
    const monthsEarly = extraImpact ? Math.max(0, basePayments - extraImpact.months) : 0;

    if (extraPaymentValue > 0 && extraImpact && savings > 0 && monthsEarly > 0) {
      // Subtitle: extra payment amount
      savingsExtraEl.innerHTML = sprintf(
        __( '+%s/mo', 'vareon-calculator-suite-lite' ),
        formatCurrencyHtml(extraPaymentValue)
      );

      // Stat 1: interest saved
      savingsAmountEl.innerHTML = formatCurrencyHtml(savings);

      // Stat 2: time saved in human-readable format
      const years = Math.floor(monthsEarly / 12);
      const remainingMonths = monthsEarly % 12;
      let timeDisplay = '';
      if (years > 0 && remainingMonths > 0) {
        timeDisplay = sprintf(
          __( '%d yr %d mo', 'vareon-calculator-suite-lite' ),
          years,
          remainingMonths
        );
      } else if (years > 0) {
        timeDisplay = sprintf(
          __( '%d yr', 'vareon-calculator-suite-lite' ),
          years
        );
      } else {
        timeDisplay = sprintf(
          __( '%d mo', 'vareon-calculator-suite-lite' ),
          remainingMonths
        );
      }
      savingsTimeEl.textContent = timeDisplay;

      savingsBox.style.display = 'block';
      if (infoGrid) { infoGrid.classList.remove('loan-info-grid--solo'); }
    } else {
      savingsBox.style.display = 'none';
      if (infoGrid) { infoGrid.classList.add('loan-info-grid--solo'); }
    }

    // Donut chart segments
    const circumference = 2 * Math.PI * 80;
    const principalLen = circumference * principalPercent / 100;
    const interestLen = circumference * interestPercent / 100;
    if (donutPrincipal) {
      donutPrincipal.setAttribute('stroke-dasharray', `${principalLen.toFixed(2)} ${(circumference - principalLen).toFixed(2)}`);
    }
    if (donutInterest) {
      donutInterest.setAttribute('stroke-dasharray', `${interestLen.toFixed(2)} ${(circumference - interestLen).toFixed(2)}`);
      donutInterest.setAttribute('stroke-dashoffset', `${(-principalLen).toFixed(2)}`);
    }

    legendPrincipalPct.textContent = principalPercent.toFixed(0) + '%';
    legendInterestPct.textContent = interestPercent.toFixed(0) + '%';
    showResultsStep();
    refreshTwoStepLayout();
  };

  // Button click handler (manual calculation)
  button.addEventListener('click', (event) => calculate(event));

  termUnitButtons.forEach(button => {
    button.addEventListener('click', () => {
      const unit = button.dataset.unit;
      if (unit === currentTermUnit) return;
      setTermUnit(unit);
      if (validateAll()) {
        calculate();
      }
    });
  });

  yrsInput.addEventListener('input', () => {
    updateTermWarning();
  });

  // Setup auto-calculation (debounced input handling)
  setupAutoCalc(root, button, [amtInput, aprInput, yrsInput, extraPaymentInput], validateAll);

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

  setTermUnit('years');
}
