/* Rooms — a canvas of room cards, each with the controls that room actually has.
   Commit model: INSTANT. A switch applies immediately; a lock raises an undo
   toast; nothing here has a Save.

   No /rooms/:id: this screen holds every room at once, which is what a house is,
   and a room has no fact a card cannot carry. */
(() => {
  const { Button, Badge, Switch, Select } = window.OriginDesignSystem_7c998b;

  function RoomCard({ room, data, now, viewer, onNavigate, onToggleDevice, onDeviceTransition, onZoneStep }) {
    const zone = room.zone;
    return (
      <Card fill>
        <div className="hh-room__top">
          <div style={{ minWidth: 0 }}>
            <div className="hh-room__name">{room.label}</div>
            <div className="hh-footnote">
              {room.devices.length ? room.on.length + " of " + room.devices.length + " on · " + formatWatts(room.watts) : "No devices in here"}
              {room.people.length ? " · " + room.people.map((p) => p.name.split(" ")[0]).join(" and ") + " here" : ""}
            </div>
          </div>
          {zone ? (
            <div style={{ textAlign: "right" }}>
              <div className="hh-room__temp">{formatTemp(zone.reportedC)}<span>°</span></div>
              <div className="hh-footnote">{zoneName(zone.id)} · {formatTemp(zone.targetC)}° wanted</div>
            </div>
          ) : null}
        </div>

        <Rows>
          {room.devices.map((device) => (
            <Row key={device.id} recessed={DEVICE_FLAGS.recessed(device)}
              title={<button type="button" className="hh-linkbtn" onClick={() => onNavigate("/devices/" + device.id)}>{device.name}</button>}
              note={labelOf(DEVICE_KINDS, device.kind) + (DEVICE_FLAGS.drawing(device) ? " · " + formatWatts(device.watts) : "") + (DEVICE_FLAGS.lowBattery(device) ? " · battery " + device.battery + "%" : "")}>
              {DEVICE_FLAGS.needsYou(device) ? <StatusBadge values={DEVICE_STATUS} value={device.status} /> : null}
              <DeviceControl device={device} viewer={viewer} onToggle={onToggleDevice} onRun={onDeviceTransition} />
            </Row>
          ))}
          {room.entries.map((entry) => (
            <Row key={entry.id} title={entry.label}
              note={labelOf(ENTRY_KINDS, entry.kind) + " · " + formatWhen(entry.changedAt, now) + (entry.byId ? " by " + memberName(data.members, entry.byId).split(" ")[0] : "")}>
              <StatusBadge values={ENTRY_STATUS} value={entry.status} />
              {ENTRY_FLAGS.insecure(entry, data.house.alarm, now) ? <Badge size="sm" variant="warning">Not secure</Badge> : null}
            </Row>
          ))}
        </Rows>

        {zone ? (
          <div className="hh-room__foot">
            <span className="hh-footnote">
              {zone.status === "off" ? "Heating off" : ZONE_FLAGS.callingForHeat(zone) ? "Calling for heat" : "At temperature"}
              {zone.overrideUntil ? " · boost until " + formatWhen(zone.overrideUntil, now) : ""}
            </span>
            <span className="hh-stepper">
              <Button variant="ghost" size="icon-xs" aria-label={"Cooler in the " + zoneName(zone.id).toLowerCase()} onClick={() => onZoneStep(zone, -0.5)}><Icon name="minus" size={14} /></Button>
              <span style={{ fontSize: "var(--text-xs)", fontVariantNumeric: "tabular-nums", minWidth: "2.6rem", textAlign: "center" }}>{formatTemp(zone.targetC)}°</span>
              <Button variant="ghost" size="icon-xs" aria-label={"Warmer in the " + zoneName(zone.id).toLowerCase()} onClick={() => onZoneStep(zone, 0.5)}><Icon name="plus" size={14} /></Button>
            </span>
          </div>
        ) : null}
      </Card>
    );
  }

  function RoomsScreen({ data, now, viewer, onNavigate, onToggleDevice, onDeviceTransition, onZoneStep, onAllOff, onNewDevice }) {
    const [only, setOnly] = React.useState("all");
    const rooms = roomRows(data, now);
    /* The filter narrows the canvas only; the lede states the scope in words. */
    const shown = only === "all" ? rooms
      : only === "on" ? rooms.filter((r) => r.on.length)
        : only === "people" ? rooms.filter((r) => r.people.length)
          : rooms.filter((r) => r.needsYou.length || r.insecure.length);
    const lit = rooms.filter((r) => r.on.length);

    return (
      <>
        <PageHead path="/rooms" title="Rooms"
          lede={lit.length + " of " + rooms.length + " rooms have something on, drawing " + formatWatts(liveWatts(data.devices)) + " between them."}
          actions={
            <>
              <span className="hh-filters__select">
                <Select size="sm" aria-label="Which rooms to show" value={only} onValueChange={setOnly}
                  items={[
                    { value: "all", label: "Every room (" + rooms.length + ")" },
                    { value: "on", label: "Something on (" + lit.length + ")" },
                    { value: "people", label: "Somebody in (" + rooms.filter((r) => r.people.length).length + ")" },
                    { value: "attention", label: "Wants a person (" + rooms.filter((r) => r.needsYou.length || r.insecure.length).length + ")" },
                  ]} />
              </span>
              <Button variant="outline" size="sm" onClick={onAllOff} disabled={!lit.length}>Everything off downstairs</Button>
              <Button size="sm" onClick={() => onNewDevice(null)}><Icon name="plus" />Pair a device</Button>
            </>
          } />
        {shown.length ? (
          <div className="hh-roomgrid">
            {shown.map((room) => (
              <RoomCard key={room.room} room={room} data={data} now={now} viewer={viewer}
                onNavigate={onNavigate} onToggleDevice={onToggleDevice} onDeviceTransition={onDeviceTransition} onZoneStep={onZoneStep} />
            ))}
          </div>
        ) : (
          <Band><Card><NoResults noun="rooms" onClear={() => setOnly("all")} /></Card></Band>
        )}
      </>
    );
  }

  Object.assign(window, { RoomsScreen, RoomCard });
})();
