import { CLINICAL_THRESHOLDS } from './pkCore.js';
import { t } from './i18n.js';

// The zone colors are deliberately fixed (independent of the interface theme):
// they reproduce the reference gradient of the original KetaPK tool. Only the text
// (zone.textHex) is chosen to remain readable on this opaque background color.
export function updateChartAnnotations(chart, mode, currentYMax) {
  const thresholds = CLINICAL_THRESHOLDS[mode];
  const annotations = {};

  thresholds.zones.forEach((zone, index) => {
    if (zone.min < currentYMax) {
      const zoneMax = zone.max === Infinity ? currentYMax : zone.max;

      annotations[`zone_${index}`] = {
        type: 'box',
        drawTime: 'beforeDraw',
        yMin: zone.min,
        yMax: Math.min(zoneMax, currentYMax),
        backgroundColor: zone.color,
        borderWidth: 0,
        label: {
          display: true,
          content: t(`zones.${zone.zoneKey}`),
          color: zone.textHex,
          font: { size: 11, weight: 'bold' },
          position: 'center'
        }
      };
    }
  });

  chart.options.plugins.annotation.annotations = annotations;
}

export function adjustChartYScale(chart, mode, datasets) {
  let highestValue = 0;

  // Find the maximum value reached among all displayed models
  datasets.forEach(ds => {
    ds.data.forEach(val => {
      if (val > highestValue) highestValue = val;
    });
  });

  // Dynamic adjustment to 110% of the peak value (or floor at 50 ng/mL if empty)
  let targetYMax = highestValue > 0 ? Math.ceil(highestValue * 1.1) : 50;

  chart.options.scales.y.max = targetYMax;
  updateChartAnnotations(chart, mode, targetYMax);
}