/* Notifications — the destination behind the bar's panel.
   Commit model: INSTANT. Opening one marks it read; "Mark all read" applies
   immediately and raises an undo toast. No Save button, nothing irreversible.
   Data state: populated, or the no-results branch when the Unread tab is empty
   — one conditional, never both.
   Scope: everything this desk has raised. The tabs narrow the list only; the
   two figures in the header sentence count the whole set either way.

   Every item carries a kind from ALERT_KINDS, which is the same list the alerts
   settings offer, so the footer can say honestly which of these would have
   reached the inbox. */
(() => {
  const {
    Button, Tabs, TabsList, TabsTab,
    Empty, EmptyHeader, EmptyMedia, EmptyTitle, EmptyDescription, EmptyContent,
  } = window.OriginDesignSystem_7c998b;

  const dayLabel = (at, now) => {
    const days = Math.round((new Date(now).setHours(0, 0, 0, 0) - new Date(at).setHours(0, 0, 0, 0)) / 864e5);
    if (days <= 0) return "Today";
    if (days === 1) return "Yesterday";
    return formatAbsolute(at).split(",")[0];
  };

  function NotificationsScreen({ items, readIds, user, now, onNavigate, onOpen, onReadAll }) {
    const [tab, setTab] = React.useState("unread");
    const unread = unreadNotifications(items, readIds);
    const TABS = [
      { value: "unread", label: "Unread", rows: unread },
      { value: "all", label: "All", rows: items },
    ];
    const spec = TABS.find((t) => t.value === tab);
    const days = notificationsByDay(spec.rows, now);
    const emailed = ALERT_KINDS.filter((k) => (user.alerts || []).indexOf(k.value) > -1);
    const wouldEmail = items.filter((n) => (user.alerts || []).indexOf(n.kind) > -1);

    return (
      <div className="cd-page">
        <PageHead
          path="/notifications"
          title="Notifications"
          lede={unread.length
            ? formatPlural(unread.length, "notification") + " you have not opened, of " + formatCount(items.length) + " raised on this desk."
            : "Everything raised on this desk has been opened. " + formatPlural(items.length, "notification") + " in total."}
          actions={unread.length ? <Button variant="outline" size="sm" onClick={onReadAll}>Mark all read</Button> : null}
        />

        <section className="cd-section">
          <div className="cd-filters">
            <p className="cd-note" style={{ maxWidth: "26rem" }}>Opening one marks it read and takes you to the record it names.</p>
            <Tabs value={tab} onValueChange={setTab}>
              <TabsList variant="underline" size="sm">
                {TABS.map((t) => (
                  <TabsTab key={t.value} value={t.value} size="sm">
                    {t.label}<span className="cd-tab-count">{t.rows.length}</span>
                  </TabsTab>
                ))}
              </TabsList>
            </Tabs>
          </div>

          {spec.rows.length === 0 ? (
            <Empty>
              <EmptyHeader>
                <EmptyMedia variant="icon"><Icon name="check" size={18} /></EmptyMedia>
                <EmptyTitle>Nothing unread</EmptyTitle>
                <EmptyDescription>All {formatCount(items.length)} notifications on this desk have been opened.</EmptyDescription>
              </EmptyHeader>
              <EmptyContent>
                <Button onClick={() => setTab("all")}>Show all notifications</Button>
              </EmptyContent>
            </Empty>
          ) : (
            <div className="cd-days">
              {days.map((day) => (
                <div className="cd-day" key={day.key}>
                  <h3 className="cd-day__label">{dayLabel(day.at, now)}</h3>
                  <div className="cd-rows">
                    {day.items.map((n) => {
                      const isUnread = readIds.indexOf(n.id) === -1;
                      return (
                        <button type="button" key={n.id} className={"cd-notice" + (isUnread ? " is-unread" : "")} onClick={() => onOpen(n)}>
                          <span className="cd-notice__dot" aria-hidden="true" />
                          <span className="cd-notice__main">
                            <span className="cd-notice__title">{n.title}</span>
                            <span className="cd-record__meta">{n.body}</span>
                          </span>
                          <span className="cd-notice__side">
                            <span className="cd-record__meta">{labelOf(ALERT_KINDS, n.kind)}</span>
                            <span className="cd-record__meta" title={formatAbsolute(n.at)}>{formatWhen(n.at, now)}</span>
                          </span>
                          {isUnread ? <span className="o-sr">Unread</span> : null}
                        </button>
                      );
                    })}
                  </div>
                </div>
              ))}
            </div>
          )}

          <div className="cd-foot">
            <span>Showing {spec.rows.length} of {formatPlural(items.length, "notification")} · {spec.label.toLowerCase()}</span>
            <span>
              {emailed.length
                ? formatCount(wouldEmail.length) + " of these would also have reached " + user.email + " — "
                : "None of these reach your inbox — "}
              <button type="button" className="cd-record__link" onClick={() => onNavigate("/settings/alerts")}>choose which kinds are emailed</button>
            </span>
          </div>
        </section>
      </div>
    );
  }

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