/* Log — what happened. Commit model: INSTANT, and in practice read-only: a log
   is never work, so this destination carries no badge and no action beyond
   opening the record an entry names.

   A day ladder rather than a table: the question is "what has the house been
   doing", which is answered by time, and the kind filter narrows the ladder
   without moving the figures above it (§5.3). */
(() => {
  const { Button, Badge, Select, Avatar } = window.OriginDesignSystem_7c998b;

  const KIND_FILTER = [{ value: "all", label: "Everything" }].concat(EVENT_KINDS);

  function LogScreen({ data, now, viewer, onNavigate, onExport }) {
    const [kind, setKind] = React.useState("all");
    const [query, setQuery] = React.useState("");

    const all = eventsNewestFirst(data.events);
    const today = eventsToday(all, now);
    const people = all.filter((e) => e.actorId).reduce((list, e) => (list.indexOf(e.actorId) > -1 ? list : list.concat([e.actorId])), []);
    const byHouse = all.filter((e) => !e.actorId);

    const dirty = !!query || kind !== "all";
    const clear = () => { setQuery(""); setKind("all"); };
    const shown = all.filter((event) => {
      if (kind !== "all" && event.kind !== kind) return false;
      if (query && (event.line + " " + (event.note || "") + " " + (event.actorId ? memberName(data.members, event.actorId) : "")).toLowerCase().indexOf(query.toLowerCase()) < 0) return false;
      return true;
    });

    /* Grouped by day, in the order the ladder reads. */
    const days = shown.reduce((groups, event) => {
      const key = new Date(event.at).toDateString();
      const found = groups.find((g) => g.key === key);
      if (found) found.events.push(event);
      else groups.push({ key: key, at: event.at, events: [event] });
      return groups;
    }, []);

    return (
      <>
        <PageHead path="/log" title="Log"
          lede={all.length + " entries on the record. Today says what is true now and Routines what happens next; this is the only screen that says what happened."}
          actions={<ExportMenu scope={dirty ? shown.length + " entries matching the filters" : "All " + all.length + " entries"} onExport={(format) => onExport("Log", dirty ? "The filtered log" : "The whole log", shown.length, format)} />} />

        <Figures items={[
          { label: "Today", value: today.length, qualifier: today.filter((e) => e.actorId).length + " by somebody, " + today.filter((e) => !e.actorId).length + " by the house itself" },
          { label: "On the record", value: all.length, qualifier: "back to " + formatWhen(all[all.length - 1].at, now) },
          { label: "People who did something", value: people.length, qualifier: people.map((id) => memberName(data.members, id).split(" ")[0]).join(", ") },
          { label: "The house on its own", value: byHouse.length, qualifier: "routines, sensors and devices reporting without anybody asking" },
        ]} />

        <Band>
          <Card flush>
            <FilterBar query={query} onQuery={setQuery} placeholder="Search the log…" dirty={dirty} onClear={clear}
              selects={[{ id: "kind", label: "Kind", items: KIND_FILTER, value: kind, onChange: setKind }]} />
            {shown.length === 0 ? <NoResults noun="entries" onClear={clear} /> : (
              <div style={{ paddingInline: "var(--card-pad)" }}>
                {days.map((day) => (
                  <div key={day.key} style={{ marginBottom: "var(--space-5)" }}>
                    <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", gap: "var(--space-3)", marginBottom: "var(--space-2)" }}>
                      <span className="hh-row__title">
                        {new Date(day.at).toDateString() === new Date(now).toDateString() ? "Today" : new Date(day.at).toLocaleDateString("en-GB", { weekday: "long", day: "numeric", month: "long" })}
                      </span>
                      <span className="hh-footnote">{day.events.length} {day.events.length === 1 ? "entry" : "entries"}</span>
                    </div>
                    <Rows>
                      {day.events.map((event) => {
                        const actor = event.actorId ? memberById(data.members, event.actorId) : null;
                        return (
                          <Row key={event.id}
                            title={
                              <>
                                <button type="button" className="hh-linkbtn" onClick={() => onNavigate(eventRoute(event))}>{event.line}</button>
                                <Badge size="sm" variant="secondary">{labelOf(EVENT_KINDS, event.kind)}</Badge>
                              </>
                            }
                            note={event.note || null}
                            value={<span className="hh-footnote" title={formatAbsolute(event.at)}>{new Date(event.at).toLocaleTimeString("en-GB", { hour: "2-digit", minute: "2-digit" })}</span>}>
                            {actor ? (
                              <FloatingTip label={actor.name + " · " + labelOf(HOUSEHOLD_ROLES, actor.role)} side="left">
                                <span style={{ display: "inline-flex" }}><Avatar size={26} src={actor.avatar} alt={actor.name} fallback={initialsOf(actor.name)} /></span>
                              </FloatingTip>
                            ) : (
                              <FloatingTip label="The house did this on its own" side="left">
                                <span style={{ display: "inline-flex", color: "var(--muted-foreground)" }}><Icon name="house" size={18} /></span>
                              </FloatingTip>
                            )}
                          </Row>
                        );
                      })}
                    </Rows>
                  </div>
                ))}
                <div className="hh-tablefoot" style={{ paddingInline: 0 }}>
                  <span className="hh-footnote">Showing {shown.length} of {all.length} entries</span>
                </div>
              </div>
            )}
          </Card>
        </Band>
      </>
    );
  }

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