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

/**
 * Tip Calculator
 * Calculate tips with preset buttons and bill splitting
 * Compact two-step layout with receipt results
 */

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

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

  // Build the form: 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="tip-form">
            <div class="tip-section vareoncalc-section">
              <div class="tip-section__header vareoncalc-section__header">
                <div class="tip-section__title vareoncalc-section__title">${__('Bill Details', 'vareon-calculator-suite-lite')}</div>
              </div>
              <div class="tip-grid tip-grid--amount">
                <div class="tip-field">
                  <label for="bill-amount">${__('Bill Amount', 'vareon-calculator-suite-lite')}</label>
          <input type="number" id="bill-amount" data-suffix="${currencySymbol}" data-suffix-family="currency" placeholder="50.00" min="0" step="0.01">
                </div>
                <div class="tip-field">
                  <label for="num-people">${__('Number of People', 'vareon-calculator-suite-lite')}</label>
                  <input type="number" id="num-people" placeholder="1" min="1" step="1">
                </div>
              </div>
            </div>

            <div class="tip-section vareoncalc-section">
              <div class="tip-section__header vareoncalc-section__header">
                <div class="tip-section__title vareoncalc-section__title">${__('Tip Percentage', 'vareon-calculator-suite-lite')}</div>
              </div>
              <div class="tip-grid tip-grid--tips">
                <div class="tip-field tip-field--full">
                  <div class="tip-field__label">${__('Tip Presets', 'vareon-calculator-suite-lite')}</div>
                  <div class="vareoncalc-tip-presets" role="group" aria-label="${__('Tip presets', 'vareon-calculator-suite-lite')}">
                    <button type="button" class="tip-preset" data-tip="10">10%</button>
                    <button type="button" class="tip-preset" data-tip="15">15%</button>
                    <button type="button" class="tip-preset tip-preset--active" data-tip="18">18%</button>
                    <button type="button" class="tip-preset" data-tip="20">20%</button>
                  </div>
                </div>
                <div class="tip-field tip-field--full">
                  <label for="tip-percent">${__('Custom Tip', 'vareon-calculator-suite-lite')}</label>
                  <input type="number" id="tip-percent" data-suffix="%" placeholder="18" min="0" max="100" step="0.5">
                </div>
              </div>
            </div>
          </div>

          <div class="tip-actions">
            <button type="button" class="vareoncalc-btn" id="calc-btn" data-two-step-next>${__('Calculate Tip', '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-panel-result--placeholder" id="result-panel">
            <div class="placeholder-icon">&#127860;</div>
            <div class="placeholder-text">${__('Enter your bill to see the tip breakdown', '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 billAmountInput = container.querySelector('#bill-amount');
  const tipPercentInput = container.querySelector('#tip-percent');
  const numPeopleInput = container.querySelector('#num-people');
  [billAmountInput, tipPercentInput].forEach((input) => {
    input?.closest('.vareoncalc-input-adorned')?.classList.add('vareoncalc-input-adorned--suffix-rail');
  });
  const btn = container.querySelector('#calc-btn');
  const resultPanel = container.querySelector('#result-panel');
  const presetButtons = container.querySelectorAll('.tip-preset');
  let smartRoundingDismissed = false;
  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 billPlaceholder = formatNumber(50, {
    decimals: formatting.currencyDecimals,
    maxDecimals: formatting.currencyDecimals,
    forceDecimals: formatting.currencyDecimals > 0,
  });
  billAmountInput.placeholder = billPlaceholder;
  tipPercentInput.placeholder = formatNumber(18, {
    decimals: percentDecimals,
    maxDecimals: percentDecimals,
    trimTrailingZeros: true,
  });

  // Set default tip value
  tipPercentInput.value = '18';
  const canProceed = () => {
    const billAmount = Number(billAmountInput.value);
    const tipPercent = Number(tipPercentInput.value);
    const numPeople = Number.parseInt(numPeopleInput.value, 10) || 1;
    if (!Number.isFinite(billAmount) || billAmount <= 0) return false;
    if (!Number.isFinite(tipPercent) || tipPercent < 0 || tipPercent > 100) return false;
    if (numPeople < 1) return false;
    return true;
  };

  // Update preset button visual state
  function updatePresetState(activeValue) {
    const activeNumber = Number(activeValue);
    const hasActive = Number.isFinite(activeNumber);
    presetButtons.forEach(b => {
      const btnValue = Number(b.getAttribute('data-tip'));
      const isActive = hasActive && Number.isFinite(btnValue) && btnValue === activeNumber;
      b.classList.toggle('tip-preset--active', isActive);
    });
  }

  // Preset button handlers
  presetButtons.forEach(button => {
    button.addEventListener('click', () => {
      const tipValue = button.getAttribute('data-tip');
      smartRoundingDismissed = false;
      tipPercentInput.value = tipValue;

      // Update visual state
      updatePresetState(tipValue);

      // Auto-calculate if bill amount exists and auto-calc is enabled
      if (billAmountInput.value && shouldAutoCalculate(container)) {
        btn.click();
      }
    });
  });

  // Sync presets when custom input changes
  tipPercentInput.addEventListener('input', () => {
    const value = tipPercentInput.value;
    smartRoundingDismissed = false;
    updatePresetState(value);
  });

  billAmountInput.addEventListener('input', () => {
    smartRoundingDismissed = false;
  });

  numPeopleInput.addEventListener('input', () => {
    smartRoundingDismissed = false;
  });

  // Calculate function
  function calculate(event = null) {
    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 billAmount = Number(billAmountInput.value);
    const tipPercent = Number(tipPercentInput.value);
    const numPeople = Number.parseInt(numPeopleInput.value, 10) || 1;

    // Validation
    if (!Number.isFinite(billAmount) || billAmount <= 0) {
      recordInvalid(
        billAmountInput,
        __('Please enter a valid bill amount.', 'vareon-calculator-suite-lite'),
        {
          validator: () => {
            const value = Number(billAmountInput.value);
            return Number.isFinite(value) && value > 0;
          },
        }
      );
    }

    if (!Number.isFinite(tipPercent) || tipPercent < 0 || tipPercent > 100) {
      recordInvalid(
        tipPercentInput,
        __('Please enter a valid tip percentage (0-100%).', 'vareon-calculator-suite-lite'),
        {
          validator: () => {
            const value = Number(tipPercentInput.value);
            return Number.isFinite(value) && value >= 0 && value <= 100;
          },
        }
      );
    }

    if (numPeople < 1) {
      recordInvalid(
        numPeopleInput,
        __('Number of people must be at least 1.', 'vareon-calculator-suite-lite'),
        {
          validator: () => {
            const value = Number.parseInt(numPeopleInput.value, 10);
            return Number.isFinite(value) && value >= 1;
          },
        }
      );
    }

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

    // Calculate tip
    const tipAmount = (billAmount * tipPercent) / 100;
    const totalAmount = billAmount + tipAmount;
    const perPersonTotal = totalAmount / numPeople;
    const withGrouping = { useGrouping: true };
    const formattedBillAmount = formatCurrencyHtml(billAmount, withGrouping);
    const formattedTipAmount = formatCurrencyHtml(tipAmount, withGrouping);
    const formattedTotalAmount = formatCurrencyHtml(totalAmount, withGrouping);
    const formattedPerPersonTotal = formatCurrencyHtml(perPersonTotal, withGrouping);
    const formattedTipPercent = formatNumber(tipPercent, {
      decimals: percentDecimals,
      maxDecimals: percentDecimals,
      trimTrailingZeros: true,
      useGrouping: true,
    });
    const tipPercentLabel = `${formattedTipPercent}%`;
    const isSplit = numPeople > 1;
    // Top headline is ALWAYS the grand total
    const formattedHeadlineAmount = formatCurrencyHtml(totalAmount, withGrouping);
    const headlineLabel = __('Total Bill', 'vareon-calculator-suite-lite');

    // Tip proportion for visual bar
    const tipFraction = totalAmount > 0 ? Math.round((tipAmount / totalAmount) * 100) : 0;
    const billFraction = 100 - tipFraction;

    // Update the receipt panel with structured layout
    if (resultPanel) {
      resultPanel.className = 'vareoncalc-panel-result';
      resultPanel.innerHTML = `
        <div class="tip-results__hero">
          <div class="tip-results__eyebrow">${headlineLabel}</div>
          <div class="tip-results__amount">${formattedHeadlineAmount}</div>
          <div class="tip-results__bar" aria-hidden="true">
            <div class="tip-results__bar-bill" style="width:${billFraction}%"></div>
            <div class="tip-results__bar-tip" style="width:${tipFraction}%"></div>
          </div>
          <div class="tip-results__bar-legend" aria-hidden="true">
            <span class="tip-results__bar-legend-item tip-results__bar-legend-item--bill">
              <span class="tip-results__legend-dot tip-results__legend-dot--bill"></span>
              ${__('Bill', 'vareon-calculator-suite-lite')}
            </span>
            <span class="tip-results__bar-legend-item tip-results__bar-legend-item--tip">
              <span class="tip-results__legend-dot tip-results__legend-dot--tip"></span>
              ${__('Tip', 'vareon-calculator-suite-lite')} ${tipPercentLabel}
            </span>
          </div>
        </div>
        <div class="tip-results__details">
          <div class="tip-results__row">
            <span class="tip-results__row-label">${__('Subtotal', 'vareon-calculator-suite-lite')}</span>
            <span class="tip-results__row-value">${formattedBillAmount}</span>
          </div>
          <div class="tip-results__row tip-results__row--accent">
            <span class="tip-results__row-label">${__('Tip', 'vareon-calculator-suite-lite')} (${tipPercentLabel})</span>
            <span class="tip-results__row-value">+${formattedTipAmount}</span>
          </div>
          <div class="tip-results__divider"></div>
          <div class="tip-results__row tip-results__row--total">
            <span class="tip-results__row-label">${__('Total', 'vareon-calculator-suite-lite')}</span>
            <span class="tip-results__row-value">${formattedHeadlineAmount}</span>
          </div>
        </div>
        <div class="tip-results__rounding" id="smart-rounding-section" style="display:none;">
          <div class="tip-results__rounding-label">${__('Quick Rounding', 'vareon-calculator-suite-lite')}</div>
          <div class="tip-results__rounding-btns">
            <button type="button" class="tip-results__round-btn" id="btn-round-tip">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M12 2v20M2 12h20"/></svg>
              ${__('Round Tip', 'vareon-calculator-suite-lite')} <span id="round-tip-val"></span>
            </button>
            <button type="button" class="tip-results__round-btn" id="btn-round-total">
              <svg width="14" height="14" 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="M12 6v12M6 12h12"/></svg>
              ${__('Round Total', 'vareon-calculator-suite-lite')} <span id="round-total-val"></span>
            </button>
          </div>
        </div>
        <div class="tip-results__split">
          <div class="tip-results__split-main">
            <div class="tip-results__split-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="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><path d="M22 21v-2a4 4 0 0 0-3-3.87"/><path d="M16 3.13a4 4 0 0 1 0 7.75"/></svg>
            </div>
            <div class="tip-results__split-content">
              <div class="tip-results__split-amount">${formattedPerPersonTotal}</div>
              <div class="tip-results__split-label">${__('per person', 'vareon-calculator-suite-lite')}</div>
            </div>
          </div>
          <div class="tip-results__split-adjust">
            <button type="button" class="tip-results__adj-btn" id="adjust-people-minus" aria-label="${__('Decrease people', 'vareon-calculator-suite-lite')}" ${numPeople <= 1 ? 'disabled' : ''}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M5 12h14"/></svg>
            </button>
            <span class="tip-results__adj-count">${formatNumber(numPeople, {
              decimals: 0,
              maxDecimals: 0,
              trimTrailingZeros: true,
              useGrouping: true,
            })}</span>
            <button type="button" class="tip-results__adj-btn" id="adjust-people-plus" aria-label="${__('Increase people', 'vareon-calculator-suite-lite')}">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M12 5v14M5 12h14"/></svg>
            </button>
          </div>
          <div class="tip-results__footer">
            <button type="button" class="tip-results__copy-btn" id="copy-breakdown-btn">
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="9" y="9" width="13" height="13" rx="2" ry="2"/><path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"/></svg>
              ${__('Copy', 'vareon-calculator-suite-lite')}
            </button>
          </div>
        </div>
      `;

      const smartRoundingSection = resultPanel.querySelector('#smart-rounding-section');
      const roundTipValue = resultPanel.querySelector('#round-tip-val');
      const roundTotalValue = resultPanel.querySelector('#round-total-val');
      const roundTipButton = resultPanel.querySelector('#btn-round-tip');
      const roundTotalButton = resultPanel.querySelector('#btn-round-total');
      const roundedTip = Math.ceil(tipAmount);
      const roundedTotal = Math.ceil(totalAmount);
      const roundingEpsilon = 1e-9;
      const shouldOfferSmartRounding = Math.abs(roundedTip - tipAmount) > roundingEpsilon
        || Math.abs(roundedTotal - totalAmount) > roundingEpsilon;
      const showSmartRounding = shouldOfferSmartRounding && !smartRoundingDismissed;

      if (smartRoundingSection) {
        smartRoundingSection.style.display = showSmartRounding ? 'block' : 'none';
      }

      if (showSmartRounding && roundTipValue && roundTotalValue && roundTipButton && roundTotalButton) {
        roundTipValue.textContent = formatCurrency(roundedTip, withGrouping);
        roundTotalValue.textContent = formatCurrency(roundedTotal, withGrouping);

        roundTipButton.onclick = () => {
          const newTipPercent = (roundedTip / billAmount) * 100;
          if (!Number.isFinite(newTipPercent)) {
            return;
          }
          smartRoundingDismissed = true;
          tipPercentInput.value = String(Math.round(newTipPercent * 100) / 100);
          updatePresetState(tipPercentInput.value);
          calculate();
        };

        roundTotalButton.onclick = () => {
          const newTipAmount = roundedTotal - billAmount;
          const newTipPercent = (newTipAmount / billAmount) * 100;
          if (!Number.isFinite(newTipPercent)) {
            return;
          }
          smartRoundingDismissed = true;
          tipPercentInput.value = String(Math.round(newTipPercent * 100) / 100);
          updatePresetState(tipPercentInput.value);
          calculate();
        };
      }

      const adjustMinus = resultPanel.querySelector('#adjust-people-minus');
      const adjustPlus = resultPanel.querySelector('#adjust-people-plus');
      const copyBtn = resultPanel.querySelector('#copy-breakdown-btn');

      if (adjustMinus && adjustPlus) {
        adjustMinus.onclick = () => {
          if (numPeople > 1) {
            numPeopleInput.value = numPeople - 1;
            smartRoundingDismissed = false;
            calculate();
          }
        };
        adjustPlus.onclick = () => {
          numPeopleInput.value = numPeople + 1;
          smartRoundingDismissed = false;
          calculate();
        };
      }

      if (copyBtn) {
        copyBtn.onclick = () => {
          const text = `${__('Total is', 'vareon-calculator-suite-lite')} ${formatCurrency(totalAmount, withGrouping)}. ${__('With', 'vareon-calculator-suite-lite')} ${tipPercentLabel} ${__('tip, we each owe', 'vareon-calculator-suite-lite')} ${formatCurrency(perPersonTotal, withGrouping)}.`;
          navigator.clipboard.writeText(text).then(() => {
            const originalHtml = copyBtn.innerHTML;
            copyBtn.innerHTML = `<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6 9 17l-5-5"/></svg> ${__('Copied!', 'vareon-calculator-suite-lite')}`;
            setTimeout(() => {
              if (resultPanel.contains(copyBtn)) {
                copyBtn.innerHTML = originalHtml;
              }
            }, 2000);
          }).catch(() => {
            ValidationHelpers.showToast(container, __('Could not copy to clipboard.', 'vareon-calculator-suite-lite'));
          });
        };
      }
    }

    showResultsStep();
    refreshTwoStepLayout();
  }

  btn.addEventListener('click', (event) => calculate(event));

  // Auto-calculate on input change (only if global setting is enabled)
  setupAutoCalc(
    container,
    btn,
    [billAmountInput, tipPercentInput, numPeopleInput],
    canProceed
  );

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