function anzahlHitzetage(data, threshold) {
  const byYear = d3.group(data, d => d.Jahr);
  return Array.from(byYear, ([Jahr, days]) => ({
    Jahr,
    Hitzetage: days.filter(d => d.tlmax >= threshold).length
  }));
}

function maxHitzeperiode(data, threshold) {
  const byYear = d3.group(data, d => d.Jahr);
  return Array.from(byYear, ([Jahr, days]) => {
    let maxRun = 0, currentRun = 0;
    for (const d of days) {
      if (d.tlmax >= threshold) { currentRun++; maxRun = Math.max(maxRun, currentRun); }
      else { currentRun = 0; }
    }
    return { Jahr, Hitzeperiode: maxRun };
  });
}
viewof schwelle = Inputs.range([25, 39], {
  value: 30,
  step: 0.5,
  label: "Schwellenwert Hitzetage (°C)"
})
combined = {
  const hitzetage = anzahlHitzetage(transpose(hw_data), schwelle);
  const perioden = maxHitzeperiode(transpose(hw_data), schwelle);
  const periodenMap = new Map(perioden.map(d => [d.Jahr, d.Hitzeperiode]));
  return hitzetage.map(d => ({
    ...d,
    Hitzeperiode: periodenMap.get(d.Jahr) ?? 0
  }));
}
Plot.plot({
  style: { fontSize: "20px" },
  marginLeft: 70,
  marginTop: 40,
  marginBottom: 50,
  marks: [
    Plot.barY(combined, { x: "Jahr", y: "Hitzetage", fill: "firebrick" }),
    Plot.tip(combined, Plot.pointerX({ x: "Jahr", y: "Hitzetage",
      title: d => `${d.Jahr}\nHitzetage: ${d.Hitzetage}\nLängste Hitzeperiode: ${d.Hitzeperiode} Tage`
    }))
  ],
  x: { tickFormat: "d", label: "Jahr", ticks: [...d3.range(1950, 2026, 10), 2026] },
  y: { label: "Anzahl Hitzetage", tickFormat: d => Number.isInteger(d) ? d : "" }
})
Plot.plot({
  style: { fontSize: "20px" },
  marginLeft: 70,
  marginTop: 40,
  marginBottom: 50,
  marks: [
    Plot.barY(combined, { x: "Jahr", y: "Hitzeperiode", fill: "firebrick" }),
    Plot.tip(combined, Plot.pointerX({ x: "Jahr", y: "Hitzeperiode",
      title: d => `${d.Jahr}\nHitzetage: ${d.Hitzetage}\nLängste Hitzeperiode: ${d.Hitzeperiode} Tage`
    }))
  ],
  x: { tickFormat: "d", label: "Jahr", ticks: [...d3.range(1950, 2026, 10), 2026] },
  y: { label: "Längste Hitzeperiode (Tage)", tickFormat: d => Number.isInteger(d) ? d : "" }
})