/* Energy — fourteen days, the tariff, the battery, the water.
   Commit model: INSTANT. Selecting a day is a bare control (harmless); setting
   the battery mode applies immediately with an undo toast.

   The period control is a SCOPE filter (§5.3): it sits above the figures and
   moves them. Selecting a day in the chart narrows the detail below the chart
   only, and the figures do not move with it — the chart says which.
   costOf in metrics.js is the only place a tariff rate is applied. */
(() => {
  const { Button, Badge, Alert, AlertTitle, AlertDescription, Select, Tabs, TabsList, TabsTab } = window.OriginDesignSystem_7c998b;

  const PERIODS = [
    { value: "7", label: "Last 7 days" },
    { value: "14", label: "Last 14 days" },
  ];

  function EnergyScreen({ data, now, viewer, period, onPeriodChange, onBatteryMode, onNavigate, onExport }) {
    const [picked, setPicked] = React.useState(null);
    const all = data.energy;
    /* Scoped first: every figure below is computed from this array. */
    const days = all.slice(-Number(period));
    const complete = energyComplete(days);
    const today = energyToday(all);
    const window_ = windowAt(now);
    const upcoming = nextWindow(now);
    const advice = batteryAdvice(data.battery, now);
    const draw = drawByRoom(data.devices);
    const water = data.water;
    const leak = leakVerdict(water);
    const selected = picked == null ? null : days[picked];
    const worst = worstDay(days);

    return (
      <>
        <PageHead path="/energy" title="Energy"
          lede={"Electricity, the tariff it is bought on, the battery and the water. " + TARIFF.name + " from " + TARIFF.supplier + " — three rates, and the house buys what it can inside the cheap one."}
          actions={
            <>
              <Button variant="outline" size="sm" onClick={() => onNavigate("/spend")}><Icon name="receipt" />Bills</Button>
              <ExportMenu scope={days.length + " days of readings"} onExport={(format) => onExport("Energy", "The last " + days.length + " days", days.length, format)} />
            </>
          } />

        <Band>
          <Card tint>
            <div style={{ display: "flex", flexWrap: "wrap", alignItems: "center", gap: "var(--space-3) var(--space-4)" }}>
              <span className="hh-fig__label">Period</span>
              <span className="hh-filters__select">
                <Select size="sm" aria-label="Scope every figure on this screen to a period" items={PERIODS} value={period} onValueChange={(v) => { onPeriodChange(v); setPicked(null); }} />
              </span>
              <p className="hh-card__note" style={{ flex: 1, minWidth: "16rem", margin: 0 }}>
                Counting the {days.length} days to {new Date(today.at).toLocaleDateString("en-GB", { day: "numeric", month: "long" })}, with today still running.
              </p>
              <span className="hh-footnote">{window_.label} rate now, {window_.pencePerKwh}p · {upcoming.window.label.toLowerCase()} in {Math.floor(upcoming.minutesAway / 60)}h {upcoming.minutesAway % 60}m</span>
            </div>
          </Card>
        </Band>

        <Figures items={[
          { label: "Used", value: formatKwh(kwhSum(days)), unit: "kWh", qualifier: "over " + days.length + " days · " + formatKwh(averageDayKwh(days)) + " a day on the " + complete.length + " complete ones" },
          { label: "Cost", value: formatPounds(costSum(days)), qualifier: "at " + tariffWindow("off_peak").pencePerKwh + "p off-peak and " + tariffWindow("standard").pencePerKwh + "p otherwise, plus " + HOUSE_POLICY.standingChargePence + "p a day standing charge" },
          { label: "From the roof", value: formatKwh(solarSum(days)), unit: "kWh", qualifier: formatKwh(exportSum(days)) + " kWh exported, worth " + formatPounds(exportValue(days)) + " back" },
          { label: "Worst day", value: formatKwh(worst.kwh), unit: "kWh", qualifier: new Date(worst.at).toLocaleDateString("en-GB", { weekday: "long" }) + " · " + formatPounds(dayCost(worst)) + " · " + Math.round(worst.offPeakShare * 100) + "% off-peak" },
        ]} />

        <div className="hh-cols hh-cols--wide">
          <div>
            <Card title="Day by day" note="The dark part of each bar is what was bought inside a cheap window. Choose a day to read it below.">
              <DayBars days={days} selected={picked} onSelect={setPicked}
                valueOf={(d) => d.kwh}
                softOf={(d) => d.kwh * (1 - d.offPeakShare)}
                tickOf={(d, i) => (days.length > 7 && i % 2 ? "" : new Date(d.at).toLocaleDateString("en-GB", { weekday: "narrow" }))}
                labelOf={(d) => new Date(d.at).toLocaleDateString("en-GB", { weekday: "long", day: "numeric", month: "short" }) + ": " + formatKwh(d.kwh) + " kWh, " + formatPounds(dayCost(d))} />
              <div style={{ marginTop: "var(--space-4)" }}>
                <Legend items={[{ label: "Bought off-peak" }, { label: "Bought at standard rate", kind: "soft" }]} />
              </div>
              {selected ? (
                <div style={{ marginTop: "var(--space-4)", paddingTop: "var(--space-4)", borderTop: "1px solid var(--border)" }}>
                  <Rows>
                    <Row title={new Date(selected.at).toLocaleDateString("en-GB", { weekday: "long", day: "numeric", month: "long" }) + (selected.partial ? " — still running" : "")}
                      note={formatKwh(selected.kwh) + " kWh · " + Math.round(selected.offPeakShare * 100) + "% off-peak · " + formatKwh(selected.solarKwh) + " kWh from the roof · " + formatKwh(selected.exportKwh) + " kWh exported"}
                      value={formatPounds(dayCost(selected))} />
                  </Rows>
                  <Button variant="ghost" size="xs" onClick={() => setPicked(null)}>Clear the day</Button>
                </div>
              ) : null}
            </Card>

            <Card title="The tariff, across a day" note="Where the cheap and expensive windows fall. The mark is now.">
              <DayStrip now={now} label="Tariff windows across the day"
                toneOf={(hour) => {
                  const off = tariffWindow("off_peak"), peak = tariffWindow("peak");
                  if (hour >= parseClock(off.from) / 60 && hour < parseClock(off.to) / 60) return "off";
                  if (hour >= parseClock(peak.from) / 60 && hour < parseClock(peak.to) / 60) return "peak";
                  return undefined;
                }} />
              <div style={{ marginTop: "var(--space-4)" }}>
                <Legend items={[
                  { label: "Off-peak " + tariffWindow("off_peak").from + "–" + tariffWindow("off_peak").to + ", " + tariffWindow("off_peak").pencePerKwh + "p", kind: "off" },
                  { label: "Peak " + tariffWindow("peak").from + "–" + tariffWindow("peak").to + ", " + tariffWindow("peak").pencePerKwh + "p", kind: "peak" },
                  { label: "Standard " + tariffWindow("standard").pencePerKwh + "p", kind: "soft" },
                ]} />
              </div>
              <p className="hh-footnote" style={{ marginTop: "var(--space-3)" }}>
                Set in <button type="button" className="hh-linkbtn" onClick={() => onNavigate("/settings/tariff")}>Settings → Tariff and meters</button>, and read by the battery, the routines and every cost on this screen.
              </p>
            </Card>

            <Card title="Water" note="Litres a day, and the overnight figure a slow leak shows up in.">
              <DayBars days={water} selected={null}
                valueOf={(d) => d.litres}
                softOf={(d) => d.overnightLitres}
                tickOf={(d) => new Date(d.at).toLocaleDateString("en-GB", { weekday: "narrow" })}
                labelOf={(d) => new Date(d.at).toLocaleDateString("en-GB", { weekday: "long" }) + ": " + d.litres + " litres, " + d.overnightLitres + " of them overnight"} />
              <div style={{ marginTop: "var(--space-4)" }}>
                <Legend items={[{ label: "Daytime" }, { label: "Overnight, when the house is asleep", kind: "soft" }]} />
              </div>
              {leak ? (
                <div style={{ marginTop: "var(--space-4)" }}>
                  <Alert variant="warning">
                    <AlertTitle>Water is moving overnight, {leak.nights} nights running</AlertTitle>
                    <AlertDescription>
                      {leak.perNight} litres a night since {formatWhen(leak.since, now)}, against 4 to 6 on a normal night — {leak.litres} litres in total. A running overflow or a cistern valve would look exactly like this, and the {labelOf(BILL_KINDS, "water").toLowerCase()} bill for this period is already {formatPounds(data.bills.find((b) => b.id === "bil_02").amountMinor - data.bills.find((b) => b.id === "bil_02").forecastMinor)} above its forecast.
                    </AlertDescription>
                  </Alert>
                </div>
              ) : null}
              <p className="hh-footnote" style={{ marginTop: "var(--space-3)" }}>
                {Math.round(waterAverage(water))} litres a day on average across the {waterComplete(water).length} complete days.
              </p>
            </Card>
          </div>

          <div>
            <Card title="The battery" note="What it ought to be doing is worked out from the tariff and its charge, not stored.">
              <div className="hh-dial" style={{ alignItems: "flex-start", minWidth: 0 }}>
                <span className="hh-dial__reading">{data.battery.chargePercent}<span>%</span></span>
                <span className="hh-dial__target" style={{ textAlign: "left" }}>{formatKwh((data.battery.chargePercent / 100) * data.battery.capacityKwh)} kWh of {data.battery.capacityKwh} kWh</span>
              </div>
              <div style={{ marginTop: "var(--space-4)" }}>
                <Bar percent={data.battery.chargePercent} tone={data.battery.chargePercent < 25 ? "warn" : "good"} label="Battery charge" />
              </div>
              <Rows>
                <Row title={advice.line} note={advice.detail} />
                <Row title="Today" note={formatKwh(data.battery.chargedTodayKwh) + " kWh in, " + formatKwh(data.battery.dischargedTodayKwh) + " kWh out · " + formatCount(data.battery.cycles) + " cycles since it was fitted"} />
              </Rows>
              <div style={{ marginTop: "var(--space-4)", paddingTop: "var(--space-3)", borderTop: "1px solid var(--border)" }}>
                <span className="hh-fig__label" style={{ display: "block", marginBottom: "var(--space-2)" }}>How it decides</span>
                <Tabs value={data.battery.mode} onValueChange={onBatteryMode}>
                  <TabsList>
                    <TabsTab value="tariff" size="sm">Follow the tariff</TabsTab>
                    <TabsTab value="solar" size="sm">Store the roof</TabsTab>
                    <TabsTab value="hold" size="sm">Hold charge</TabsTab>
                  </TabsList>
                </Tabs>
                <p className="hh-footnote" style={{ marginTop: "var(--space-2)" }}>
                  {data.battery.mode === "tariff" ? "Charging inside the off-peak window and running the house through the peak one."
                    : data.battery.mode === "solar" ? "Only charging from the roof, so nothing is bought to fill it."
                      : "Keeping what it has for a power cut, and neither charging nor discharging."}
                </p>
              </div>
            </Card>

            <Card title="From the roof" note="Today against what the array can do at its best.">
              <Rows>
                <Row title="Generated today" value={formatKwh(data.solar.todayKwh) + " kWh"}
                  note={"Best " + formatKwh(data.solar.bestTodayKw) + " kW at " + new Date(data.solar.bestAt).toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" }) + " · " + data.solar.peakKwp + " kWp fitted"} />
                <Row title="Generating now" value={formatKwh(data.solar.nowKw) + " kW"} note={isDark(now) ? "Dark since " + HOUSE_POLICY.darkAfter : "Daylight"} />
                <Row title="Exported today" value={formatKwh(today.exportKwh) + " kWh"} note={"Worth " + formatPounds(Math.round(today.exportKwh * TARIFF.exportPencePerKwh)) + " at " + TARIFF.exportPencePerKwh + "p"} />
              </Rows>
            </Card>

            <Card title="Where it is going, now" note="Every device drawing power, grouped by room — the same array the device table renders.">
              <Rows>
                {draw.map((row) => (
                  <Row key={row.room} title={row.label} value={formatWatts(row.watts)}
                    note={row.devices.map((d) => d.name.toLowerCase()).join(", ")}>
                    <span style={{ width: "5rem" }}>
                      <Bar percent={(row.watts / Math.max(1, liveWatts(data.devices))) * 100} label={row.label + " share"} />
                    </span>
                  </Row>
                ))}
              </Rows>
              <p className="hh-footnote" style={{ marginTop: "var(--space-3)" }}>
                {formatWatts(liveWatts(data.devices))} across {devicesDrawing(data.devices).length} devices · <button type="button" className="hh-linkbtn" onClick={() => onNavigate("/devices")}>the device list</button>
              </p>
            </Card>
          </div>
        </div>
      </>
    );
  }

  Object.assign(window, { EnergyScreen });
})();
