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';

/**
 * ROI (Return on Investment) Calculator
 * Clean, modern input design with optional details toggle
 */

export function mount(container) {
  const formatting = getFormattingConfig();
  const currencySymbol = escapeHtml(formatting.currencySymbol || '$');

  // Compact two-step layout: inputs -> results + edit handle
  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="roi-form">
            <!-- Section 1: Your Investment -->
            <div class="roi-section vareoncalc-section">
              <div class="roi-section__header vareoncalc-section__header">
                <div class="roi-section__title vareoncalc-section__title">${__('Your Investment', 'vareon-calculator-suite-lite')}</div>
              </div>
              <div class="roi-grid">
                <div class="roi-field">
                  <label for="initial-investment">${__('Initial Investment', 'vareon-calculator-suite-lite')}</label>
      <input type="number" id="initial-investment" data-suffix="${currencySymbol}" data-suffix-family="currency" placeholder="10000" min="0" step="100" inputmode="numeric">
                </div>
                <div class="roi-field">
                  <label for="final-value">${__('Final Value', 'vareon-calculator-suite-lite')}</label>
      <input type="number" id="final-value" data-suffix="${currencySymbol}" data-suffix-family="currency" placeholder="15000" min="0" step="100" inputmode="numeric">
                </div>
              </div>
            </div>

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

              <div class="roi-optional-content vareoncalc-disclosure__content" id="roi-optional-content" hidden>
                <div class="roi-grid roi-grid--optional-details">
                  <div class="roi-field">
                    <label for="duration">${__('Duration', 'vareon-calculator-suite-lite')}</label>
                    <div class="roi-duration-input">
                      <input type="number" id="duration" placeholder="5" min="0" step="0.5" inputmode="decimal">
                      <select id="duration-unit" aria-label="${__('Time Unit', 'vareon-calculator-suite-lite')}">
                        <option value="years">${__('Years', 'vareon-calculator-suite-lite')}</option>
                        <option value="months">${__('Months', 'vareon-calculator-suite-lite')}</option>
                      </select>
                    </div>
                  </div>
                  <div class="roi-field">
                    <label for="additional-costs">${__('Additional Costs', 'vareon-calculator-suite-lite')}</label>
      <input type="number" id="additional-costs" data-suffix="${currencySymbol}" data-suffix-family="currency" placeholder="500" min="0" step="10" inputmode="numeric">
                  </div>
                  <div class="roi-field">
                    <label for="inflation-rate">${__('Inflation Rate', 'vareon-calculator-suite-lite')}</label>
                    <input type="number" id="inflation-rate" data-suffix="%" placeholder="2.5" min="0" step="0.1" inputmode="decimal">
                  </div>
                </div>
              </div>
            </div>

            <!-- Calculate Button -->
            <button type="button" class="vareoncalc-btn" id="calc-btn" data-two-step-next>${__('Calculate ROI', '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 vareoncalc-roi-result" id="result-panel">
            <!-- Placeholder state -->
            <div class="vareoncalc-roi-result__placeholder" id="result-placeholder">
              <div class="placeholder-icon">&#128200;</div>
              <div class="placeholder-text">${__('Enter investment details to see your returns', 'vareon-calculator-suite-lite')}</div>
            </div>

            <!-- Results (hidden initially) -->
            <div class="vareoncalc-roi-result__content" id="result-content" style="display: none;">
              <!-- The Headline: Massive ROI + Multiplier -->
              <div class="roi-result-headline">
                <div class="roi-percentage" id="roi-percentage"></div>
                <div class="roi-multiplier" id="roi-multiplier"></div>
              </div>

              <!-- Profit Waterfall Bar -->
              <div class="roi-visual-bar" role="img" aria-label="${__('Investment growth bar showing initial capital and profit', 'vareon-calculator-suite-lite')}">
                <div class="roi-visual-bar__header">${__('Your Money Growth', 'vareon-calculator-suite-lite')}</div>
                <div class="roi-visual-bar__track">
                  <div class="roi-visual-bar__initial" id="bar-initial"></div>
                  <div class="roi-visual-bar__profit" id="bar-profit"></div>
                </div>
                <div class="roi-visual-bar__labels">
                  <div class="roi-bar-label roi-bar-label--initial">
                    <span class="roi-bar-label__title">${__('Initial', 'vareon-calculator-suite-lite')}</span>
                    <span class="roi-bar-label__value" id="label-initial"></span>
                  </div>
                  <div class="roi-bar-label roi-bar-label--profit">
                    <span class="roi-bar-label__title" id="label-profit-title">${__('Profit', 'vareon-calculator-suite-lite')}</span>
                    <span class="roi-bar-label__value" id="label-profit"></span>
                  </div>
                  <div class="roi-bar-label roi-bar-label--total">
                    <span class="roi-bar-label__title">${__('Final', 'vareon-calculator-suite-lite')}</span>
                    <span class="roi-bar-label__value" id="label-total"></span>
                  </div>
                </div>
              </div>

              <!-- Annualized + Real ROI Cards -->
              <div class="roi-metrics-row">
                <div class="roi-speed-metric" id="speed-metric" style="display: none;">
                  <div class="roi-speed-metric__icon" 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"><path d="M13 2 3 14h9l-1 8 10-12h-9l1-8z"/></svg>
                  </div>
                  <div class="roi-speed-metric__content">
                    <div class="roi-speed-metric__label">${__('Annualized Return', 'vareon-calculator-suite-lite')}</div>
                    <div class="roi-speed-metric__value" id="annualized-roi"></div>
                  </div>
                  <div class="roi-speed-metric__duration" id="duration-text"></div>
                </div>
                <div class="roi-real-metric" id="real-roi-metric" style="display: none;">
                  <div class="roi-real-metric__icon" 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"><path d="M3 3v18h18"/><path d="m19 9-5 5-4-4-3 3"/></svg>
                  </div>
                  <div class="roi-real-metric__content">
                    <div class="roi-real-metric__label">${__('Real ROI', 'vareon-calculator-suite-lite')}</div>
                    <div class="roi-real-metric__value" id="real-roi-value"></div>
                  </div>
                </div>
              </div>

              <!-- Break-Even Requirement -->
              <div class="roi-break-even" id="break-even-metric" style="display: none;">
                <div class="roi-break-even__icon">&#127919;</div>
                <div class="roi-break-even__content">
                  <div class="roi-break-even__label">${__('Break-Even Requirement', 'vareon-calculator-suite-lite')}</div>
                  <div class="roi-break-even__value" id="break-even-value"></div>
                </div>
              </div>

              <!-- Cost adjustment note -->
              <div class="roi-cost-note" id="cost-note" style="display: none;"></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(container);
  HelpTooltip.apply(container);

  const btn = container.querySelector('#calc-btn');
  const resultPlaceholder = container.querySelector('#result-placeholder');
  const resultContent = container.querySelector('#result-content');
  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();
      }
    });
  };

  // Input elements
  const initialInput = container.querySelector('#initial-investment');
  const finalInput = container.querySelector('#final-value');
  const durationInput = container.querySelector('#duration');
  const durationUnitSelect = container.querySelector('#duration-unit');
  const costsInput = container.querySelector('#additional-costs');
  const inflationInput = container.querySelector('#inflation-rate');
  [initialInput, finalInput, costsInput, inflationInput].forEach((input) => {
    input?.closest('.vareoncalc-input-adorned')?.classList.add('vareoncalc-input-adorned--suffix-rail');
  });

  // Optional details accordion
  const optionalAccordion = container.querySelector('#roi-optional-accordion');
  const optionalAccordionText = container.querySelector('.roi-optional-accordion__text');
  const optionalContent = container.querySelector('#roi-optional-content');

  const isOptionalEnabled = () => optionalAccordion?.getAttribute('aria-expanded') === 'true';

  const setOptionalEnabled = (enabled) => {
    if (!optionalContent) {
      return;
    }
    const isEnabled = !!enabled;
    if (optionalAccordion) {
      optionalAccordion.setAttribute('aria-expanded', isEnabled ? 'true' : 'false');
    }
    if (optionalAccordionText) {
      optionalAccordionText.textContent = isEnabled
        ? __('Hide options', 'vareon-calculator-suite-lite')
        : __('Show more options', 'vareon-calculator-suite-lite');
    }
    optionalContent.hidden = !isEnabled;
    if (durationInput) {
      durationInput.disabled = !isEnabled;
    }
    if (durationUnitSelect) {
      durationUnitSelect.disabled = !isEnabled;
    }
    if (costsInput) {
      costsInput.disabled = !isEnabled;
    }
    if (inflationInput) {
      inflationInput.disabled = !isEnabled;
    }
    refreshTwoStepLayout();
  };

  const setupOptionalAccordion = () => {
    if (!optionalAccordion) {
      return;
    }
    optionalAccordion.addEventListener('click', () => {
      setOptionalEnabled(!isOptionalEnabled());
    });
  };

  setupOptionalAccordion();
  setOptionalEnabled(false);

  // Result elements
  const roiPercentageEl = container.querySelector('#roi-percentage');
  const roiMultiplierEl = container.querySelector('#roi-multiplier');
  const barInitial = container.querySelector('#bar-initial');
  const barProfit = container.querySelector('#bar-profit');
  const labelInitial = container.querySelector('#label-initial');
  const labelProfit = container.querySelector('#label-profit');
  const labelProfitTitle = container.querySelector('#label-profit-title');
  const labelTotal = container.querySelector('#label-total');
  const speedMetric = container.querySelector('#speed-metric');
  const annualizedRoiEl = container.querySelector('#annualized-roi');
  const durationText = container.querySelector('#duration-text');
  const realRoiMetric = container.querySelector('#real-roi-metric');
  const realRoiValue = container.querySelector('#real-roi-value');
  const breakEvenMetric = container.querySelector('#break-even-metric');
  const breakEvenValue = container.querySelector('#break-even-value');
  const costNote = container.querySelector('#cost-note');

  // Validation function for auto-calc
  const validateAll = () => {
    const initial = Number(initialInput.value);
    const final = Number(finalInput.value);

    if (!initialInput.value || isNaN(initial) || initial <= 0) return false;
    if (finalInput.value === '' || isNaN(final) || final < 0) return false;

    return true;
  };
  const inputsToWatch = [initialInput, finalInput, durationInput, durationUnitSelect, costsInput, inflationInput].filter(Boolean);

  const validateRequiredInputs = (event = null) => {
    ValidationHelpers.clearAllErrors(container);
    let isValid = true;

    const initialValue = Number(initialInput.value);
    if (!initialInput.value || Number.isNaN(initialValue) || initialValue <= 0) {
      ValidationHelpers.showError(
        initialInput,
        __('Please enter a valid initial investment amount.', 'vareon-calculator-suite-lite')
      );
      isValid = false;
    }

    const finalValue = Number(finalInput.value);
    if (finalInput.value === '' || Number.isNaN(finalValue) || finalValue < 0) {
      ValidationHelpers.showError(
        finalInput,
        __('Please enter a valid final value.', 'vareon-calculator-suite-lite')
      );
      isValid = false;
    }

    if (!isValid && event) {
      event.preventDefault();
      event.stopImmediatePropagation();
    }

    return isValid;
  };

  const calculate = () => {
    const initialInvestment = parseFloat(initialInput.value);
    const finalValue = parseFloat(finalInput.value);
    
    // Only use optional values if toggle is on
    const optionalEnabled = isOptionalEnabled();
    const rawDuration = optionalEnabled ? parseFloat(durationInput.value) : 0;
    const durationValue = Number.isNaN(rawDuration) ? 0 : rawDuration;
    const durationUnit = durationUnitSelect ? durationUnitSelect.value : 'years';
    const durationYears = durationUnit === 'months' ? durationValue / 12 : durationValue;
    const additionalCosts = optionalEnabled ? (parseFloat(costsInput.value) || 0) : 0;
    const inflationRate = optionalEnabled ? Math.max(0, parseFloat(inflationInput.value) || 0) : 0;

    // Calculate ROI (subtract additional costs from profit)
    const totalCost = initialInvestment + additionalCosts;
    const netProfit = finalValue - totalCost;
    const roiPercentage = ((netProfit / totalCost) * 100);
    const multiplier = finalValue / totalCost;

    // Calculate annualized ROI if duration is provided
    let annualizedROI = null;
    if (durationYears > 0 && finalValue > 0 && totalCost > 0) {
      annualizedROI = (Math.pow(finalValue / totalCost, 1 / durationYears) - 1) * 100;
    }

    const isProfit = netProfit >= 0;

    // Show results
    resultPlaceholder.style.display = 'none';
    resultContent.style.display = 'block';

    // The headline ROI percentage
    roiPercentageEl.textContent = `${roiPercentage >= 0 ? '+' : ''}${roiPercentage.toFixed(2)}%`;
    roiPercentageEl.className = `roi-percentage ${isProfit ? 'roi-percentage--profit' : 'roi-percentage--loss'}`;

    // Multiplier (e.g., "150x Return" for high ROI)
    if (multiplier >= 1.5) {
      roiMultiplierEl.textContent = `${multiplier.toFixed(1)}x ${__('Return', 'vareon-calculator-suite-lite')}`;
      roiMultiplierEl.style.display = 'block';
    } else if (multiplier < 1) {
      roiMultiplierEl.textContent = `${(multiplier * 100).toFixed(0)}% ${__('Recovered', 'vareon-calculator-suite-lite')}`;
      roiMultiplierEl.style.display = 'block';
    } else {
      roiMultiplierEl.style.display = 'none';
    }

    // Visual bar calculations
    const absProfit = Math.abs(netProfit);
    const maxValue = Math.max(totalCost, finalValue, totalCost + absProfit);
    const initialPercent = (totalCost / maxValue) * 100;
    const profitPercent = isProfit ? (netProfit / maxValue) * 100 : 0;

    // Update visual bar
    barInitial.style.width = initialPercent + '%';
    barProfit.style.width = profitPercent + '%';
    barProfit.className = `roi-visual-bar__profit ${isProfit ? '' : 'roi-visual-bar__profit--loss'}`;

    // Update labels
    labelInitial.innerHTML = formatCurrencyHtml(totalCost);
    labelProfit.innerHTML = `${isProfit ? '+' : '-'}${formatCurrencyHtml(absProfit)}`;
    labelProfit.className = `roi-bar-label__value ${isProfit ? 'roi-bar-label__value--profit' : 'roi-bar-label__value--loss'}`;
    labelProfitTitle.textContent = isProfit ? __('Profit', 'vareon-calculator-suite-lite') : __('Loss', 'vareon-calculator-suite-lite');
    labelTotal.innerHTML = formatCurrencyHtml(finalValue);

    // Annualized ROI speed metric
    if (annualizedROI !== null) {
      speedMetric.style.display = 'flex';
      annualizedRoiEl.textContent = `${annualizedROI >= 0 ? '+' : ''}${annualizedROI.toFixed(2)}%/${__('year', 'vareon-calculator-suite-lite')}`;
      annualizedRoiEl.className = `roi-speed-metric__value ${isProfit ? 'roi-speed-metric__value--profit' : 'roi-speed-metric__value--loss'}`;
      const durationLabel = durationUnit === 'months'
        ? (durationValue === 1 ? __('month', 'vareon-calculator-suite-lite') : __('months', 'vareon-calculator-suite-lite'))
        : (durationValue === 1 ? __('year', 'vareon-calculator-suite-lite') : __('years', 'vareon-calculator-suite-lite'));
      durationText.textContent = `${durationValue} ${durationLabel}`;
    } else {
      speedMetric.style.display = 'none';
    }

    // Real ROI (inflation-adjusted) - only show if inflation rate is provided
    const roiDecimal = roiPercentage / 100;
    const inflationDecimal = inflationRate / 100;
    const realRoiDecimal = ((1 + roiDecimal) / (1 + inflationDecimal)) - 1;
    const realRoiPercent = realRoiDecimal * 100;
    if (realRoiMetric && realRoiValue && inflationRate > 0) {
      realRoiMetric.style.display = 'flex';
      realRoiValue.textContent = `${realRoiPercent >= 0 ? '+' : ''}${realRoiPercent.toFixed(2)}%`;
      realRoiValue.className = `roi-real-metric__value ${realRoiPercent >= 0 ? 'roi-real-metric__value--profit' : 'roi-real-metric__value--loss'}`;
    } else if (realRoiMetric) {
      realRoiMetric.style.display = 'none';
    }

    // Break-even requirement for losses
    if (!isProfit && breakEvenMetric && breakEvenValue) {
      breakEvenMetric.style.display = 'flex';
      if (finalValue > 0) {
        const requiredPct = (Math.abs(netProfit) / finalValue) * 100;
        breakEvenValue.textContent = sprintf(
          __('You need a +%s gain to recover your losses.', 'vareon-calculator-suite-lite'),
          `${requiredPct.toFixed(2)}%`
        );
      } else {
        breakEvenValue.textContent = __('Recovery requires a new investment because the remaining value is zero.', 'vareon-calculator-suite-lite');
      }
    } else if (breakEvenMetric) {
      breakEvenMetric.style.display = 'none';
    }

    // Cost adjustment note
    if (additionalCosts > 0) {
      costNote.style.display = 'block';
      costNote.innerHTML = `<span class="roi-cost-note__icon">&#128161;</span> ${__('Includes', 'vareon-calculator-suite-lite')} ${formatCurrencyHtml(additionalCosts)} ${__('in additional costs', 'vareon-calculator-suite-lite')}`;
    } else {
      costNote.style.display = 'none';
    }
    showResultsStep();
    refreshTwoStepLayout();
  };

  // Button click handler
  btn.addEventListener('click', (event) => {
    if (!validateRequiredInputs(event)) {
      return;
    }
    calculate();
  });

  // Setup auto-calculation (Pro feature)
  setupAutoCalc(
    container,
    btn,
    [initialInput, finalInput, durationInput, durationUnitSelect, costsInput, inflationInput],
    validateAll
  );

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