/* Your desk — the day's work, over the same arrays every other screen reads.
   Instant commit model: everything here applies immediately, consequential
   moves raise an undo toast, and the two destructive ones open a dialog.
   Every figure names its array; the four anchor figures drill through to the
   rows they count. */
(() => {
  const { Card, CardHeader, CardTitle, CardDescription, CardPanel, CardFooter, Button, Badge, Alert, AlertTitle, AlertDescription, Avatar } = window.OriginDesignSystem_7c998b;

  function QueueRow({ application, data, now, onNavigate, onRun }) {
    const requisition = requisitionById(data.requisitions, application.requisitionId);
    const over = stageOverBy(application, now);
    return (
      <div className="rd-list__row">
        <div className="rd-list__main">
          <CandidateCell application={application} onNavigate={onNavigate} meta={requisition.title + " · " + labelOf(SITES, requisition.site)} />
          <Stepper application={application} data={data} now={now} mini />
        </div>
        <div className="rd-list__side">
          <span className="rd-status">
            <StatusBadge values={APPLICATION_STAGE} value={application.stage} />
            {APPLICATION_FLAGS.isUnread(application) ? <Badge size="sm" variant="secondary">Unread</Badge> : null}
          </span>
          <span className={"rd-clock" + (over > 0 ? " rd-clock--danger" : over === 0 ? " rd-clock--warning" : "")} title={formatAbsolute(application.stageEnteredAt)}>
            {plural(daysInStage(application, now), "day", "days")} in {statusValue(APPLICATION_STAGE, application.stage).label.toLowerCase()}
            {over > 0 ? " · " + plural(over, "day", "days") + " over" : ""}
          </span>
          <RowActions transitions={transitionsFor(application)} onRun={(t) => onRun(application, t)} label={"Actions for " + application.candidate.name} />
        </div>
      </div>
    );
  }

  function DeskScreen({ data, now, session, onNavigate, onApplicationTransition, onInterviewTransition, onReact }) {
    const me = staffById(data.staff, session.personId);
    const live = liveApplications(data.applications);
    const queue = awaitingUs(data.applications);
    const mine = queue.filter((a) => a.ownerId === me.id).sort((a, b) => stageOverBy(b, now) - stageOverBy(a, now));
    const others = queue.filter((a) => a.ownerId !== me.id);
    const unread = unreadApplications(data.applications);
    const stalled = stalledApplications(data.applications, now);
    const outstanding = feedbackOutstanding(data.interviews);
    const today = interviewsToday(data.interviews, now);
    const offers = live.filter((a) => a.stage === "offer");
    const checks = live.filter((a) => a.stage === "checks");
    const mentions = data.notes.filter((n) => mentionIds(n.body).indexOf(me.id) > -1).sort((a, b) => b.at - a.at).slice(0, 3);

    return (
      <div className="rd-page">
        <PageHead path="/" title={"Good morning, " + firstNameOf(me)}
          note={dayLabel(now, now) + ", " + formatDay(now) + " · " + plural(live.length, "live application", "live applications") + " across " + plural(data.requisitions.filter(REQUISITION_FLAGS.isOpen).length, "open requisition", "open requisitions") + "."}
          avatar={me}
          actions={<Button size="sm" onClick={() => onNavigate("/applications/new")}><Icon name="plus" size={14} />New application</Button>} />

        {/* The four figures the desk is run on. The first is the one the day is
            judged on, so it carries the primary plane; the rest are read after
            it. Each drills to the rows it counts or names its predicate. */}
        <div className="rd-metrics">
          {/* Inline, not a class: this is the one tile whose plane inverts, and
              the token pair is the whole rule. */}
          <Card className="rd-tile--primary" style={{ background: "var(--primary)", borderColor: "var(--primary)", color: "var(--primary-foreground)" }}>
            <div className="rd-tile">
              <span className="rd-tile__label" style={{ color: "color-mix(in srgb, var(--primary-foreground) 82%, transparent)" }}>Waiting on the desk</span>
              <button type="button" className="rd-tile__value rd-link" style={{ color: "var(--primary-foreground)", textDecorationColor: "color-mix(in srgb, var(--primary-foreground) 45%, transparent)" }}
                onClick={() => onNavigate("/applications")} aria-label="Show the applications waiting on the desk">{queue.length}</button>
              <span className="rd-tile__qual" style={{ color: "color-mix(in srgb, var(--primary-foreground) 82%, transparent)" }}>{mine.length} yours, {others.length} another recruiter's</span>
            </div>
          </Card>
          <StatTile label="Not read yet" value={unread.length}
            qualifier={unread.length ? "Oldest applied " + formatDayShort(Math.min.apply(null, unread.map((a) => a.appliedAt))) : "Everything has been opened"} />
          <StatTile label="Over their service level" value={stalled.length}
            qualifier="Counted per stage, not one figure for all of them" />
          <StatTile label="Scorecards outstanding" value={outstanding.length}
            qualifier={outstanding.length ? "From " + outstanding.map((iv) => formatDayShort(iv.at)).join(" and ") : "Every panel has reported"}
            onDrill={() => onNavigate("/interviews")} drillLabel="Show the interviews awaiting feedback" />
        </div>

        <div className="rd-columns">
          <div className="rd-col">
            <Card>
              <CardHeader>
                <CardTitle>Your queue</CardTitle>
                <CardDescription>The {Math.min(3, mine.length)} most urgent of the {mine.length} you own where the next move is ours, worst over its service level first.</CardDescription>
              </CardHeader>
              <CardPanel>
                {mine.length ? (
                  <div className="rd-list">
                    {mine.slice(0, 3).map((application) => (
                      <QueueRow key={application.id} application={application} data={data} now={now} onNavigate={onNavigate} onRun={onApplicationTransition} />
                    ))}
                  </div>
                ) : <p className="rd-foot">Nothing of yours is waiting on the desk. {others.length ? plural(others.length, "application", "applications") + " sit with another recruiter." : ""}</p>}
              </CardPanel>
              {mine.length > 3 ? (
                <CardFooter className="rd-card-foot">
                  <span className="rd-foot">{plural(mine.length - 3, "other", "others")} of yours are waiting on the desk, less urgent than these.</span>
                  <Button variant="outline" size="sm" onClick={() => onNavigate("/applications")}>Open the full queue</Button>
                </CardFooter>
              ) : null}
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>Today</CardTitle>
                <CardDescription>{today.length ? plural(today.length, "conversation", "conversations") + " booked for " + formatDay(now) + "." : "Nothing booked for today."}</CardDescription>
              </CardHeader>
              <CardPanel>
                {today.length ? today.map((interview) => {
                  const application = applicationById(data.applications, interview.applicationId);
                  const panel = panelOf(data.staff, interview);
                  return (
                    <div className="rd-slot" key={interview.id}>
                      <span className="rd-slot__time">{formatTime(interview.at)}</span>
                      <span className="rd-slot__body">
                        <CandidateCell application={application} onNavigate={onNavigate} meta={statusValue(APPLICATION_STAGE, interview.kind === "screening" ? "screening" : interview.kind === "panel" ? "panel" : "assessment").label + " · " + interview.where} />
                        <span className="rd-foot">{interview.minutes} minutes · {panel.map((p) => p.name).join(", ")}</span>
                      </span>
                      <span className="rd-slot__side">
                        <StatusBadge values={INTERVIEW_STATUS} value={interview.status} />
                        <RowActions transitions={interviewTransitions(interview)} onRun={(t) => onInterviewTransition(interview, t)} label={"Actions for the " + interview.kind + " with " + application.candidate.name} />
                      </span>
                    </div>
                  );
                }) : (() => {
                  const next = interviewsAhead(data.interviews, now)[0];
                  return <p className="rd-foot">{next ? "The next one is " + formatWeekday(next.at) + " at " + formatTime(next.at) + "." : "Nothing is booked at all — the queue is where the work is."}</p>;
                })()}
              </CardPanel>
            </Card>
          </div>

          <div className="rd-col">
            <Card>
              <CardHeader>
                <CardTitle>Offers with candidates</CardTitle>
                <CardDescription>{plural(offers.length, "offer", "offers")} out. Nothing here is ours to move.</CardDescription>
              </CardHeader>
              <CardPanel>
                <div className="rd-list">
                  {offers.map((application) => {
                    const left = daysBetween(now, application.offer.expiresAt);
                    return (
                      <div className="rd-list__row" key={application.id}>
                        <div className="rd-list__main">
                          <CandidateCell application={application} onNavigate={onNavigate} meta={money(application.offer.salaryMinor) + " · starts " + formatDayShort(application.offer.startAt)} />
                          {application.offer.acceptedAt
                            ? <span className="rd-foot">Accepted {formatWhen(application.offer.acceptedAt, now)} — record it to move to hired.</span>
                            : <span className="rd-foot">Sent {formatDayShort(application.offer.sentAt)}, valid to {formatDay(application.offer.expiresAt)}.</span>}
                        </div>
                        <div className="rd-list__side">
                          {application.offer.acceptedAt
                            ? <Badge size="sm" variant="success">Accepted</Badge>
                            : <span className={"rd-clock" + (left <= 3 ? " rd-clock--warning" : "")}>{durationWords(left)}</span>}
                          <Transitions transitions={transitionsFor(application).filter((t) => t.primary)} onRun={(t) => onApplicationTransition(application, t)} />
                        </div>
                      </div>
                    );
                  })}
                </div>
              </CardPanel>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>Checks outstanding</CardTitle>
                <CardDescription>{plural(checks.length, "application", "applications")} in checks. Referees and the DBS service owe these, not us.</CardDescription>
              </CardHeader>
              <CardPanel>
                <div className="rd-list">
                  {checks.map((application) => {
                    const missing = checksMissing(application);
                    return (
                      <div className={"rd-list__row" + (missing.length ? "" : " rd-row--recessed")} key={application.id}>
                        <div className="rd-list__main">
                          <CandidateCell application={application} onNavigate={onNavigate} meta={requisitionById(data.requisitions, application.requisitionId).title} />
                          <span className="rd-foot">{missing.length ? "Waiting on " + missing.join(" · ") : "Everything is in — the offer is ours to send."}</span>
                        </div>
                        <div className="rd-list__side">
                          <span className="rd-clock">{plural(daysInStage(application, now), "day", "days")} in checks</span>
                          <Transitions transitions={transitionsFor(application).filter((t) => t.primary)} onRun={(t) => onApplicationTransition(application, t)} />
                        </div>
                      </div>
                    );
                  })}
                </div>
              </CardPanel>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>You were mentioned</CardTitle>
                <CardDescription>The three most recent notes naming you.</CardDescription>
              </CardHeader>
              <CardPanel>
                <div className="rd-thread">
                  {mentions.map((note) => {
                    const application = applicationById(data.applications, note.applicationId);
                    return (
                      <div className="rd-part" key={note.id}>
                        <button type="button" className="rd-link rd-foot" onClick={() => onNavigate("/applications/" + application.id)}>{application.candidate.name} · {requisitionById(data.requisitions, application.requisitionId).title}</button>
                        <Note note={note} staff={data.staff} me={me} now={now} onReact={onReact} />
                      </div>
                    );
                  })}
                </div>
              </CardPanel>
            </Card>
          </div>
        </div>
      </div>
    );
  }

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