/* Security — the alarm, then every way into the house.
   Commit model: INSTANT. Arming, locking and unlocking apply immediately and
   raise an undo toast; calling the response company is irreversible in the sense
   that matters, so it confirms first (from App.jsx).

   A board rather than a table: the question is "is the house shut", and an entry
   is only insecure against the alarm and the clock — ENTRY_FLAGS.insecure is the
   one predicate the row, the section count and the nav badge all read. */
(() => {
  const { Button, Badge, Alert, AlertTitle, AlertDescription, Avatar } = window.OriginDesignSystem_7c998b;

  function SecurityScreen({ data, now, viewer, onNavigate, onArm, onEntry, onCallResponse, onDeviceTransition, onExport }) {
    const verdict = securityVerdict(data, now);
    const insecure = entriesInsecure(data, now);
    const blocking = entriesBlockingArming(data.entries);
    const cameras = cameraRows(data);
    const watching = camerasWatching(cameras);
    const grants = grantsLive(data.grants);
    const events = eventsOfKind(eventsNewestFirst(data.events), "security");
    const secure = data.entries.filter((e) => insecure.indexOf(e) < 0);

    return (
      <>
        <PageHead path="/security" title="Security"
          lede={"Ten ways into the house. An entry counts as insecure against the alarm and the clock — an open window at four in the afternoon is a window; the same window armed away is why the alarm exists."}
          actions={
            <>
              <Button variant="outline" size="sm" onClick={() => onNavigate("/cameras")}><Icon name="video" />Cameras</Button>
              <ExportMenu scope={"All " + data.entries.length + " ways in and " + grants.length + " live grants"} onExport={(format) => onExport("Security", "Ways in and who can use them", data.entries.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 22rem" }}>
                <span className="hh-actions__row" style={{ marginBottom: "var(--space-2)" }}>
                  <StatusBadge values={ALARM_STATUS} value={data.house.alarm} />
                  <span className="hh-footnote">since {formatWhen(data.house.alarmChangedAt, now)}, by {memberName(data.members, data.house.alarmChangedById)}</span>
                </span>
                <VerdictLine verdict={verdict} />
                <p className="hh-card__note">{verdict.detail}</p>
                <span className="hh-actions__row" style={{ marginTop: "var(--space-4)" }}>
                  <Transitions transitions={armTransitions(data, viewer)} onRun={onArm} />
                  {data.house.alarm === "triggered" ? null : <Button variant="ghost" size="sm" onClick={onCallResponse}>Call Sentinel Response</Button>}
                </span>
              </div>
              <div style={{ flex: "0 1 16rem", minWidth: 0 }}>
                <span className="hh-fig__label">Monitoring</span>
                <p className="hh-footnote" style={{ marginTop: "var(--space-2)" }}>
                  {providerName(data.providers, "prv_05")} · {RESIDENCE.responseNumber}<br />
                  Calls {memberName(data.members, "mem_01").split(" ")[0]}, then {memberName(data.members, "mem_02").split(" ")[0]}, then the police.
                </p>
                <p className="hh-footnote">Last armed away {formatWhen(data.house.lastArmedAwayAt, now)}.</p>
              </div>
            </div>
          </Card>
        </Band>

        <Figures items={[
          { label: "Not secure", value: insecure.length, unit: "of " + data.entries.length, qualifier: insecure.length ? insecure.map((e) => e.label.toLowerCase()).join(", ") : "everything is shut and locked" },
          { label: "Would block arming", value: blocking.length, qualifier: blocking.length ? blocking.map((e) => e.label.toLowerCase()).join(", ") + " — open or not reporting" : "the house can be armed as it stands" },
          { label: "Cameras watching", value: watching.length, unit: "of " + cameras.length, qualifier: camerasNotWatching(cameras).map((c) => c.name.toLowerCase() + " " + (c.shuttered ? "has its shutter closed" : statusValue(DEVICE_STATUS, c.device ? c.device.status : "offline").label.toLowerCase())).join(", ") || "all of them online, recording and open" },
          { label: "Ways in handed out", value: grants.length, qualifier: grantsExpiringSoon(data.grants, now).length + " expiring within " + HOUSE_POLICY.accessExpirySoonDays + " days, " + grantsNeverUsed(data.grants).length + " never used" },
        ]} />

        {insecure.length ? (
          <Band>
            <Card flush title={"Not secure (" + insecure.length + ")"} note="Each one says what it is, and what the house would do about it if it were armed.">
              <div style={{ paddingInline: "var(--card-pad)" }}>
                <Rows>
                  {insecure.map((entry) => (
                    <Row key={entry.id} title={entry.label}
                      note={roomName(entry.room) + " · " + labelOf(ENTRY_KINDS, entry.kind) + " · " + statusValue(ENTRY_STATUS, entry.status).label.toLowerCase() + " since " + formatWhen(entry.changedAt, now) + (entry.byId ? ", " + memberName(data.members, entry.byId) : "")}
                      meta={entry.status === "unknown"
                        ? "Its sensor stopped reporting — the house cannot tell whether it is open, so arming would fault."
                        : ENTRY_FLAGS.wouldBlockArming(entry) ? "Arming the house now would fault immediately."
                          : "It is dark, so an unlocked door counts against the house."}>
                      <StatusBadge values={ENTRY_STATUS} value={entry.status} />
                      <Transitions transitions={entryTransitions(entry, data, viewer)} onRun={(t) => onEntry(entry, t)} />
                    </Row>
                  ))}
                </Rows>
              </div>
            </Card>
          </Band>
        ) : null}

        <div className="hh-cols hh-cols--wide">
          <div>
            <Card flush title={"Everything shut (" + secure.length + ")"} note="Locked, or reported closed by a sensor that is still talking to the house.">
              <div style={{ paddingInline: "var(--card-pad)" }}>
                <Rows>
                  {secure.map((entry) => {
                    const holders = grantsForEntry(data.grants, entry.id);
                    return (
                      <Row key={entry.id} title={entry.label}
                        note={roomName(entry.room) + " · " + formatWhen(entry.changedAt, now) + (entry.byId ? " by " + memberName(data.members, entry.byId).split(" ")[0] : "")}
                        meta={holders.length ? holders.length + (holders.length === 1 ? " grant opens it: " : " grants open it: ") + holders.map((g) => g.label.toLowerCase()).join(", ") : "No grant opens it"}>
                        <StatusBadge values={ENTRY_STATUS} value={entry.status} />
                        <Transitions transitions={entryTransitions(entry, data, viewer)} onRun={(t) => onEntry(entry, t)} />
                      </Row>
                    );
                  })}
                </Rows>
              </div>
            </Card>
          </div>

          <div>
            <Card title={"Cameras (" + cameras.length + ")"} note="Watching means online, recording and the shutter open — the same predicate the cameras screen and the sidebar count read."
              actions={<Button variant="outline" size="sm" onClick={() => onNavigate("/cameras")}>Live view</Button>}>
              <Rows>
                {cameras.map((camera) => (
                  <Row key={camera.id} recessed={camera.recessed}
                    title={<button type="button" className="hh-linkbtn" onClick={() => onNavigate("/cameras")}>{camera.name}</button>}
                    note={camera.view + " · " + (camera.watching ? "watching, last frame " + formatWhen(camera.device.lastSeenAt, now) : camera.shuttered ? "shutter closed on purpose, recording nothing" : camera.device && camera.device.status === "setup_pending" ? "added " + formatWhen(camera.device.addedAt, now) + ", never commissioned" : "not answering")}>
                    {camera.device ? <StatusBadge values={DEVICE_STATUS} value={camera.device.status} /> : null}
                    {camera.shuttered ? <Badge size="sm" variant="secondary">Shutter closed</Badge> : null}
                    {camera.device && camera.device.status === "setup_pending" ? <Transitions transitions={deviceTransitions(camera.device, viewer).filter((t) => t.primary)} onRun={(t) => onDeviceTransition(camera.device, t)} /> : null}
                  </Row>
                ))}
              </Rows>
              <p className="hh-footnote" style={{ marginTop: "var(--space-3)", paddingTop: "var(--space-3)", borderTop: "1px solid var(--border)" }}>
                The monitoring renewal is priced on the cameras being live — <button type="button" className="hh-linkbtn" onClick={() => onNavigate("/upkeep/job_08")}>commissioning is job 08</button>.
              </p>
            </Card>

            <Card title={"Who can get in (" + grants.length + ")"} note="Every way in that is not a person."
              actions={<Button variant="outline" size="sm" onClick={() => onNavigate("/access")}>All access</Button>}>
              <Rows>
                {grants.map((grant) => (
                  <Row key={grant.id} title={grant.label}
                    note={grant.holder + " · " + labelOf(ACCESS_KINDS, grant.kind) + " · " + grant.entryIds.map((id) => (entryById(data.entries, id) || {}).label).join(", ")}>
                    <StatusBadge values={ACCESS_STATUS} value={grant.status} />
                    {ACCESS_FLAGS.expiringSoon(grant, now) ? <Badge size="sm" variant="warning">{formatCountdown(grant.endsAt, now)}</Badge> : null}
                    {ACCESS_FLAGS.neverUsed(grant) ? <Badge size="sm" variant="secondary">Never used</Badge> : null}
                  </Row>
                ))}
              </Rows>
            </Card>

            <Card title={"Security in the log (" + events.length + ")"} note="Doors, windows, gates and the alarm.">
              <Rows>
                {events.map((event) => (
                  <Row key={event.id}
                    title={<button type="button" className="hh-linkbtn" onClick={() => onNavigate(eventRoute(event))}>{event.line}</button>}
                    note={(event.actorId ? memberName(data.members, event.actorId) + " · " : "") + (event.note || "")}
                    value={<span className="hh-footnote" title={formatAbsolute(event.at)}>{formatWhen(event.at, now)}</span>} />
                ))}
              </Rows>
            </Card>
          </div>
        </div>
      </>
    );
  }

  /* An entry's transitions: what the house can do about this door or window now.
     Lives here because it is a screen-level composition over the lock device the
     entry names, not a stored state of its own. */
  function entryTransitions(entry, data, viewer) {
    const may = ROLE_CAN_UNLOCK[viewer.role];
    const gate = (t) => Object.assign({}, t, may ? {} : { disabled: true, disabledReason: "Doors and windows are an adult's to move. You are signed in as " + labelOf(HOUSEHOLD_ROLES, viewer.role).toLowerCase() + "." });
    if (entry.status === "unknown") {
      const device = entry.deviceId ? deviceById(data.devices, entry.deviceId) : null;
      return device ? [{ id: "open_device", label: "Open the sensor", primary: true, deviceId: device.id }] : [];
    }
    if (entry.status === "open") return [{ id: "acknowledge", label: "I have shut it", primary: true }];
    if (entry.status === "unlocked") return [gate({ id: "lock", label: "Lock", primary: true })];
    return [gate({ id: "unlock", label: "Unlock" })];
  }

  Object.assign(window, { SecurityScreen, entryTransitions });
})();
