/* Cameras — the live view, then the four cameras, then what they caught.
   Commit model: INSTANT. A shutter, a floodlight and a clip apply immediately
   and raise an undo toast where the move is consequential; commissioning a
   camera that has never been set up is the pairing flow, opened from Devices.

   The focused camera is a STATE of this screen, not a route (§nav.js): a camera
   has no fact a card cannot carry, so /cameras/:id would be a screen invented to
   make a link resolve.

   Watching is derived from three facts at once — online, recording, shutter open
   — and CAMERA_FLAGS.watching is the one predicate the tile, the verdict, the
   count and the nav badge all read. Nothing stores it.

   Role: the live view and the clips are an adult's. A child sees the screen and
   is told why it is empty rather than being shown a wall of disabled buttons. */
(() => {
  const { Button, Badge, Switch } = window.OriginDesignSystem_7c998b;

  function CamerasScreen({ data, now, viewer, onNavigate, onCameraAction, onCameraPrivacy, onDeviceTransition, onExport }) {
    const rows = cameraRows(data);
    const may = ROLE_CAN_WATCH[viewer.role];
    const [focusId, setFocusId] = React.useState(() => (camerasWatching(rows)[0] || rows[0]).id);
    const focus = rows.find((c) => c.id === focusId) || rows[0];
    const verdict = cameraVerdict(data, now);
    const watching = camerasWatching(rows);
    const today = clipsToday(data.clips, now);
    const clips = clipsNewestFirst(data.clips);

    return (
      <>
        <PageHead path="/cameras" title="Cameras"
          lede={rows.length + " cameras on the outside of the house. A camera counts as watching only when it is online, set to record and its shutter is open — so a closed shutter reads as a decision somebody made, not a fault."}
          actions={
            <>
              <Button variant="outline" size="sm" onClick={() => onNavigate("/settings/data")}><Icon name="clock" />Clips and privacy</Button>
              <ExportMenu scope={clips.length + " clips from the last " + DATA_PREFS.keepClipsDays + " days"}
                onExport={(format) => onExport("Clips", "What the cameras caught", clips.length, format)} />
            </>
          } />

        <Band>
          <Card>
            <div style={{ display: "flex", flexWrap: "wrap", alignItems: "flex-start", justifyContent: "space-between", gap: "var(--space-5)" }}>
              <div style={{ minWidth: 0, flex: "1 1 20rem" }}>
                <VerdictLine verdict={verdict} />
                <p className="hh-card__note">{verdict.detail}</p>
              </div>
              <div style={{ flex: "0 1 15rem", minWidth: 0 }}>
                <span className="hh-fig__label">Caught today</span>
                <p className="hh-footnote" style={{ marginTop: "var(--space-2)" }}>
                  {today.length} clips, the newest {today.length ? formatWhen(today[0].at, now) : "— nothing yet"}.<br />
                  Kept {DATA_PREFS.keepClipsDays} days, then deleted.
                </p>
              </div>
            </div>
          </Card>
        </Band>

        {may ? (
          <div className="hh-cols hh-cols--wide">
            <div>
              <Card title={focus.name} note={focus.view + " · " + focus.resolution + (focus.nightVision ? " · night vision" : "") + " · " + focus.clipSeconds + "-second clips"}>
                <CameraView camera={focus} now={now} tall />
                <div style={{ marginTop: "var(--space-4)", display: "flex", flexWrap: "wrap", alignItems: "center", justifyContent: "space-between", gap: "var(--space-3)" }}>
                  <Transitions transitions={cameraTransitions(focus, viewer)} onRun={(t) => onCameraAction(focus, t)} />
                  <span className="hh-footnote">
                    {focus.blind ? "Nothing is being recorded from this camera." : focus.privacy ? "The shutter is closed, so nothing is recorded until it is opened." : "Recording motion. " + clipsFor(data.clips, focus.id).length + " clips kept from this camera."}
                  </span>
                </div>
              </Card>

              <Card title="Every camera" note="Pick one to watch it. A camera that is not answering falls back to the plain plane rather than showing a picture it does not have.">
                <div className="hh-views">
                  {rows.map((camera) => (
                    <CameraView key={camera.id} camera={camera} now={now} selected={camera.id === focus.id} onClick={() => setFocusId(camera.id)} />
                  ))}
                </div>
              </Card>
            </div>

            <div>
              <Card flush title={"Caught today (" + today.length + " of " + clips.length + ")"} note="Motion the cameras classified themselves.">
                <div style={{ paddingInline: "var(--card-pad)" }}>
                  <Rows>
                    {clips.slice(0, 6).map((clip) => {
                      const camera = rows.find((c) => c.id === clip.deviceId);
                      return (
                        <Row key={clip.id} title={labelOf(CLIP_KINDS, clip.kind)} note={clip.note}
                          value={
                            <span className="hh-actions__row">
                              <span className="hh-footnote" title={formatAbsolute(clip.at)}>{formatWhen(clip.at, now)} · {clip.seconds}s</span>
                              <Button variant="outline" size="sm" onClick={() => { if (camera) setFocusId(camera.id); }}>{camera ? camera.name.split(" ")[0] : "Camera"}</Button>
                            </span>
                          } />
                      );
                    })}
                  </Rows>
                </div>
                <TableFoot shown={Math.min(6, clips.length)} total={clips.length} noun="clips" />
              </Card>

              <Card title="Shutters" note="A closed shutter stops the camera recording anything at all. It is a household decision, so it sits here rather than in settings.">
                <Rows>
                  {rows.map((camera) => (
                    <Row key={camera.id} recessed={camera.recessed} title={camera.name}
                      note={camera.blind ? statusValue(DEVICE_STATUS, camera.device ? camera.device.status : "offline").label + " — the shutter cannot be moved" : camera.privacy ? "Closed" : "Open, recording motion"}
                      value={
                        camera.blind
                          ? <Button variant="outline" size="sm" onClick={() => onNavigate("/devices/" + camera.id)}>Open device</Button>
                          : <Switch checked={!camera.privacy} aria-label={"Shutter open on " + camera.name} onCheckedChange={() => onCameraPrivacy(camera)} />
                      } />
                  ))}
                </Rows>
              </Card>

              <Card tint title="What the house keeps">
                <Pairs items={[
                  { label: "Clips kept", value: DATA_PREFS.keepClipsDays + " days" },
                  { label: "Cameras watching", value: watching.length + " of " + rows.length },
                  { label: "Shutters closed", value: camerasShuttered(rows).length ? camerasShuttered(rows).map((c) => c.name).join(", ") : "None" },
                  { label: "Shared with providers", value: DATA_PREFS.shareWithProviders ? <span>Yes — <button type="button" className="hh-linkbtn" onClick={() => onNavigate("/settings/data")}>change</button></span> : "No" },
                ]} />
              </Card>
            </div>
          </div>
        ) : (
          <Band>
            <Card tint title="The live view is an adult's">
              <p className="hh-card__note">
                You are signed in as {labelOf(HOUSEHOLD_ROLES, viewer.role).toLowerCase()}, and the household's rule is that the cameras and their clips are for the adults. {watching.length} of {rows.length} cameras are watching the outside of the house.
              </p>
              <div style={{ marginTop: "var(--space-4)" }}>
                <Button variant="outline" size="sm" onClick={() => onNavigate("/people/" + viewer.id)}>Your standing in the household</Button>
              </div>
            </Card>
          </Band>
        )}
      </>
    );
  }

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