aboutsummaryrefslogtreecommitdiff
path: root/web/app.js
blob: 64689433ce623ec7da8b61d01ed7b1ff948c71df (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
"use strict";

const $ = (id) => document.getElementById(id);
const MONTH_DAYS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
const MONTH_NAMES = ["Jan", "Feb", "Mär", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"];
const HOUR_MONTH = new Uint8Array(8760);
{
  let h = 0;
  MONTH_DAYS.forEach((days, m) => { HOUR_MONTH.fill(m, h, h + days * 24); h += days * 24; });
}

// constant source temperature of ground and water heat pumps, and their Carnot efficiency
const SOURCE = { brine: [0, 0.68], water: [10, 0.68], dx: [-2, 0.68] };
const K = 273.15;

// Carnot COP between condensing (5 K above flow) and evaporating (6 K below source) temperature
const carnot = (flow, source) => (flow + 5 + K) / (flow + 5 - (source - 6));
const COP_MAX = 6.5;

function interp(points, x) {
  if (x <= points[0][0]) return points[0][1];
  for (let i = 1; i < points.length; i++) {
    const [x0, y0] = points[i - 1], [x1, y1] = points[i];
    if (x <= x1) return y0 + ((y1 - y0) * (x - x0)) / (x1 - x0);
  }
  return points[points.length - 1][1];
}

/** Interpolate a device table ({35: points, 45: points, 55: points}) in outdoor and flow temperature. */
function interpFlow(table, t, flow) {
  const f = Math.min(55, Math.max(35, flow));
  const f0 = f >= 45 ? 45 : 35, f1 = f0 + 10;
  const v0 = interp(table[f0], t), v1 = interp(table[f1], t);
  return v0 + ((v1 - v0) * (f - f0)) / (f1 - f0);
}

/** Device COP; outside the datasheet range it is scaled with the Carnot COP. */
function deviceCop(dev, t, flow) {
  const points = dev.cop[35];
  const tc = Math.min(points[points.length - 1][0], Math.max(points[0][0], t));
  const fc = Math.min(55, Math.max(35, flow));
  return Math.min(COP_MAX, (interpFlow(dev.cop, tc, fc) * carnot(flow, t)) / carnot(fc, tc));
}

// Backup heating fuels, energy content as lower heating value. `perPrice` is the energy in
// kWh bought per price unit and `scale` converts the price to euros.
const FUELS = {
  electric: { unit: "kWh", kwh: 1, price: 28, priceUnit: "ct/kWh", perPrice: 1, scale: 0.01, eff: 100 },
  gas: { unit: "m³", kwh: 10, price: 11, priceUnit: "ct/kWh", perPrice: 1, scale: 0.01, eff: 95 },
  lpg: { unit: "l", kwh: 6.6, price: 0.7, priceUnit: "€/l", perPrice: 6.6, scale: 1, eff: 95 },
  oil: { unit: "l", kwh: 9.8, price: 1.0, priceUnit: "€/l", perPrice: 9.8, scale: 1, eff: 95 },
  pellets: { unit: "kg", kwh: 4.8, price: 350, priceUnit: "€/t", perPrice: 4800, scale: 1, eff: 90 },
  wood: { unit: "rm", kwh: 1700, price: 110, priceUnit: "€/rm", perPrice: 1700, scale: 1, eff: 80 },
};

// hot water is charged daily in these hours (UTC), i.e. 11 to 15 h MEZ
const WW_HOURS = [10, 11, 12, 13];
const WW_LIFT = 5; // flow temperature above the tank temperature
// PV module: temperature coefficient per K and cell heating per W/m² (NOCT 45 °C);
// the stored yield includes 14 % losses, so irradiance is yield / 0.86
const PV_GAMMA = -0.004, PV_HEATING = 25 / 800, PV_PR = 0.86;
const BATTERY_EFF = Math.sqrt(0.9); // per direction, 90 % round trip

const fmt = (v, digits = 0) => v.toLocaleString("de-DE", { minimumFractionDigits: digits, maximumFractionDigits: digits });

let meta, plzMap, stationById, pvStationById;
const seriesCache = new Map();
const pvCache = new Map();
let station = null;
let tnEdited = false;
let lastResult = null;
let binView = "energy";

// ---------- data ----------

async function loadSeries(id) {
  if (!seriesCache.has(id)) {
    const res = await fetch(`data/t/${id}.bin`);
    const raw = new Int16Array(await res.arrayBuffer());
    const years = new Map();
    meta.years.forEach((year, i) => {
      const slice = raw.subarray(i * meta.hours, (i + 1) * meta.hours);
      if (slice[0] !== meta.missing) years.set(year, slice);
    });
    seriesCache.set(id, years);
  }
  return seriesCache.get(id);
}

/** Hourly PV yield in Wh/kWp of a solar station for one year, or null without data. */
async function loadPv(id, year) {
  if (!id) return null;
  if (!pvCache.has(id)) {
    pvCache.set(id, fetch(`data/pv/${id}.bin`).then(async (res) => new Uint16Array(await res.arrayBuffer())));
  }
  const raw = await pvCache.get(id);
  const i = meta.years.indexOf(year);
  const slice = raw.subarray(i * meta.hours, (i + 1) * meta.hours);
  return slice[0] === meta.pvMissing ? null : slice;
}

/** Heating degree hours below 15 °C, used to find the coldest and warmest year. */
function degreeHours(slice) {
  let sum = 0;
  for (let i = 0; i < slice.length; i++) sum += Math.max(0, 150 - slice[i]);
  return sum;
}

function scenarioYears(series, scenario) {
  const years = [...series.keys()];
  if (scenario === "all") return years;
  if (scenario === "cold" || scenario === "warm") {
    const sorted = years.slice().sort((a, b) => degreeHours(series.get(b)) - degreeHours(series.get(a)));
    return [scenario === "cold" ? sorted[0] : sorted[sorted.length - 1]];
  }
  return series.has(+scenario) ? [+scenario] : years;
}

/** Temperatures in °C as used by the chosen evaluation type. */
function temperatures(slice, resolution) {
  const t = new Float32Array(slice.length);
  for (let i = 0; i < slice.length; i++) t[i] = slice[i] / 10;
  if (resolution === "day") {
    for (let d = 0; d < t.length; d += 24) {
      let sum = 0;
      for (let h = 0; h < 24; h++) sum += t[d + h];
      t.fill(sum / 24, d, d + 24);
    }
  } else if (resolution === "bin") {
    for (let i = 0; i < t.length; i++) t[i] = Math.round(t[i]);
  }
  return t;
}

// ---------- model ----------

/**
 * Hour-by-hour split of the heating load between heat pump and backup heater.
 * Load is linear from qn at tn to 0 at the heating limit thg. A datasheet device
 * delivers its maximum capacity; the generic heat pump is sized so that its capacity
 * equals the load at the bivalence point and changes by `slope` (fraction per K).
 * With a device the bivalence point is where its capacity meets the load, except in
 * alternative mode, where it is the user's switching temperature.
 * Below the bivalence point the backup heater is released (always when monovalent,
 * i.e. monoenergetic with heater rod); load neither of them covers stays uncovered.
 * Hot water has priority: in its charging hours it takes the share of the capacity it
 * needs at its own flow temperature, and the backup heater covers what is left. Below the
 * bivalence point that share is missing for heating and the backup heater covers it too.
 */
function model(p) {
  const dev = p.type === "air" && p.device !== "generic" ? DEVICES[p.device] : null;
  let tb = p.mode === "mono" ? p.tn : p.tbiv;
  const load = (t) => (t < p.thg ? (p.qn * (p.thg - t)) / (p.thg - p.tn) : 0);
  const flow = (t) => {
    if (!p.flowCurve) return p.flowN;
    const f = 20 + ((p.flowN - 20) * (20 - t)) / (20 - p.tn);
    return Math.min(p.flowN, Math.max(25, f));
  };
  let capacityAt;
  if (dev) {
    capacityAt = (t, f) => (t < dev.tmin ? 0 : interpFlow(dev.cap, t, f));
  } else {
    const pb = load(tb);
    capacityAt = (t) => Math.max(0, pb * (1 + p.slope * (t - tb)));
  }
  const capacity = (t) => capacityAt(t, flow(t));
  // outdoor temperature below which the heat pump alone no longer covers the load:
  // scan down in 0.1 K steps, then bisect, so every colder temperature lies strictly below it
  const short = (t) => capacity(t) < load(t) - 1e-9;
  let limit = null;
  for (let k = 1; p.thg - k / 10 >= -30; k++) {
    let lo = p.thg - k / 10, hi = p.thg - (k - 1) / 10;
    if (!short(lo)) continue;
    for (let i = 0; i < 40; i++) {
      const mid = (lo + hi) / 2;
      if (short(mid)) lo = mid; else hi = mid;
    }
    limit = hi;
    break;
  }
  if (dev && p.mode !== "alternative") tb = limit ?? -Infinity;
  const running = (t) => !(p.mode === "alternative" && t < tb) &&
    !(p.mode === "parallel" && Number.isFinite(p.cutoff) && t < p.cutoff);
  // `share` is the part of the hour the heat pump spends on hot water
  const heatPump = (t, share = 0) => (running(t) ? Math.min(load(t), capacity(t) * (1 - share)) : 0);
  const backupAllowed = (t) => p.mode === "mono" || t < tb;
  const copAt = (t, f) => {
    if (p.type === "air") return deviceCop(dev || DEVICES.lwm110, t, f);
    const [source, eta] = SOURCE[p.type];
    return Math.min(COP_MAX, eta * carnot(f, source));
  };
  const cop = (t) => copAt(t, flow(t));
  const wwFlow = p.wwTemp + WW_LIFT;
  /** Hot water of one charging hour: heat pump part, its share of the hour and electricity. */
  const hotWater = (t, need) => {
    const cap = running(t) ? capacityAt(t, wwFlow) : 0;
    const hp = Math.min(need, cap);
    return { hp, share: cap > 0 ? hp / cap : 0, el: hp > 0 ? hp / copAt(t, wwFlow) : 0 };
  };
  return { dev, tb, pb: Number.isFinite(tb) ? capacity(tb) : 0, load, capacity, heatPump, backupAllowed, flow, cop, limit, hotWater, wwFlow, copAt };
}

function simulate(series, years, p) {
  const m = model(p);
  const n = years.length;
  const wwNeed = p.hotWater ? p.ww / WW_HOURS.length : 0;
  const r = {
    years, n, tb: m.tb, pb: m.pb, model: m, params: p,
    q: 0, hp: 0, backup: 0, uncovered: 0, el: 0, peak: 0,
    heatingHours: 0, backupHours: 0, uncoveredHours: 0, cyclingHours: 0, belowTn: 0,
    ww: 0, wwHp: 0, wwBackup: 0, elWw: 0,
    months: Array.from({ length: 12 }, () => ({ hp: 0, backup: 0, uncovered: 0 })),
    wwMonths: Array.from({ length: 12 }, () => ({ hp: 0, backup: 0 })),
    els: new Float32Array(n * 8760),
    bins: new Map(),
    loads: new Float32Array(n * 8760),
    hps: new Float32Array(n * 8760),
    backs: new Float32Array(n * 8760),
    wwHps: new Float32Array(n * 8760),
    wwBacks: new Float32Array(n * 8760),
    temps: [],
  };
  const isWw = new Uint8Array(8760);
  if (wwNeed > 0) for (let i = 0; i < 8760; i++) isWw[i] = WW_HOURS.includes(i % 24) ? 1 : 0;
  // temperatures repeat a lot (0.1 K resolution), so evaluate the model once per value
  const caches = [new Map(), new Map()];
  const evaluate = (t, ww) => {
    let v = caches[ww].get(t);
    if (!v) {
      const w = ww ? m.hotWater(t, wwNeed) : { hp: 0, share: 0, el: 0 };
      // above the bivalence point the heat pump catches up on the heating pause afterwards
      const q = m.load(t), hp = m.heatPump(t, m.backupAllowed(t) ? w.share : 0);
      const backup = m.backupAllowed(t) ? q - hp : 0;
      v = { q, hp, backup, uncovered: q - hp - backup, el: hp > 0 ? hp / m.cop(t) : 0,
        wwHp: w.hp, wwBackup: ww ? wwNeed - w.hp : 0, wwEl: w.el };
      caches[ww].set(t, v);
    }
    return v;
  };
  years.forEach((year, y) => {
    const t = temperatures(series.get(year), p.resolution);
    r.temps.push(t);
    for (let i = 0; i < t.length; i++) {
      const { q, hp, backup, uncovered, el, wwHp, wwBackup, wwEl } = evaluate(t[i], isWw[i]);
      const j = y * 8760 + i;
      r.loads[j] = q;
      r.hps[j] = hp;
      r.backs[j] = backup;
      r.els[j] = el + wwEl;
      if (isWw[i]) {
        r.wwHps[j] = wwHp;
        r.wwBacks[j] = wwBackup;
        r.ww += wwNeed; r.wwHp += wwHp; r.wwBackup += wwBackup; r.elWw += wwEl;
        r.wwMonths[HOUR_MONTH[i]].hp += wwHp;
        r.wwMonths[HOUR_MONTH[i]].backup += wwBackup;
      }
      if (q <= 0) continue;
      r.q += q; r.hp += hp; r.backup += backup; r.uncovered += uncovered; r.el += el;
      r.heatingHours++;
      if (backup > 1e-9) r.backupHours++;
      if (uncovered > 1e-9) r.uncoveredHours++;
      if (m.dev?.pmin && hp > 0 && hp < m.dev.pmin) r.cyclingHours++;
      if (t[i] < p.tn) r.belowTn++;
      if (q > r.peak) r.peak = q;
      r.months[HOUR_MONTH[i]].hp += hp;
      r.months[HOUR_MONTH[i]].backup += backup;
      r.months[HOUR_MONTH[i]].uncovered += uncovered;
      const key = Math.round(t[i]);
      const bin = r.bins.get(key) || { hours: 0, hp: 0, backup: 0, uncovered: 0, el: 0 };
      bin.hours++; bin.hp += hp; bin.backup += backup; bin.uncovered += uncovered; bin.el += el;
      r.bins.set(key, bin);
    }
  });
  // per-year averages
  for (const k of ["q", "hp", "backup", "uncovered", "el", "heatingHours", "backupHours",
    "uncoveredHours", "cyclingHours", "belowTn", "ww", "wwHp", "wwBackup", "elWw"]) r[k] /= n;
  for (const month of [...r.months, ...r.wwMonths]) for (const k in month) month[k] /= n;
  for (const bin of r.bins.values()) for (const k in bin) bin[k] /= n;
  r.jaz = r.el > 0 ? r.hp / r.el : 0;
  r.costHp = (r.el * p.priceEl) / 100;
  r.backupFuel = r.backup / p.effBackup;
  const fuel = FUELS[p.fuel];
  r.backupAmount = r.backupFuel / fuel.kwh;
  r.costBackup = (r.backupFuel / fuel.perPrice) * p.priceBackup * fuel.scale;
  const loadTn = m.load(p.tn);
  r.powerShareTn = loadTn > 0 ? m.heatPump(p.tn) / loadTn : 0;
  // heating and hot water together
  r.heat = r.q + r.ww;
  r.hpAll = r.hp + r.wwHp;
  r.backupAll = r.backup + r.wwBackup;
  r.elAll = r.el + r.elWw;
  r.jazWw = r.elWw > 0 ? r.wwHp / r.elWw : 0;
  r.jazAll = r.elAll > 0 ? r.hpAll / r.elAll : 0;
  r.backupFuelAll = r.backupAll / p.effBackup;
  r.backupAmountAll = r.backupFuelAll / fuel.kwh;
  r.costBackupAll = (r.backupFuelAll / fuel.perPrice) * p.priceBackup * fuel.scale;
  r.cost = (r.elAll * p.priceEl) / 100 + r.costBackupAll;
  return r;
}

/**
 * Hourly electricity balance of heat pump and (electric backup only) heater rod with PV
 * and battery. `pvData` holds the yield in Wh/kWp per simulated year, or null.
 * The battery starts empty each year, charges only from surplus PV and is limited to 1 C.
 */
function balance(r, p, series, pvData) {
  const n = r.n, cap = p.battery;
  const electric = p.fuel === "electric";
  const b = {
    pv: 0, direct: 0, charge: 0, discharge: 0, feed: 0, grid: 0, demand: 0, gridCost: 0, noPvCost: 0,
    months: Array.from({ length: 12 }, () => ({ pv: 0, direct: 0, battery: 0, grid: 0 })),
    pvs: new Float32Array(n * 8760), grids: new Float32Array(n * 8760), feeds: new Float32Array(n * 8760),
    missingYears: r.years.filter((_, y) => !pvData[y]),
  };
  r.years.forEach((year, y) => {
    const yieldWh = pvData[y], temps = series.get(year);
    let soc = 0;
    for (let i = 0; i < 8760; i++) {
      const j = y * 8760 + i;
      const hp = r.els[j];
      const rod = electric ? (r.backs[j] + r.wwBacks[j]) / p.effBackup : 0;
      const d = hp + rod;
      let pv = 0;
      if (yieldWh && yieldWh[i] > 0) {
        const cell = temps[i] / 10 + (PV_HEATING * yieldWh[i]) / PV_PR;
        pv = ((p.kwp * yieldWh[i]) / 1000) * (1 + PV_GAMMA * (cell - 25));
      }
      const direct = Math.min(pv, d);
      const charge = Math.min(pv - direct, (cap - soc) / BATTERY_EFF, cap);
      soc += charge * BATTERY_EFF;
      const discharge = Math.min(d - direct, soc * BATTERY_EFF, cap);
      soc -= discharge / BATTERY_EFF;
      const grid = d - direct - discharge;
      const feed = pv - direct - charge;
      // grid electricity is priced per consumer in proportion to its demand
      const price = d > 0 ? (hp * p.priceEl + rod * p.priceBackup) / d : 0;
      b.gridCost += (grid * price) / 100;
      b.noPvCost += (hp * p.priceEl + rod * p.priceBackup) / 100;
      b.pv += pv; b.direct += direct; b.charge += charge; b.discharge += discharge;
      b.feed += feed; b.grid += grid; b.demand += d;
      const month = b.months[HOUR_MONTH[i]];
      month.pv += pv; month.direct += direct; month.battery += discharge; month.grid += grid;
      b.pvs[j] = pv; b.grids[j] = grid; b.feeds[j] = feed;
    }
  });
  for (const k of ["pv", "direct", "charge", "discharge", "feed", "grid", "demand", "gridCost", "noPvCost"]) b[k] /= n;
  for (const month of b.months) for (const k in month) month[k] /= n;
  b.selfShare = b.pv > 0 ? (b.pv - b.feed) / b.pv : 0;
  b.autarky = b.demand > 0 ? (b.direct + b.discharge) / b.demand : 0;
  b.revenue = p.feedOn ? (b.feed * p.feedIn) / 100 : 0;
  b.cycles = cap > 0 ? b.discharge / cap : 0;
  // electricity from the grid replaces the electricity costs; fuels stay as they are
  b.cost = b.gridCost - b.revenue + (electric ? 0 : r.costBackupAll);
  b.saving = r.cost - b.cost;
  return b;
}

// ---------- form ----------

/** Number from an input; NaN when it is empty or not a valid number (e.g. while typing "-"). */
function num(id) {
  const v = $(id).value.trim();
  return v === "" ? NaN : +v;
}

function params() {
  const cutoff = $("cutoff").value.trim();
  return {
    qn: num("qn"),
    tn: num("tn"),
    thg: num("thg"),
    mode: $("mode").value,
    tbiv: num("tbiv"),
    cutoff: cutoff === "" ? NaN : +cutoff,
    slope: num("slope") / 100,
    resolution: $("resolution").value,
    type: $("type").value,
    device: $("device").value,
    flowN: num("flowN"),
    flowCurve: $("flowCurve").checked,
    priceEl: num("priceEl"),
    fuel: $("fuel").value,
    priceBackup: num("priceBackup"),
    effBackup: num("effBackup") / 100,
    hotWater: $("wwOn").checked,
    pv: $("pvOn").checked,
    extra: $("wwOn").checked || $("pvOn").checked,
    ww: num("ww"),
    wwTemp: num("wwTemp"),
    kwp: num("kwp"),
    battery: num("battery"),
    feedOn: $("feedOn").checked,
    feedIn: num("feedIn"),
  };
}

function validate(p) {
  const manualTbiv = p.mode === "alternative" || p.type !== "air" || p.device === "generic";
  const generic = p.type !== "air" || p.device === "generic";
  const required = [
    ["qn", "Norm-Heizlast"], ["tn", "Norm-Außentemperatur"], ["flowN", "Vorlauftemperatur"],
    ["priceEl", "Strompreis"], ["priceBackup", "Preis Zusatzheizung"], ["effBackup", "Wirkungsgrad Zusatzheizung"],
  ];
  if (p.mode !== "mono" && manualTbiv) required.push(["tbiv", $("tbivLabel").textContent]);
  if (generic) required.push(["slope", "Leistungsänderung der WP"]);
  if (p.hotWater) required.push(["ww", "Warmwasserbedarf"], ["wwTemp", "Speichertemperatur"]);
  if (p.pv) required.push(["kwp", "PV-Anlage"], ["battery", "Batteriespeicher"]);
  if (p.pv && p.feedOn) required.push(["feedIn", "Einspeisevergütung"]);
  for (const [key, label] of required) {
    if (!Number.isFinite(p[key])) return `Bitte eine gültige Zahl für „${label}“ eingeben.`;
  }
  if (!(p.qn > 0)) return "Norm-Heizlast muss größer als 0 sein.";
  if (!(p.flowN >= 25 && p.flowN <= 65)) return "Vorlauftemperatur muss zwischen 25 und 65 °C liegen.";
  if (!(p.effBackup > 0)) return "Wirkungsgrad der Zusatzheizung muss größer als 0 sein.";
  if (!(p.tn < p.thg)) return "Norm-Außentemperatur muss unter der Heizgrenztemperatur liegen.";
  if (p.hotWater) {
    if (!(p.ww >= 0)) return "Warmwasserbedarf darf nicht negativ sein.";
    if (!(p.wwTemp >= 40 && p.wwTemp <= 60)) return "Speichertemperatur muss zwischen 40 und 60 °C liegen.";
  }
  if (p.pv && (!(p.kwp >= 0) || !(p.battery >= 0))) return "PV-Leistung und Speicher dürfen nicht negativ sein.";
  if (p.mode !== "mono" && manualTbiv && !(p.tbiv < p.thg)) return `${$("tbivLabel").textContent} muss unter der Heizgrenztemperatur liegen.`;
  return null;
}

function showLocation() {
  const code = $("plz").value.trim();
  const entry = plzMap[code];
  if (!entry) {
    station = null;
    $("location").textContent = code.length === 5 ? "Postleitzahl nicht gefunden." : "";
    return;
  }
  const [place, , , id, dist] = entry;
  station = stationById[id];
  $("location").innerHTML =
    `${place} · Station <b>${station.name}</b> (${station.elev} m ü. NN, ${fmt(dist, 1)} km entfernt, ${station.years.length} Jahre)` +
    (dist > 25 ? ` <span class="warn">Nächste Station ist weit entfernt.</span>` : "");
  $("tnHint").textContent = station.tnorm != null ? `(${fmt(station.tnorm, 1)} °C)` : "";
  if (!tnEdited && station.tnorm != null) $("tn").value = station.tnorm;
  fillScenarios();
}

function fillScenarios() {
  const select = $("scenario");
  const previous = select.value || "all";
  const first = station.years[0], last = station.years[station.years.length - 1];
  select.innerHTML =
    `<option value="all">Mittel ${first}–${last} (${station.years.length} Jahre)</option>` +
    `<option value="cold">Kältestes Jahr</option><option value="warm">Wärmstes Jahr</option>` +
    station.years.slice().reverse().map((y) => `<option>${y}</option>`).join("");
  select.value = [...select.options].some((o) => o.value === previous) ? previous : "all";
}

function updateFieldVisibility() {
  const mode = $("mode").value;
  const air = $("type").value === "air";
  $("deviceField").hidden = !air;
  $("slopeField").hidden = air && $("device").value !== "generic";
  $("bivalentFields").hidden = mode === "mono";
  const device = air && $("device").value !== "generic";
  $("tbivField").hidden = device && mode === "parallel";
  $("tbivLabel").textContent = device ? "Umschalttemperatur" : "Bivalenzpunkt";
  $("cutoffField").hidden = mode !== "parallel";
  $("cutoffField").nextElementSibling.hidden = mode !== "parallel";
  const ww = $("wwOn").checked, pv = $("pvOn").checked;
  $("wwFields").hidden = !ww;
  $("pvFields").hidden = !pv;
  $("feedInField").hidden = !(pv && $("feedOn").checked);
  $("summaryBlock").hidden = !(ww || pv);
  $("extraBlock").hidden = !(ww || pv);
  $("extraHeading").textContent = ww && pv ? "Warmwasser & PV" : ww ? "Warmwasser" : "PV und Speicher";
  $("wwFigure").hidden = !ww;
  if (!pv) $("powerFigure").hidden = true;
}

// ---------- steps ----------

const steps = [...document.querySelectorAll(".step")];
const figures = [...document.querySelectorAll("figure[data-step]")];
let step = 1;

/** Show one step; charts sit beside the inputs they depend on and all together under Ergebnisse. */
function showStep(n) {
  step = Math.min(Math.max(n, 1), steps.length);
  steps.forEach((s) => { s.hidden = +s.dataset.step !== step; });
  const last = step === steps.length;
  for (const f of figures) {
    const target = last ? `figs-${f.dataset.group}` : +f.dataset.step === step ? `aside-${step}` : "figures";
    $(target).append(f);
  }
  $("stepper").querySelectorAll("button").forEach((b) => {
    const k = +b.dataset.step;
    b.setAttribute("aria-current", k === step ? "step" : "false");
    b.classList.toggle("done", k < step);
    if (k === step) b.scrollIntoView({ block: "nearest", inline: "nearest" });
  });
  $("prev").hidden = step === 1;
  $("next").hidden = last;
  if (!last) $("next").textContent = `Weiter: ${steps[step].dataset.title}`;
  try { history.replaceState(null, "", `#${step}`); } catch {}
}

function buildStepper() {
  $("stepper").innerHTML = steps.map((s) =>
    `<button type="button" data-step="${s.dataset.step}"><span class="num">${s.dataset.step}</span>${s.dataset.title}</button>`).join("");
  $("stepper").querySelectorAll("button").forEach((b) => b.addEventListener("click", () => showStep(+b.dataset.step)));
  $("prev").addEventListener("click", () => { showStep(step - 1); scrollTo({ top: 0 }); });
  $("next").addEventListener("click", () => { showStep(step + 1); scrollTo({ top: 0 }); });
  showStep(parseInt(location.hash.slice(1), 10) || 1);
}

/** Solar station used for the most recent simulated year, with its distance. */
function pvStationText(years) {
  const id = station.pv?.[meta.years.indexOf(years[years.length - 1])];
  const s = id && pvStationById[id];
  if (!s) return null;
  const rad = Math.PI / 180;
  const a = Math.sin(((s.lat - station.lat) * rad) / 2) ** 2 +
    Math.cos(station.lat * rad) * Math.cos(s.lat * rad) * Math.sin(((s.lon - station.lon) * rad) / 2) ** 2;
  return `${s.name} (${fmt(12742 * Math.asin(Math.sqrt(a)), 0)} km von der Temperaturstation)`;
}

function onFuelChange(resetValues = true) {
  const fuel = FUELS[$("fuel").value];
  if (resetValues) {
    $("priceBackup").value = fuel.price;
    $("effBackup").value = fuel.eff;
  }
  $("priceBackupUnit").textContent = fuel.priceUnit;
  $("fuelHint").textContent = fuel.unit === "kWh" ? "" :
    `Heizwert ${fmt(fuel.kwh, fuel.kwh < 100 ? 1 : 0)} kWh/${fuel.unit}, Wirkungsgrad bezogen auf den Heizwert.`;
}

function onTypeChange() {
  $("slope").value = $("type").value === "air" ? 3 : 0;
}

let scheduled = null;
function scheduleRun() {
  clearTimeout(scheduled);
  scheduled = setTimeout(run, 60);
}

let runToken = 0;
async function run() {
  updateFieldVisibility();
  if (!station) {
    $("status").textContent = "Bitte eine gültige Postleitzahl eingeben.";
    return;
  }
  const p = params();
  const error = validate(p);
  // keep the last results visible but greyed out until the input is valid again
  document.body.classList.toggle("stale", !!error);
  if (error) { $("status").innerHTML = `<span class="warn">${error}</span>`; return; }
  const token = ++runToken;
  const series = await loadSeries(station.id);
  if (token !== runToken) return;
  let years = scenarioYears(series, $("scenario").value);
  let pvData = null, pvOnly = false;
  if (p.pv && p.kwp > 0) {
    // with PV the mean covers only the years with irradiation data, so both sides match
    const pvId = (year) => station.pv?.[meta.years.indexOf(year)];
    const withPv = years.filter(pvId);
    if (years.length > 1 && withPv.length && withPv.length < years.length) { years = withPv; pvOnly = true; }
    pvData = await Promise.all(years.map((year) => loadPv(pvId(year), year)));
    if (token !== runToken) return;
  }
  const r = simulate(series, years, p);
  r.pv = pvData ? balance(r, p, series, pvData) : null;
  lastResult = r;
  $("status").textContent = years.length > 1
    ? `Mittelwerte über ${years.length} Jahre${pvOnly ? " mit Strahlungsdaten" : ""} (${years[0]}–${years[years.length - 1]}), Station ${station.name}.`
    : `Wetterjahr ${years[0]}, Station ${station.name}.`;
  if (r.pv) {
    const text = pvStationText(years);
    if (text) $("status").textContent += ` Strahlung: ${text}.`;
    if (r.pv.missingYears.length) {
      $("status").innerHTML += ` <span class="warn">Keine Strahlungsdaten (Station bis 100 km) für ${r.pv.missingYears.join(", ")}, dort ohne PV gerechnet.</span>`;
    }
  }
  if (r.model.dev) {
    const auto = p.mode !== "alternative";
    $("tbivHint").textContent = r.model.limit == null
      ? `${r.model.dev.name} deckt die Heizlast bei allen Temperaturen.`
      : auto ? `Bivalenzpunkt ${fmt(r.model.limit, 1)} °C: dort erreicht die Heizlast die Leistung der ${r.model.dev.name}.`
      : `Leistungsgrenze ${r.model.dev.name}: ${fmt(r.model.limit, 1)} °C. Darunter muss umgeschaltet werden.`;
    $("tbivAdopt").hidden = auto || r.model.limit == null;
  } else {
    $("tbivHint").textContent = `WP-Heizleistung am Bivalenzpunkt: ${fmt(r.pb, 1)} kW`;
    $("tbivAdopt").hidden = true;
  }
  if (r.uncovered > 0.5) {
    $("status").innerHTML += ` <span class="warn">${fmt(r.uncovered)} kWh/a nicht gedeckt: Die WP schafft die Heizlast oberhalb des Bivalenzpunkts nicht.</span>`;
  }
  renderPreview(r);
  renderKpis(r);
  renderDuration(r);
  renderBins(r);
  renderMonths(r);
  if (p.extra) {
    renderSummary(r);
    renderExtra(r);
  }
}

// ---------- output ----------

function kpi(label, value, sub = "", cls = "") {
  return `<div class="kpi ${cls}"><div class="label">${label}</div><div class="value">${value}</div><div class="sub">${sub}</div></div>`;
}

/** The few numbers that stay visible above every step. */
function renderPreview(r) {
  const p = r.params, b = r.pv;
  const heat = p.extra ? r.heat : r.q, hp = p.extra ? r.hpAll : r.hp;
  const el = p.extra ? r.elAll : r.el, jaz = p.extra ? r.jazAll : r.jaz;
  const cost = b ? b.cost : p.extra ? r.cost : r.costHp + r.costBackup;
  $("previewKpis").innerHTML = [
    kpi(p.hotWater ? "Wärmebedarf" : "Heizwärmebedarf", `${fmt(heat)} kWh/a`),
    kpi("Deckungsanteil WP", `${fmt(heat > 0 ? (100 * hp) / heat : 0, 1)} %`, "", "hp"),
    kpi("Jahresarbeitszahl", fmt(jaz, 2), "", "hp"),
    b ? kpi("Autarkie Strom", `${fmt(100 * b.autarky, 1)} %`, "", "pv") : kpi("Strombedarf WP", `${fmt(el)} kWh/a`, "", "hp"),
    Number.isFinite(r.tb) ? kpi("Bivalenzpunkt", `${fmt(r.tb, 1)} °C`, "", "backup") : kpi("Bivalenzpunkt", "keiner", "", "backup"),
    kpi("Energiekosten", `${fmt(cost)} €/a`),
  ].join("");
}

function renderKpis(r) {
  const share = (x) => (r.q > 0 ? (100 * x) / r.q : 0);
  const p = r.params;
  $("kpis").innerHTML = [
    kpi("Heizwärmebedarf", `${fmt(r.q)} kWh/a`, `${fmt(r.q / p.qn)} Vollbenutzungsstunden`),
    kpi("Deckungsanteil Wärmepumpe", `${fmt(share(r.hp), 1)} %`, `${fmt(r.hp)} kWh/a`, "hp"),
    kpi("Deckungsanteil Zusatzheizung", `${fmt(share(r.backup), 1)} %`, `${fmt(r.backup)} kWh/a`, "backup"),
    r.uncovered > 0.5 ? kpi("Nicht gedeckt", `${fmt(share(r.uncovered), 1)} %`, `${fmt(r.uncovered)} kWh/a in ${fmt(r.uncoveredHours)} h`, "uncovered") : "",
    kpi("Jahresarbeitszahl WP", fmt(r.jaz, 2), `COP bei Norm-Außentemp. ${fmt(r.model.cop(p.tn), 2)}`, "hp"),
    kpi("Strombedarf WP", `${fmt(r.el)} kWh/a`, `${fmt(r.costHp)} €/a`, "hp"),
    kpi(`Endenergie ${$("fuel").selectedOptions[0].text}`,
      `${fmt(r.backupAmount, FUELS[p.fuel].unit === "rm" ? 1 : 0)} ${FUELS[p.fuel].unit}/a`,
      `${p.fuel === "electric" ? "" : `${fmt(r.backupFuel)} kWh · `}${fmt(r.costBackup)} €/a`, "backup"),
    kpi("Heizkosten gesamt", `${fmt(r.costHp + r.costBackup)} €/a`, `${fmt(r.q > 0 ? (100 * (r.costHp + r.costBackup)) / r.q : 0, 1)} ct/kWh Wärme`),
    kpi("Leistungsanteil bei Norm-Außentemp.", `${fmt(100 * r.powerShareTn, 1)} %`, `WP ${fmt(r.model.heatPump(p.tn), 1)} von ${fmt(p.qn, 1)} kW`),
    Number.isFinite(r.tb)
      ? kpi("Bivalenzpunkt", `${fmt(r.tb, 1)} °C`, `WP-Leistung ${fmt(r.pb, 1)} kW` +
        (r.model.dev && p.mode === "alternative" && r.model.limit != null ? ` · Leistungsgrenze ${fmt(r.model.limit, 1)} °C` : ""))
      : kpi("Bivalenzpunkt", "keiner", "WP deckt die Heizlast allein"),
    kpi("Heizstunden", `${fmt(r.heatingHours)} h/a`, `davon ${fmt(r.backupHours)} h mit Zusatzheizung` +
      (r.model.dev?.pmin ? `, ${fmt(r.cyclingHours)} h unter Mindestleistung ${fmt(r.model.dev.pmin, 1)} kW (Takten)` : "")),
    kpi("Stunden unter Norm-Außentemp.", `${fmt(r.belowTn)} h/a`, `max. Heizlast ${fmt(r.peak, 1)} kW`),
  ].join("");
}

/** Heating and hot water together, with PV and battery if there are any. */
function renderSummary(r) {
  const p = r.params, b = r.pv, fuel = FUELS[p.fuel];
  const share = (x) => (r.heat > 0 ? (100 * x) / r.heat : 0);
  const uncovered = r.uncovered;
  const cost = b ? b.cost : r.cost;
  $("summaryKpis").innerHTML = [
    kpi("Wärmebedarf gesamt", `${fmt(r.heat)} kWh/a`, p.hotWater ? `Heizung ${fmt(r.q)} · Warmwasser ${fmt(r.ww)} kWh` : "nur Heizung"),
    kpi("Deckungsanteil Wärmepumpe", `${fmt(share(r.hpAll), 1)} %`, `${fmt(r.hpAll)} kWh/a`, "hp"),
    kpi("Deckungsanteil Zusatzheizung", `${fmt(share(r.backupAll), 1)} %`, `${fmt(r.backupAll)} kWh/a`, "backup"),
    uncovered > 0.5 ? kpi("Nicht gedeckt", `${fmt(share(uncovered), 1)} %`, `${fmt(uncovered)} kWh/a Heizung`, "uncovered") : "",
    kpi("Jahresarbeitszahl WP", fmt(r.jazAll, 2), p.hotWater ? `Heizung ${fmt(r.jaz, 2)} · Warmwasser ${fmt(r.jazWw, 2)}` : "", "hp"),
    kpi("Strombedarf WP", `${fmt(r.elAll)} kWh/a`, p.hotWater ? `Heizung ${fmt(r.el)} · Warmwasser ${fmt(r.elWw)} kWh` : "", "hp"),
    kpi(`Endenergie ${$("fuel").selectedOptions[0].text}`,
      `${fmt(r.backupAmountAll, fuel.unit === "rm" ? 1 : 0)} ${fuel.unit}/a`,
      `${p.fuel === "electric" ? "" : `${fmt(r.backupFuelAll)} kWh · `}${fmt(r.costBackupAll)} €/a${p.fuel === "electric" && b ? " ohne PV" : ""}`, "backup"),
    b ? kpi("Autarkie Strom", `${fmt(100 * b.autarky, 1)} %`, `Netzbezug ${fmt(b.grid)} von ${fmt(b.demand)} kWh/a`, "pv") : "",
    kpi("Energiekosten gesamt", `${fmt(cost)} €/a`,
      `${fmt(r.heat > 0 ? (100 * cost) / r.heat : 0, 1)} ct/kWh Wärme` + (b ? ` · ohne PV ${fmt(r.cost)} €/a` : "")),
  ].join("");
}

function renderExtra(r) {
  const p = r.params, b = r.pv;
  const wwShare = r.ww > 0 ? (100 * r.wwHp) / r.ww : 0;
  $("extraKpis").innerHTML = [
    ...(p.hotWater ? [
      kpi("Warmwasser", `${fmt(r.ww)} kWh/a`, `Vorlauf ${fmt(r.model.wwFlow)} °C`, "ww"),
      kpi("Warmwasser durch WP", `${fmt(wwShare, 1)} %`, `Zusatzheizung ${fmt(r.wwBackup)} kWh/a`, "ww"),
      kpi("Arbeitszahl Warmwasser", fmt(r.jazWw, 2), `Strom ${fmt(r.elWw)} kWh/a`, "ww"),
    ] : []),
    ...(b ? [
      kpi("PV-Ertrag", `${fmt(b.pv)} kWh/a`, `${fmt(p.kwp > 0 ? b.pv / p.kwp : 0)} kWh/kWp`, "pv"),
      kpi("Eigenverbrauch", `${fmt(100 * b.selfShare, 1)} %`, `${fmt(b.pv - b.feed)} kWh/a genutzt`, "pv"),
      kpi("Autarkie Strom", `${fmt(100 * b.autarky, 1)} %`, `direkt ${fmt(b.direct)} · Speicher ${fmt(b.discharge)} kWh/a`, "pv"),
      kpi("Netzbezug", `${fmt(b.grid)} kWh/a`, `${fmt(b.gridCost)} €/a`),
      p.feedOn ? kpi("Einspeisung", `${fmt(b.feed)} kWh/a`, `${fmt(b.revenue)} €/a Vergütung`)
        : kpi("Abgeregelt", `${fmt(b.feed)} kWh/a`, "ohne Einspeisung, keine Vergütung"),
      p.battery > 0 ? kpi("Speicher", `${fmt(b.cycles)} Vollzyklen/a`, `${fmt(b.discharge)} kWh/a entladen`) : "",
      kpi("Ersparnis durch PV", `${fmt(b.saving)} €/a`, p.feedOn ? "Strom für WP und Heizstab inkl. Einspeisung" : "Strom für WP und Heizstab"),
    ] : []),
  ].join("");
  $("powerFigure").hidden = !b;
  if (b) renderPower(r);
  if (p.hotWater) renderWwMonths(r);
}

const W = 760, H = 280, PAD = { l: 62, r: 12, t: 10, b: 32 };

function niceMax(v) {
  if (v <= 0) return 1;
  const e = Math.pow(10, Math.floor(Math.log10(v)));
  return [1, 2, 2.5, 5, 10].map((f) => f * e).find((x) => x >= v);
}

function axes(xTicks, yMax, yLabel, xLabel) {
  const ih = H - PAD.t - PAD.b;
  let s = "";
  for (let i = 0; i <= 4; i++) {
    const v = (yMax * i) / 4, y = PAD.t + ih - (ih * i) / 4;
    s += `<line class="grid" x1="${PAD.l}" x2="${W - PAD.r}" y1="${y}" y2="${y}"/>`;
    s += `<text x="${PAD.l - 6}" y="${y + 4}" text-anchor="end">${fmt(v, v < 10 && v % 1 ? 1 : 0)}</text>`;
  }
  for (const [x, label] of xTicks) s += `<text x="${x}" y="${H - PAD.b + 16}" text-anchor="middle">${label}</text>`;
  s += `<text x="12" y="${PAD.t + ih / 2}" transform="rotate(-90 12 ${PAD.t + ih / 2})" text-anchor="middle">${yLabel}</text>`;
  s += `<text x="${PAD.l + (W - PAD.l - PAD.r) / 2}" y="${H - 2}" text-anchor="middle">${xLabel}</text>`;
  return s;
}

function legend(items) {
  return `<div class="legend">${items.map(([cls, label]) => `<span><i style="background:var(--${cls})"></i>${label}</span>`).join("")}</div>`;
}

function energyLegend(r) {
  const items = [["hp", "Wärmepumpe"], ["backup", "Zusatzheizung"]];
  if (r.uncovered > 0.5) items.push(["uncovered", "nicht gedeckt"]);
  return items;
}

/** Stacked bar of heat pump, backup and uncovered energy. */
function stack(x, w, py, parts) {
  let s = "", sum = 0;
  for (const [cls, v] of parts) {
    if (v <= 0) continue;
    const y0 = py(sum), y1 = py(sum + v);
    s += `<rect class="${cls}" x="${x}" width="${w}" y="${y1}" height="${y0 - y1}"/>`;
    sum += v;
  }
  return s;
}

function renderDuration(r) {
  // sort all hours by load, descending; x axis is hours per year
  const total = r.loads.length;
  const order = Array.from({ length: total }, (_, i) => i).sort((a, b) => r.loads[b] - r.loads[a]);
  const heating = Math.ceil(order.findIndex((i) => r.loads[i] <= 0) / r.n) || 8760;
  const xMax = Math.min(8760, Math.ceil(heating / 500) * 500 + 500);
  const steps = 380;
  const iw = W - PAD.l - PAD.r, ih = H - PAD.t - PAD.b;
  const yMax = niceMax(r.peak);
  const px = (h) => PAD.l + (iw * h) / xMax, py = (v) => PAD.t + ih - (ih * v) / yMax;
  const loadPts = [], coveredPts = [], hpPts = [];
  // each point averages the hours up to the next one, so single hours (e.g. hot water
  // charging) don't show up as spikes
  const index = (s) => Math.min(total, Math.floor(((s / steps) * xMax) * r.n));
  for (let s = 0; s <= steps; s++) {
    const a = Math.min(total - 1, index(s)), b = Math.max(a + 1, index(s + 1));
    let load = 0, hp = 0, back = 0;
    for (let k = a; k < b; k++) {
      const i = order[k];
      load += r.loads[i]; hp += r.hps[i]; back += r.backs[i];
    }
    const h = (s / steps) * xMax, c = b - a;
    loadPts.push(`${px(h)},${py(load / c)}`);
    coveredPts.push(`${px(h)},${py((hp + back) / c)}`);
    hpPts.push(`${px(h)},${py(hp / c)}`);
  }
  const base = `${px(xMax)},${py(0)} ${px(0)},${py(0)}`;
  const ticks = [];
  for (let h = 0; h <= xMax; h += xMax > 4000 ? 1000 : 500) ticks.push([px(h), fmt(h)]);
  $("duration").innerHTML =
    `<svg viewBox="0 0 ${W} ${H}" role="img" aria-label="Jahresdauerlinie">` +
    axes(ticks, yMax, "Heizlast [kW]", "Stunden pro Jahr") +
    `<polygon class="uncovered" points="${loadPts.join(" ")} ${base}"/>` +
    `<polygon class="backup" points="${coveredPts.join(" ")} ${base}"/>` +
    `<polygon class="hp" points="${hpPts.join(" ")} ${base}"/>` +
    `</svg>` + legend(energyLegend(r));
}

function renderBins(r) {
  const keys = [...r.bins.keys()].sort((a, b) => a - b);
  if (!keys.length) { $("bins").innerHTML = ""; return; }
  const lo = keys[0], hi = keys[keys.length - 1];
  const iw = W - PAD.l - PAD.r, ih = H - PAD.t - PAD.b;
  const count = hi - lo + 1, bw = iw / count;
  const energy = binView === "energy";
  const value = (b) => (energy ? b.hp + b.backup + b.uncovered : b.hours);
  const yMax = niceMax(Math.max(...keys.map((k) => value(r.bins.get(k)))));
  const py = (v) => PAD.t + ih - (ih * v) / yMax;
  let bars = "";
  const ticks = [];
  for (let k = lo; k <= hi; k++) {
    const x = PAD.l + (k - lo) * bw;
    if (k % 5 === 0) ticks.push([x + bw / 2, k]);
    const b = r.bins.get(k);
    if (!b) continue;
    const title = `<title>${k} °C: ${fmt(b.hours)} h, WP ${fmt(b.hp)} kWh, Zusatz ${fmt(b.backup)} kWh` +
      (b.uncovered > 0.05 ? `, nicht gedeckt ${fmt(b.uncovered)} kWh` : "") + `</title>`;
    if (energy) {
      bars += `<g>${title}${stack(x + 0.5, bw - 1, py, [["hp", b.hp], ["backup", b.backup], ["uncovered", b.uncovered]])}</g>`;
    } else {
      const cls = b.uncovered > 1e-9 ? "uncovered" : b.backup > 1e-9 ? "backup" : "hp";
      bars += `<g>${title}<rect class="${cls}" x="${x + 0.5}" width="${bw - 1}" y="${py(b.hours)}" height="${py(0) - py(b.hours)}"/></g>`;
    }
  }
  const toggle = `<div class="actions" style="margin:0 0 6px">` +
    `<button type="button" data-view="energy"${energy ? ' aria-pressed="true"' : ""}>Wärme</button>` +
    `<button type="button" data-view="hours"${energy ? "" : ' aria-pressed="true"'}>Stunden</button></div>`;
  $("bins").innerHTML = toggle +
    `<svg viewBox="0 0 ${W} ${H}" role="img" aria-label="Bins">` +
    axes(ticks, yMax, energy ? "Wärme [kWh/a]" : "Stunden [h/a]", "Außentemperatur [°C]") + bars + `</svg>` +
    legend(energy ? energyLegend(r)
      : [["hp", "nur WP"], ["backup", "mit Zusatzheizung"], ...(r.uncovered > 0.5 ? [["uncovered", "teils nicht gedeckt"]] : [])]);
  $("bins").querySelectorAll("button").forEach((b) =>
    b.addEventListener("click", () => { binView = b.dataset.view; renderBins(lastResult); }));
}

function renderMonths(r) {
  const iw = W - PAD.l - PAD.r, ih = H - PAD.t - PAD.b, bw = iw / 12;
  const yMax = niceMax(Math.max(...r.months.map((m) => m.hp + m.backup + m.uncovered)));
  const py = (v) => PAD.t + ih - (ih * v) / yMax;
  let bars = "";
  const ticks = [];
  r.months.forEach((m, i) => {
    const x = PAD.l + i * bw;
    ticks.push([x + bw / 2, MONTH_NAMES[i]]);
    bars += `<g><title>${MONTH_NAMES[i]}: WP ${fmt(m.hp)} kWh, Zusatz ${fmt(m.backup)} kWh` +
      (m.uncovered > 0.05 ? `, nicht gedeckt ${fmt(m.uncovered)} kWh` : "") + `</title>` +
      stack(x + 4, bw - 8, py, [["hp", m.hp], ["backup", m.backup], ["uncovered", m.uncovered]]) + `</g>`;
  });
  $("months").innerHTML =
    `<svg viewBox="0 0 ${W} ${H}" role="img" aria-label="Monate">` +
    axes(ticks, yMax, "Wärme [kWh]", "") + bars + `</svg>` +
    legend(energyLegend(r));
}

/** Monthly electricity demand split into PV direct, battery and grid, PV yield as a line. */
function renderPower(r) {
  const b = r.pv;
  const iw = W - PAD.l - PAD.r, ih = H - PAD.t - PAD.b, bw = iw / 12;
  const yMax = niceMax(Math.max(...b.months.map((m) => Math.max(m.pv, m.direct + m.battery + m.grid))));
  const py = (v) => PAD.t + ih - (ih * v) / yMax;
  let bars = "";
  const ticks = [], line = [];
  b.months.forEach((m, i) => {
    const x = PAD.l + i * bw;
    ticks.push([x + bw / 2, MONTH_NAMES[i]]);
    line.push(`${x + bw / 2},${py(m.pv)}`);
    bars += `<g><title>${MONTH_NAMES[i]}: PV direkt ${fmt(m.direct)} kWh, Speicher ${fmt(m.battery)} kWh, Netz ${fmt(m.grid)} kWh, PV-Ertrag ${fmt(m.pv)} kWh</title>` +
      stack(x + 4, bw - 8, py, [["pv", m.direct], ["battery", m.battery], ["grid-el", m.grid]]) + `</g>`;
  });
  $("power").innerHTML =
    `<svg viewBox="0 0 ${W} ${H}" role="img" aria-label="Strom je Monat">` +
    axes(ticks, yMax, "Strom [kWh]", "") + bars + `<polyline class="pvline" points="${line.join(" ")}"/></svg>` +
    legend([["pv", "PV direkt"], ["battery", "aus Speicher"], ["grid-el", "Netzbezug"], ["pv", "PV-Ertrag (Linie)"]]);
}

function renderWwMonths(r) {
  const iw = W - PAD.l - PAD.r, ih = H - PAD.t - PAD.b, bw = iw / 12;
  const yMax = niceMax(Math.max(...r.wwMonths.map((m) => m.hp + m.backup)));
  const py = (v) => PAD.t + ih - (ih * v) / yMax;
  let bars = "";
  const ticks = [];
  r.wwMonths.forEach((m, i) => {
    const x = PAD.l + i * bw;
    ticks.push([x + bw / 2, MONTH_NAMES[i]]);
    bars += `<g><title>${MONTH_NAMES[i]}: WP ${fmt(m.hp)} kWh, Zusatz ${fmt(m.backup)} kWh</title>` +
      stack(x + 4, bw - 8, py, [["ww", m.hp], ["backup", m.backup]]) + `</g>`;
  });
  $("wwMonths").innerHTML =
    `<svg viewBox="0 0 ${W} ${H}" role="img" aria-label="Warmwasser je Monat">` +
    axes(ticks, yMax, "Wärme [kWh]", "") + bars + `</svg>` +
    legend([["ww", "Wärmepumpe"], ["backup", "Zusatzheizung"]]);
}

// ---------- export ----------

function download(name, rows) {
  const csv = rows.map((r) => r.map((v) => (typeof v === "number" ? String(Math.round(v * 1000) / 1000).replace(".", ",") : v)).join(";")).join("\n");
  const a = document.createElement("a");
  a.href = URL.createObjectURL(new Blob(["" + csv], { type: "text/csv;charset=utf-8" }));
  a.download = name;
  a.click();
  URL.revokeObjectURL(a.href);
}

function exportBins() {
  const r = lastResult;
  if (!r) return;
  const m = r.model;
  const rows = [["Außentemperatur °C", "Stunden h/a", "Heizlast kW", "WP-Leistung kW", "Vorlauf °C", "COP", "Wärme kWh/a", "WP kWh/a", "Zusatzheizung kWh/a", "nicht gedeckt kWh/a", "Strom WP kWh/a"]];
  for (const k of [...r.bins.keys()].sort((a, b) => a - b)) {
    const b = r.bins.get(k);
    rows.push([k, b.hours, m.load(k), m.heatPump(k), m.flow(k), m.cop(k), b.hp + b.backup + b.uncovered, b.hp, b.backup, b.uncovered, b.el]);
  }
  download(`bins_${$("plz").value}.csv`, rows);
}

function exportHours() {
  const r = lastResult;
  if (!r) return;
  const ww = r.params.hotWater, b = r.pv;
  const rows = [["Jahr", "Monat", "Tag", "Stunde (UTC)", "Außentemperatur °C", "Heizlast kW", "WP kW", "Zusatzheizung kW", "nicht gedeckt kW", "Strom WP kW",
    ...(ww ? ["Warmwasser WP kW", "Warmwasser Zusatz kW"] : []), ...(b ? ["PV kW", "Netzbezug kW", r.params.feedOn ? "Einspeisung kW" : "Abgeregelt kW"] : [])]];
  r.years.forEach((year, y) => {
    let i = 0;
    MONTH_DAYS.forEach((days, month) => {
      for (let d = 1; d <= days; d++) for (let h = 0; h < 24; h++, i++) {
        const j = y * 8760 + i, q = r.loads[j], hp = r.hps[j], backup = r.backs[j];
        rows.push([year, month + 1, d, h, r.temps[y][i], q, hp, backup, q - hp - backup, r.els[j],
          ...(ww ? [r.wwHps[j], r.wwBacks[j]] : []), ...(b ? [b.pvs[j], b.grids[j], b.feeds[j]] : [])]);
      }
    });
  });
  download(`stunden_${$("plz").value}.csv`, rows);
}

// ---------- init ----------

async function init() {
  [meta, plzMap] = await Promise.all([
    fetch("data/stations.json").then((r) => r.json()),
    fetch("data/plz.json").then((r) => r.json()),
  ]);
  stationById = Object.fromEntries(meta.stations.map((s) => [s.id, s]));
  pvStationById = Object.fromEntries((meta.pvStations || []).map((s) => [s.id, s]));

  $("plz").addEventListener("input", () => { showLocation(); scheduleRun(); });
  $("tn").addEventListener("input", () => { tnEdited = true; });
  $("tnReset").addEventListener("click", () => {
    tnEdited = false;
    if (station && station.tnorm != null) $("tn").value = station.tnorm;
    run();
  });
  $("type").addEventListener("change", onTypeChange);
  $("fuel").addEventListener("change", () => onFuelChange());
  $("tbivAdopt").addEventListener("click", () => {
    // round up to 0.5 K so the heat pump covers everything above the bivalence point
    if (lastResult && lastResult.model.limit != null) $("tbiv").value = Math.ceil(lastResult.model.limit * 2) / 2;
    run();
  });
  onFuelChange(false);
  $("form").addEventListener("input", scheduleRun);
  $("form").addEventListener("change", scheduleRun);
  $("form").addEventListener("submit", (e) => e.preventDefault());
  $("exportBins").addEventListener("click", exportBins);
  $("exportHours").addEventListener("click", exportHours);
  buildStepper();

  showLocation();
  run();
}

init().catch((e) => { $("status").textContent = `Fehler beim Laden: ${e.message}`; });