/* Inbox — the notifications panel as a screen, for when four lines in a popover
   are not enough to work from.
   Commit model: INSTANT. Marking something read is harmless and applies as
   clicked, so there is no Save and no undo toast — reading is not a change to
   the book.
   Data state: populated. Unread and everything are two tabs over one list, not
   two states: the tabs narrow the list only and no figure above them moves.
   Actions derive from the record: every line opens the record it is about, so
   the row's link is the action; a line already read carries no Mark read.
   Primary display: a list grouped by day, because the only ordering that helps
   is the one that answers "what happened while I was out". */
(() => {
  const {
    Button, Badge, Tabs, TabsList, TabsTab,
    Empty, EmptyHeader, EmptyMedia, EmptyTitle, EmptyDescription, EmptyContent,
  } = window.OriginDesignSystem_7c998b;

  const startOfDay = (ts) => { const d = new Date(ts); d.setUTCHours(0, 0, 0, 0); return d.getTime(); };

  const INBOX_TABS = [
    { value: "unread", label: "Unread" },
    { value: "all", label: "Everything" },
  ];

  function InboxScreen({ notifications, readIds, data, now, onNavigate, onRead, onReadAll }) {
    const [tab, setTab] = React.useState("unread");
    const isRead = (n) => readIds.indexOf(n.id) > -1;
    const unread = notifications.filter((n) => !isRead(n));
    const ordered = notifications.slice().sort((a, b) => b.at - a.at);
    const rows = tab === "unread" ? ordered.filter((n) => !isRead(n)) : ordered;
    const days = rows.map((n) => startOfDay(n.at)).filter((d, i, all) => all.indexOf(d) === i);
    const oldest = ordered[ordered.length - 1];

    return (
      <div className="mq-page mq-page--tight">
        <PageHead
          path="/inbox"
          title="Inbox"
          lede={unread.length
            ? unread.length + " of " + notifications.length + " unread. Every line is about a record on the desk and opens it — nothing here is a message you have to answer somewhere else."
            : "Nothing unread. All " + notifications.length + " lines since " + formatAbsolute(oldest.at).split(",")[0] + " are still here, newest first."}
          actions={unread.length ? <Button size="sm" variant="outline" onClick={onReadAll}>Mark all read</Button> : null}
        />

        <section className="mq-section">
          <div className="mq-filters">
            <Tabs value={tab} onValueChange={setTab}>
              <TabsList variant="underline" size="sm">
                {INBOX_TABS.map((t) => (
                  <TabsTab key={t.value} value={t.value} size="sm">
                    {t.label}<span className="mq-tab-count">{t.value === "unread" ? unread.length : notifications.length}</span>
                  </TabsTab>
                ))}
              </TabsList>
            </Tabs>
            <span className="mq-note">Read against unread is the only distinction here; the urgency lives on the record each line points at.</span>
          </div>

          {rows.length === 0 ? (
            <Empty>
              <EmptyHeader>
                <EmptyMedia variant="icon"><Icon name="inbox" size={18} /></EmptyMedia>
                <EmptyTitle>Nothing unread</EmptyTitle>
                <EmptyDescription>All {notifications.length} lines have been read. They are kept, so nothing that happened on the desk disappears when you clear it.</EmptyDescription>
              </EmptyHeader>
              <EmptyContent>
                <Button onClick={() => setTab("all")}>Show everything</Button>
              </EmptyContent>
            </Empty>
          ) : (
            <div className="mq-col">
              {days.map((day) => {
                const onDay = rows.filter((n) => startOfDay(n.at) === day);
                return (
                  <div className="mq-col mq-col--tight" key={day}>
                    <Eyebrow>{formatAbsolute(day).split(",")[0]}{day === startOfDay(now) ? " · today" : ""} · {onDay.length} {onDay.length === 1 ? "line" : "lines"}</Eyebrow>
                    <div className="mq-rows">
                      {onDay.map((n) => {
                        const read = isRead(n);
                        const route = matchRoute(n.route, MARQUE_ROUTES);
                        return (
                          <div className={"mq-row" + (read ? " mq-row--recessed" : "")} key={n.id}>
                            <div className="mq-row__main mq-row__wide">
                              <span className="mq-row__title">
                                <button type="button" className="mq-link" onClick={() => { onRead(n.id); onNavigate(n.route); }}>{n.title}</button>
                                {read ? null : <Badge size="sm" variant="warning" style={{ marginInlineStart: "var(--space-2)" }}>New</Badge>}
                              </span>
                              <span className="mq-row__meta">{n.body}</span>
                            </div>
                            <div className="mq-row__side">
                              <span className="mq-mono mq-muted" title={formatAbsolute(n.at)}>{formatWhen(n.at, now)}</span>
                              <span className="mq-mono mq-muted">{route ? route.label : n.route}</span>
                              {read ? null : <Button variant="ghost" size="xs" onClick={() => onRead(n.id)}>Mark read</Button>}
                            </div>
                          </div>
                        );
                      })}
                    </div>
                  </div>
                );
              })}
              <div className="mq-foot">
                <span>Showing {rows.length} of {notifications.length} lines{tab === "unread" ? " that have not been read" : ""} · newest first</span>
                <span>Oldest {formatAbsolute(oldest.at).split(",")[0]}</span>
              </div>
            </div>
          )}
        </section>
      </div>
    );
  }

  Object.assign(window, { InboxScreen, INBOX_TABS });
})();
