const TAX_PERIODS = {
  2024: {
    year: 2024,
    nczdFull: 5646.48,
    nczdLimit: 24952.06,
    nczdFormulaBase: 11884.50,
    employeeBands: [
      { upTo: 47537.98, rate: 0.19 },
      { upTo: Infinity, rate: 0.25 }
    ],
    businessReducedLimit: 60000,
    businessBands: [
      { upTo: 47537.98, rate: 0.19 },
      { upTo: Infinity, rate: 0.25 }
    ],
    source: 'Parametre odvodené zo životného minima 268,88 € platného k 1.1.2024.'
  },
  2025: {
    year: 2025,
    nczdFull: 5753.79,
    nczdLimit: 25426.27,
    nczdFormulaBase: 12110.36,
    employeeBands: [
      { upTo: 48441.43, rate: 0.19 },
      { upTo: Infinity, rate: 0.25 }
    ],
    businessReducedLimit: 100000,
    businessBands: [
      { upTo: 48441.43, rate: 0.19 },
      { upTo: Infinity, rate: 0.25 }
    ],
    source: 'Finančná správa SR: NČZD 5 753,79 €, hranica 19 % sadzby 48 441,43 €, 15 % pre § 6 do 100 000 €.'
  },
  2026: {
    year: 2026,
    nczdFull: 5966.73,
    nczdLimit: 26367.28,
    nczdFormulaBase: 12558.55,
    employeeBands: [
      { upTo: 43983.32, rate: 0.19 },
      { upTo: 60349.21, rate: 0.25 },
      { upTo: 75010.32, rate: 0.30 },
      { upTo: Infinity, rate: 0.35 }
    ],
    businessReducedLimit: 100000,
    businessBands: [
      { upTo: 43983.32, rate: 0.19 },
      { upTo: 60349.21, rate: 0.25 },
      { upTo: 75010.32, rate: 0.30 },
      { upTo: Infinity, rate: 0.35 }
    ],
    source: 'Parametre pre priebežný výpočet 2026; pred podaním overte finálne tlačivo a poučenie Finančnej správy SR.'
  }
};

let lastCalculation = null;

function num(id) {
  return parseFloat(document.getElementById(id)?.value) || 0;
}

function money(value) {
  return `${roundCents(value).toFixed(2)} €`;
}

function roundCents(value) {
  return Math.round((Number(value) + Number.EPSILON) * 100) / 100;
}

function activeForm() {
  return document.querySelector('.tab.active').dataset.form;
}

function getPeriod() {
  const year = document.getElementById('obdobie')?.value || '2025';
  return TAX_PERIODS[year] || TAX_PERIODS[2025];
}

function computeNczd(base, period, mode, manualValue) {
  if (mode === 'none') return 0;
  if (mode === 'manual') return Math.min(Math.max(manualValue, 0), Math.max(base, 0));
  if (base <= 0) return 0;
  if (base <= period.nczdLimit) return Math.min(period.nczdFull, base);
  return Math.min(Math.max(period.nczdFormulaBase - (base / 4), 0), base);
}

function taxFromBands(base, bands) {
  let remaining = Math.max(base, 0);
  let previousLimit = 0;
  let tax = 0;
  const details = [];

  bands.forEach(band => {
    if (remaining <= 0) return;
    const bandSize = band.upTo === Infinity ? remaining : Math.max(band.upTo - previousLimit, 0);
    const taxedBase = Math.min(remaining, bandSize);
    const bandTax = taxedBase * band.rate;
    tax += bandTax;
    details.push({
      base: roundCents(taxedBase),
      rate: band.rate,
      tax: roundCents(bandTax)
    });
    remaining -= taxedBase;
    previousLimit = band.upTo;
  });

  return { tax: roundCents(tax), details };
}

function calculateData() {
  const form = activeForm();
  const period = getPeriod();
  let income = 0;
  let expenses = 0;
  let loss = 0;
  let advances = 0;
  let nczdMode = 'auto';
  let manualNczd = 0;
  let taxBasisType = 'employee';

  if (form === 'A') {
    income = num('a_prijmy');
    expenses = num('a_poistne');
    advances = num('a_preddavky');
    nczdMode = document.getElementById('a_nczd_rezim')?.value || 'auto';
    manualNczd = num('a_nczd');
  } else {
    income = num('b_prijmy');
    expenses = num('b_vydavky');
    loss = num('b_strata');
    advances = num('b_preddavky');
    nczdMode = document.getElementById('b_nczd_rezim')?.value || 'auto';
    manualNczd = num('b_nczd');
    taxBasisType = 'business';
  }

  const partialBase = Math.max(income - expenses, 0);
  const nczd = computeNczd(partialBase, period, nczdMode, manualNczd);
  const taxBase = Math.max(partialBase - nczd - loss, 0);
  const useReducedBusinessRate = form === 'B' && income <= period.businessReducedLimit;
  const bands = form === 'B' && useReducedBusinessRate
    ? [{ upTo: Infinity, rate: 0.15 }]
    : (taxBasisType === 'business' ? period.businessBands : period.employeeBands);
  const taxResult = taxFromBands(taxBase, bands);
  const settlement = roundCents(taxResult.tax - advances);

  return {
    form,
    period,
    income: roundCents(income),
    expenses: roundCents(expenses),
    loss: roundCents(loss),
    advances: roundCents(advances),
    partialBase: roundCents(partialBase),
    nczd: roundCents(nczd),
    taxBase: roundCents(taxBase),
    tax: taxResult.tax,
    settlement,
    isOverpayment: settlement < 0,
    bands: taxResult.details,
    useReducedBusinessRate
  };
}

function getCalculation() {
  return lastCalculation || calculateData();
}

function calculate() {
  const result = calculateData();
  lastCalculation = result;

  document.getElementById('ciastkovyZaklad').textContent = money(result.partialBase);
  document.getElementById('uplatnenaNczd').textContent = money(result.nczd);
  document.getElementById('zaklad').textContent = money(result.taxBase);
  document.getElementById('dan').textContent = money(result.tax);
  document.getElementById('preddavky').textContent = money(result.advances);
  document.getElementById('vysledokUhrady').textContent = money(Math.abs(result.settlement));
  document.getElementById('settlementLabel').firstChild.textContent = result.isOverpayment ? 'Preplatok: ' : 'Na úhradu: ';

  const bandText = result.bands
    .map(item => `${money(item.base)} x ${(item.rate * 100).toFixed(0)} % = ${money(item.tax)}`)
    .join(', ');
  const businessNote = result.useReducedBusinessRate
    ? ` Uplatnená znížená sadzba 15 %, keďže príjmy podľa § 6 nepresiahli ${money(result.period.businessReducedLimit)}.`
    : '';

  document.getElementById('calculationNote').textContent =
    `Obdobie ${result.period.year}: ${bandText || 'bez zdaniteľného základu'}.${businessNote} ${result.period.source}`;

  renderPdfForm(result);
}
