var growthCache = null;

export function loadGrowthLmsData() {
  if (growthCache) return Promise.resolve(growthCache);
  return fetch('/data/calculators/growth-lms.json', { credentials: 'same-origin' })
    .then(function(response) {
      if (!response.ok) throw new Error('Failed to load growth LMS data');
      return response.json();
    })
    .then(function(data) {
      growthCache = data.lms || {};
      return growthCache;
    });
}

export function interpolateLMS(lmsTable, val) {
  var keys = Object.keys(lmsTable).map(Number).sort(function(a,b){return a-b;});
  if (val <= keys[0]) return lmsTable[keys[0]];
  if (val >= keys[keys.length-1]) return lmsTable[keys[keys.length-1]];
  for (var i = 0; i < keys.length - 1; i++) {
    if (val >= keys[i] && val <= keys[i+1]) {
      var t = (val - keys[i]) / (keys[i+1] - keys[i]);
      var a = lmsTable[keys[i]], b = lmsTable[keys[i+1]];
      return { L: a.L + t*(b.L-a.L), M: a.M + t*(b.M-a.M), S: a.S + t*(b.S-a.S) };
    }
  }
  return lmsTable[keys[0]];
}

export function normalCDF(z) {
  var a1=0.254829592, a2=-0.284496736, a3=1.421413741, a4=-1.453152027, a5=1.061405429, p=0.3275911;
  var sign = z < 0 ? -1 : 1;
  z = Math.abs(z) / Math.sqrt(2);
  var t = 1 / (1 + p * z);
  var y = 1 - (((((a5*t+a4)*t)+a3)*t+a2)*t+a1)*t*Math.exp(-z*z);
  return 0.5 * (1 + sign * y);
}

export function valueFromLMS(L, M, S, z) {
  if (Math.abs(L) < 0.001) return M * Math.exp(S * z);
  return M * Math.pow(1 + L * S * z, 1 / L);
}

export function calcZFromLMS(value, L, M, S) {
  if (Math.abs(L) < 0.001) return Math.log(value / M) / S;
  return (Math.pow(value / M, L) - 1) / (L * S);
}

export function calculateLmsPercentile(lmsTable, x, value) {
  var lms = interpolateLMS(lmsTable, x);
  var z = calcZFromLMS(value, lms.L, lms.M, lms.S);
  return { lms: lms, z: z, percentile: normalCDF(z) * 100 };
}

export function calcMidParentalHeight(motherHt, fatherHt, sex) {
  if (!motherHt || !fatherHt) return null;
  var mph = sex === 'male' ? (motherHt + fatherHt + 13) / 2 : (motherHt + fatherHt - 13) / 2;
  return { target: mph, low: mph - 8.5, high: mph + 8.5 };
}

export function renderGrowthResult(label, value, unit, z, percentile) {
  var pctl = (Math.round(percentile * 100) / 100).toFixed(2);
  var cl;
  if (pctl >= 95 || pctl <= 5) cl = { color: '#f59e0b', bg: '#fef3c7', text: pctl <= 5 ? 'Below 5th percentile' : 'Above 95th percentile' };
  else if (pctl >= 85 || pctl <= 15) cl = { color: '#f97316', bg: '#ffedd5', text: pctl + 'th percentile' };
  else cl = { color: '#10b981', bg: '#d1fae5', text: pctl + 'th percentile' };

  return '<div class="calc-result-header" style="background:' + cl.bg + ';border-color:' + cl.color + ';">' +
    '<div style="font-size:18px;font-weight:700;color:' + cl.color + ';">' + cl.text + '</div>' +
    '<div style="font-size:13px;color:var(--g600);margin-top:4px;">' + label + ': ' + value + ' ' + unit + '</div>' +
  '</div>' +
  '<div class="calc-result-grid">' +
    '<div class="calc-result-item"><div class="calc-result-label">Percentile</div><div class="calc-result-value">' + pctl + '<span style="font-size:12px;">th</span></div></div>' +
    '<div class="calc-result-item"><div class="calc-result-label">Z-Score</div><div class="calc-result-value" style="font-size:16px;">' + z.toFixed(2) + '</div></div>' +
  '</div>';
}
