/* Interviews — the destination that is not a table. The question is "what is
   happening, and when", so the days are the display and the conversations sit
   in them. Instant commit model; feedback is a staged dialog.
   The tabs narrow the list only; the figures above them do not move. */
(() => {
  const {
    Card, CardHeader, CardTitle, CardDescription, CardPanel, CardFooter,
    Button, Badge, Avatar, Alert, AlertTitle, AlertDescription, Separator,
  } = window.OriginDesignSystem_7c998b;

  const KIND_LABEL = { screening: "Screening call", assessment: "Assessment", panel: "Panel interview" };

  const VIEWS = [
    { value: "ahead", label: "Booked", predicate: (rows, now) => rows.filter((iv) => INTERVIEW_FLAGS.isAhead(iv, now)) },
    { value: "feedback", label: "Awaiting feedback", predicate: (rows) => rows.filter(INTERVIEW_FLAGS.feedbackOutstanding) },
    { value: "held", label: "Held", predicate: (rows) => rows.filter((iv) => iv.status === "complete" || iv.status === "no_show") },
  ];

  function Slot({ interview, data, now, onNavigate, onInterviewTransition }) {
    const application = applicationById(data.applications, interview.applicationId);
    const requisition = requisitionById(data.requisitions, application.requisitionId);
    const panel = panelOf(data.staff, interview);
    const recessed = interview.status === "complete" || interview.status === "cancelled";
    return (
      <div className="rd-slot">
        <span className="rd-slot__time">
          {formatTime(interview.at)}
          <span className="rd-sub">{interview.minutes} min</span>
        </span>
        <span className="rd-slot__body">
          <CandidateCell application={application} onNavigate={onNavigate} meta={KIND_LABEL[interview.kind] + " · " + requisition.title} />
          <span className="rd-foot">{interview.where} · {panel.map((p) => p.name).join(", ")}</span>
          {interview.note ? <p className="rd-quote">{interview.note}</p> : null}
        </span>
        <span className="rd-slot__side">
          <span className="rd-faces" aria-hidden="true">
            {panel.map((person) => <Avatar key={person.id} size={24} src={person.photo} alt="" fallback={person.initials} />)}
          </span>
          <StatusBadge values={INTERVIEW_STATUS} value={interview.status} />
          {recessed ? null : <RowActions transitions={interviewTransitions(interview)} onRun={(t) => onInterviewTransition(interview, t)} label={"Actions for the " + interview.kind + " with " + application.candidate.name} />}
        </span>
      </div>
    );
  }

  function InterviewsScreen({ data, now, session, onNavigate, onInterviewTransition, onBookInterview }) {
    const [view, setView] = React.useState("ahead");
    const me = staffById(data.staff, session.personId);
    const outstanding = feedbackOutstanding(data.interviews);
    const today = interviewsToday(data.interviews, now);
    const ahead = interviewsAhead(data.interviews, now);
    const views = VIEWS.map((v) => ({ value: v.value, label: v.label, count: v.predicate(data.interviews, now).length }));
    const rows = VIEWS.find((v) => v.value === view).predicate(data.interviews, now);
    const days = interviewDays(rows, now);

    return (
      <div className="rd-page">
        <PageHead path="/interviews" title="Interviews"
          note={plural(today.length, "conversation", "conversations") + " today, " + plural(ahead.length, "booked", "booked") + " in all. " + (outstanding.length ? plural(outstanding.length, "panel", "panels") + " owe us a scorecard." : "Every panel has reported.")}
          actions={<Button size="sm" onClick={onBookInterview}><Icon name="calendar-plus" size={14} />Book an interview</Button>} />

        {outstanding.length ? (
          <Alert variant="warning">
            <Icon name="clipboard-pen" size={16} />
            <AlertTitle>{plural(outstanding.length, "scorecard", "scorecards")} outstanding</AlertTitle>
            <AlertDescription>
              {outstanding.map((iv) => applicationById(data.applications, iv.applicationId).candidate.name + " (" + formatDayShort(iv.at) + ")").join(" · ")}.
              A panel decision needs {RD_POLICY.panelScorecards} cards from different people, so nothing after the panel can move until they are in.
            </AlertDescription>
          </Alert>
        ) : null}

        <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)}{dayLabel(day.at, now).indexOf("day") === -1 ? "" : " · " + formatDay(day.at)}</span>
                      <span className="rd-day__count">{plural(day.items.length, "conversation", "conversations")}</span>
                    </div>
                    {day.items.map((interview) => (
                      <Slot key={interview.id} interview={interview} data={data} now={now} onNavigate={onNavigate} onInterviewTransition={onInterviewTransition} />
                    ))}
                  </div>
                ))}
              </div>
            ) : (
              <p className="rd-foot">Nothing in this view. {view === "feedback" ? "Every panel has filed its scorecard." : "Book one from an application at screening, assessment or panel."}</p>
            )}
          </CardPanel>
          <CardFooter className="rd-card-foot">
            <span className="rd-foot">
              {view === "ahead" ? "Booked conversations from " + formatDay(now) + " onwards, earliest first." : view === "feedback" ? "Held, waiting on a scorecard." : "Everything that has already happened, including the one no-show."}
            </span>
            <span className="rd-foot">{plural(rows.length, "conversation", "conversations")} across {plural(days.length, "day", "days")}.</span>
          </CardFooter>
        </Card>
      </div>
    );
  }

  /* ── Talent pool: faces first, because the question is "who do we know". ── */
  function PoolScreen({ data, now, session, onNavigate, onApplicationTransition }) {
    const [site, setSite] = React.useState("all");
    const [query, setQuery] = React.useState("");
    const pool = talentPool(data.applications);
    const dirty = !!query || site !== "all";
    const clear = () => { setQuery(""); setSite("all"); };
    const rows = pool.filter((application) => {
      const requisition = requisitionById(data.requisitions, application.requisitionId);
      if (site !== "all" && requisition.site !== site) return false;
      if (!query) return true;
      return (application.candidate.name + " " + application.candidate.headline).toLowerCase().indexOf(query.trim().toLowerCase()) > -1;
    });

    return (
      <div className="rd-page">
        <PageHead path="/pool" title="Talent pool"
          note={"The " + pool.length + " people we declined or who withdrew and said we would talk again. It is a predicate over the applications, not a separate list — reopening somebody here moves their own record."} />

        <FilterBar query={query} onQuery={setQuery} placeholder="Search a name or a headline…" dirty={dirty} onClear={clear}
          selects={[{ id: "site", label: "Site", value: site, onChange: setSite,
            items: [{ value: "all", label: "Every site" }].concat(SITES.map((s) => ({ value: s.value, label: s.label }))) }]} />

        {rows.length ? (
          <div className="rd-grid">
            {rows.map((application) => {
              const requisition = requisitionById(data.requisitions, application.requisitionId);
              const reached = statusValue(APPLICATION_STAGE, application.lastLiveStage || "applied");
              return (
                <Card key={application.id}>
                  <div className="rd-poolcard">
                    <div className="rd-poolcard__head">
                      <Avatar size={48} src={application.candidate.photo} alt="" fallback={application.candidate.initials} />
                      <span className="rd-record">
                        <button type="button" className="rd-link rd-record__name" onClick={() => onNavigate("/applications/" + application.id)}>{application.candidate.name}</button>
                        <span className="rd-record__meta">{application.candidate.headline}</span>
                      </span>
                    </div>
                    <span className="rd-status">
                      <StatusBadge values={APPLICATION_STAGE} value={application.stage} />
                      <Badge size="sm" variant="secondary">Reached {reached.label.toLowerCase()}</Badge>
                    </span>
                    <p className="rd-quote">{application.declineNote || application.withdrawNote}</p>
                    <div className="rd-poolcard__foot">
                      <span className="rd-foot">
                        {requisition.title} · {application.stage === "declined" ? "declined " : "withdrew "}{formatDayShort(application.decidedAt)} · {labelOf(SITES, requisition.site)}
                      </span>
                      <Transitions transitions={transitionsFor(application)} onRun={(t) => onApplicationTransition(application, t)} />
                    </div>
                  </div>
                </Card>
              );
            })}
          </div>
        ) : (
          <Card><NoResults title="Nobody in the pool matches that" description={"Clearing the filters brings back " + plural(pool.length, "person", "people") + "."} onClear={clear} /></Card>
        )}
      </div>
    );
  }

  Object.assign(window, { InterviewsScreen, PoolScreen });
})();
