/* The notifications inbox — the same array the bell's count reads, laid out
   properly. Instant commit model: reading, unreading and marking the lot apply
   immediately; marking all read raises an undo toast because it is the one that
   throws information away.
   Unread is the absence of `readAt`, so the count on the bell and the count on
   the tab cannot disagree. */
(() => {
  const {
    Card, CardHeader, CardTitle, CardDescription, CardPanel, CardFooter,
    Button, Badge, Avatar, Alert, AlertTitle, AlertDescription, Separator, MenuItem,
  } = window.OriginDesignSystem_7c998b;

  function NotificationsScreen({ data, now, session, onNavigate, onReadNotification, onUnreadNotification, onReadAll }) {
    const [view, setView] = React.useState("unread");
    const all = data.notifications;
    const unread = unreadNotifications(all);
    const views = [
      { value: "unread", label: "Unread", count: unread.length },
      { value: "mentions", label: "Mentions", count: notificationsOfKind(all, "mention").length },
      { value: "all", label: "Everything", count: all.length },
    ];
    const rows = view === "unread" ? unread : view === "mentions" ? notificationsOfKind(all, "mention") : all;
    const days = notificationDays(rows, now);

    return (
      <div className="rd-page">
        <PageHead path="/notifications" title="Notifications"
          note={unread.length
            ? plural(unread.length, "unread notification", "unread notifications") + " of " + all.length + ". Everything here points at a record — nothing is a summary of something you cannot open."
            : "Nothing unread. All " + all.length + " are kept so you can find what happened last week."}
          actions={<Button variant="outline" size="sm" disabled={!unread.length} onClick={onReadAll}>Mark all read</Button>} />

        {/* One tile per kind that has something in it — the enum read whole and
           filtered, never its first four. */}
        <div className="rd-metrics">
          {NOTIFICATION_KINDS.map((kind) => ({ kind, ofKind: notificationsOfKind(all, kind.value) }))
            .filter((row) => row.ofKind.length > 0)
            .map(({ kind, ofKind }) => {
            const unreadOfKind = ofKind.filter((n) => !n.readAt).length;
            return (
              <StatTile key={kind.value} label={kind.label} value={ofKind.length}
                qualifier={unreadOfKind ? plural(unreadOfKind, "unread", "unread") : "All read"} />
            );
          })}
        </div>

        <Card>
          <div className="rd-card-tabs"><ViewTabs views={views} value={view} onSelect={setView} /></div>
          <CardPanel>
            {days.length ? (
              <div className="rd-stack">
                {days.map((day) => (
                  <div className="rd-day" key={day.key}>
                    <div className="rd-day__head">
                      <span className="rd-day__label">{dayLabel(day.at, now)}</span>
                      <span className="rd-day__count">{plural(day.items.length, "notification", "notifications")}</span>
                    </div>
                    {day.items.map((notification) => {
                      const kind = notificationKind(notification);
                      const actor = notification.actorId ? staffById(data.staff, notification.actorId) : null;
                      return (
                        <div className={"rd-notif" + (notification.readAt ? " rd-notif--read" : "")} key={notification.id}>
                          <span className="rd-notif__mark" aria-hidden="true">
                            {actor
                              ? <Avatar size={32} src={actor.photo} alt="" fallback={actor.initials} />
                              : <span className="rd-notif__icon"><Icon name={kind.icon} size={15} /></span>}
                          </span>
                          <span className="rd-notif__body">
                            <span className="rd-notif__head">
                              <button type="button" className="rd-link rd-notif__title"
                                onClick={() => { onReadNotification(notification); onNavigate(notification.route); }}>{notification.title}</button>
                              {notification.readAt ? null : <span className="rd-notif__dot" aria-label="Unread" />}
                            </span>
                            <span className="rd-notif__text">{notification.body}</span>
                            <span className="rd-notif__meta">
                              {kind.label}
                              {actor ? " · " + actor.name : ""}
                              {" · "}
                              <span title={formatAbsolute(notification.at)}>{formatWhen(notification.at, now)}</span>
                              {notification.readAt ? " · read " + formatWhen(notification.readAt, now) : ""}
                            </span>
                          </span>
                          <span className="rd-notif__side">
                            <Button variant="ghost" size="xs"
                              onClick={() => (notification.readAt ? onUnreadNotification(notification) : onReadNotification(notification))}>
                              {notification.readAt ? "Mark unread" : "Mark read"}
                            </Button>
                          </span>
                        </div>
                      );
                    })}
                  </div>
                ))}
              </div>
            ) : (
              <p className="rd-foot">
                {view === "unread" ? "Nothing unread. " : view === "mentions" ? "Nobody has mentioned you. " : ""}
                {view === "unread" ? <button type="button" className="rd-link" onClick={() => setView("all")}>Show all {all.length}</button> : "Everything you are sent lands here."}
              </p>
            )}
          </CardPanel>
          <CardFooter className="rd-card-foot">
            <span className="rd-foot">
              What you are notified about is set on <button type="button" className="rd-link" onClick={() => onNavigate("/me/profile")}>your profile</button>.
              The desk's own defaults are in Settings.
            </span>
            <span className="rd-foot">{plural(rows.length, "notification", "notifications")} in this view.</span>
          </CardFooter>
        </Card>
      </div>
    );
  }

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