function switchForm(type) {
  document.getElementById('formA').classList.toggle('hidden', type !== 'A');
  document.getElementById('formB').classList.toggle('hidden', type !== 'B');

  document.querySelectorAll('.tab').forEach(tab => {
    tab.classList.toggle('active', tab.dataset.form === type);
  });

  calculate();
}

function syncPeriodDates() {
  const year = document.getElementById('obdobie').value;
  document.getElementById('obdobie_od').value = `${year}-01-01`;
  document.getElementById('obdobie_do').value = `${year}-12-31`;
}

document.addEventListener('DOMContentLoaded', () => {
  loadData();

  document.querySelectorAll('.tab').forEach(tab => {
    tab.addEventListener('click', () => switchForm(tab.dataset.form));
  });

  document.querySelectorAll('input, select').forEach(input => {
    input.addEventListener('input', calculate);
    input.addEventListener('change', calculate);
    input.addEventListener('blur', () => validateField(input));
    input.addEventListener('focus', () => {
      const help = input.dataset.help || 'Zadajte hodnotu do poľa.';
      document.getElementById('helpBox').textContent = help;
    });
  });

  document.getElementById('obdobie').addEventListener('change', () => {
    syncPeriodDates();
    calculate();
  });

  document.getElementById('calcBtn').addEventListener('click', calculate);
  document.getElementById('saveBtn').addEventListener('click', saveData);
  document.getElementById('exportBtn').addEventListener('click', exportJSON);
  document.getElementById('xmlBtn').addEventListener('click', exportXML);
  document.getElementById('printBtn').addEventListener('click', () => {
    calculate();
    window.print();
  });

  const fileInput = document.getElementById('fileInput');
  document.getElementById('importBtn').addEventListener('click', () => fileInput.click());
  fileInput.addEventListener('change', e => {
    if (e.target.files[0]) importJSON(e.target.files[0]);
  });

  calculate();
});
