import { CalculatorEngine } from './pkCore.js';

export function initCalculatorUI() {
  const modal = document.getElementById('modalCalc');
  const btnOpen = document.getElementById('btnOpenCalc');
  const btnClose = document.getElementById('btnCloseCalc');

  if (!modal || !btnOpen || !btnClose) return;

  btnOpen.addEventListener('click', () => {
    // Uses patientWeight instead of inputWeight
    const mainWeight = document.getElementById('patientWeight')?.value || 70;
    const calcWeightInput = document.getElementById('calcWeight');
    if (calcWeightInput) calcWeightInput.value = mainWeight;

    modal.classList.remove('hidden');
  });

  btnClose.addEventListener('click', () => {
    modal.classList.add('hidden');
  });

  modal.addEventListener('click', (e) => {
    if (e.target === modal) {
      modal.classList.add('hidden');
    }
  });

  const calcWeightInput = document.getElementById('calcWeight');
  const mgInput = document.getElementById('calcMg');
  const mgKgInput = document.getElementById('calcMgKg');
  const mgKgHInput = document.getElementById('calcMgKgH');
  const ugKgMinInput = document.getElementById('calcUgKgMin');

  const getWeight = () => parseFloat(calcWeightInput.value) || 70;

  mgInput?.addEventListener('input', () => {
    const mg = parseFloat(mgInput.value);
    mgKgInput.value = isNaN(mg) ? '' : (mg / getWeight()).toFixed(2);
  });

  mgKgInput?.addEventListener('input', () => {
    const mgKg = parseFloat(mgKgInput.value);
    mgInput.value = isNaN(mgKg) ? '' : (mgKg * getWeight()).toFixed(1);
  });

  mgKgHInput?.addEventListener('input', () => {
    const mgKgH = parseFloat(mgKgHInput.value);
    ugKgMinInput.value = isNaN(mgKgH) ? '' : CalculatorEngine.mgKgHToMicrogKgMin(mgKgH).toFixed(1);
  });

  ugKgMinInput?.addEventListener('input', () => {
    const ug = parseFloat(ugKgMinInput.value);
    mgKgHInput.value = isNaN(ug) ? '' : CalculatorEngine.microgKgMinToMgKgH(ug).toFixed(2);
  });
}