var bhutaniCache = null;
var aapCache = null;

export function loadAapBilirubinThresholds() {
  if (aapCache) return Promise.resolve(aapCache);
  return fetch('/data/calculators/aap-bilirubin-thresholds.json', { credentials: 'same-origin' })
    .then(function(response) {
      if (!response.ok) throw new Error('Failed to load AAP bilirubin threshold data');
      return response.json();
    })
    .then(function(data) {
      aapCache = data;
      return aapCache;
    });
}

function pickGestationalAgeTable(tables, gaWeeks, maxWeek) {
  var ga = Math.max(35, Math.min(maxWeek, parseInt(gaWeeks, 10)));
  return tables[String(ga)];
}

export function selectAapBilirubinThresholdTables(thresholds, gaWeeks, risk) {
  var hasRiskFactors = risk === 'medium';
  return {
    phototherapy: hasRiskFactors
      ? pickGestationalAgeTable(thresholds.phototherapy.risk, gaWeeks, 38)
      : pickGestationalAgeTable(thresholds.phototherapy.noRisk, gaWeeks, 40),
    exchange: hasRiskFactors
      ? pickGestationalAgeTable(thresholds.exchange.risk, gaWeeks, 38)
      : pickGestationalAgeTable(thresholds.exchange.noRisk, gaWeeks, 38)
  };
}

export function calculateAapBilirubinAssessment(thresholds, gaWeeks, hours, tsb, risk) {
  var tables = selectAapBilirubinThresholdTables(thresholds, gaWeeks, risk);
  var phototherapyThreshold = interpolateThreshold(tables.phototherapy, hours);
  var exchangeThreshold = interpolateThreshold(tables.exchange, hours);
  var aboveExchange = tsb >= exchangeThreshold;
  var abovePhototherapy = tsb >= phototherapyThreshold;
  return {
    phototherapyTable: tables.phototherapy,
    exchangeTable: tables.exchange,
    phototherapyThreshold: phototherapyThreshold,
    exchangeThreshold: exchangeThreshold,
    phototherapyMargin: tsb - phototherapyThreshold,
    exchangeMargin: tsb - exchangeThreshold,
    abovePhototherapy: abovePhototherapy,
    aboveExchange: aboveExchange,
    status: aboveExchange ? 'exchange' : (abovePhototherapy ? 'phototherapy' : 'below')
  };
}

export function loadBhutaniZones() {
  if (bhutaniCache) return Promise.resolve(bhutaniCache);
  return fetch('/data/calculators/bhutani-zones.json', { credentials: 'same-origin' })
    .then(function(response) {
      if (!response.ok) throw new Error('Failed to load Bhutani zone data');
      return response.json();
    })
    .then(function(data) {
      bhutaniCache = data.zones || {};
      return bhutaniCache;
    });
}

export function interpolateThreshold(table, hours) {
  var keys = Object.keys(table).map(Number).sort(function(a,b){return a-b;});
  if (hours <= keys[0]) return table[keys[0]];
  if (hours >= keys[keys.length-1]) return table[keys[keys.length-1]];
  for (var i = 0; i < keys.length-1; i++) {
    if (hours >= keys[i] && hours <= keys[i+1]) {
      var t = (hours - keys[i]) / (keys[i+1] - keys[i]);
      return table[keys[i]] + t * (table[keys[i+1]] - table[keys[i]]);
    }
  }
  return table[keys[0]];
}

export function classifyBhutaniRisk(zones, hours, tsb) {
  var p95 = interpolateThreshold(zones.p95, hours);
  var p75 = interpolateThreshold(zones.p75, hours);
  var p40 = interpolateThreshold(zones.p40, hours);
  if (tsb >= p95) return { zone: 'High-Risk Zone', color: '#ef4444', bg: '#fee2e2', p95: p95, p75: p75, p40: p40 };
  if (tsb >= p75) return { zone: 'High-Intermediate Zone', color: '#f97316', bg: '#ffedd5', p95: p95, p75: p75, p40: p40 };
  if (tsb >= p40) return { zone: 'Low-Intermediate Zone', color: '#f59e0b', bg: '#fef3c7', p95: p95, p75: p75, p40: p40 };
  return { zone: 'Low-Risk Zone', color: '#10b981', bg: '#d1fae5', p95: p95, p75: p75, p40: p40 };
}
