/* Offers, and compliance. Two screens over the same applications array, both
   Instant: every control here confirms itself, consequential ones raise an undo
   toast, and nothing on either screen is destructive.

   Offers exists because an offer is the only record in the desk with a hard
   deadline nobody on the desk controls. Compliance exists because a start date
   is the thing that actually slips, and it slips on three checks. */
(() => {
  const {
    Card, CardHeader, CardTitle, CardDescription, CardPanel, CardFooter,
    Table, TableHeader, TableBody, TableRow, TableHead, TableCell,
    Button, Badge, Avatar, Alert, AlertTitle, AlertDescription, Separator, MenuItem, Progress,
  } = window.OriginDesignSystem_7c998b;

  /* ── /offers ───────────────────────────────────────────────────────────── */
  const OFFER_VIEWS = [
    { value: "waiting", label: "With the candidate", predicate: (rows) => rows.filter((r) => !r.answered) },
    { value: "answered", label: "Answered", predicate: (rows) => rows.filter((r) => r.answered) },
    { value: "all", label: "Everything", predicate: (rows) => rows },
  ];

  function OffersScreen({ data, now, session, onNavigate, onApplicationTransition, onChaseOffer, onExtendOffer }) {
    const [view, setView] = React.useState("waiting");
    const all = offersOut(data.applications).map((a) => offerRow(a, data.requisitions, now));
    const waiting = all.filter((r) => !r.answered);
    const expiring = offersExpiringSoon(data.applications, now);
    const outcome = offerOutcome(data.applications);
    const views = OFFER_VIEWS.map((v) => ({ value: v.value, label: v.label, count: v.predicate(all).length }));
    const rows = OFFER_VIEWS.find((v) => v.value === view).predicate(all);

    return (
      <div className="rd-page">
        <PageHead path="/offers" title="Offers"
          note={plural(waiting.length, "offer", "offers") + " out with candidates and "
            + plural(all.length - waiting.length, "answered", "answered") + ". Every one of them has a date on it that we do not control, which is why they live on their own screen."} />

        {expiring.length ? (
          <Alert variant="warning">
            <Icon name="clock-alert" size={16} />
            <AlertTitle>{plural(expiring.length, "offer", "offers")} inside {RD_POLICY.offerExpiryWarnDays} days of running out</AlertTitle>
            <AlertDescription>
              {expiring.map((a) => a.candidate.name + " — " + durationWords(daysBetween(now, a.offer.expiresAt))).join(" · ")}.
              A call is worth more than an email at this point; extending is the desk's decision, not the candidate's.
            </AlertDescription>
          </Alert>
        ) : null}

        <div className="rd-metrics">
          <StatTile label="Out with candidates" value={waiting.length}
            qualifier={waiting.length ? "Soonest runs out " + formatDay(waiting[0].offer.expiresAt) : "Nothing waiting on an answer"} />
          <StatTile label="Accepted" value={outcome.accepted.length + " of " + outcome.sent.length}
            qualifier={outcome.sent.length ? percent(outcome.rate) + " of every offer this desk has sent" : "No offer has gone out yet"} />
          <StatTile label="Committed salary" value={money(sumBy(all.filter((r) => r.answered), (r) => r.offer.salaryMinor))}
            qualifier={"Annual, over the " + plural(all.filter((r) => r.answered).length, "accepted offer", "accepted offers") + " — offers still out are not counted"} />
          <StatTile label="Starting inside 30 days" value={all.filter((r) => r.answered && r.daysToStart <= 30).length}
            qualifier="Accepted offers with a start date in the next month" />
        </div>

        <Card>
          <div className="rd-card-tabs"><ViewTabs views={views} value={view} onSelect={setView} /></div>
          {rows.length === 0 ? (
            <NoResults title="No offer in this view"
              description={view === "waiting" ? "Nothing is waiting on a candidate right now." : "Nothing has been answered yet."}
              action={<Button onClick={() => setView("all")}>Show everything</Button>} />
          ) : (
            <div className="rd-card-table">
              <Table variant="card">
                <TableHeader>
                  <TableRow>
                    <TableHead>Candidate</TableHead>
                    <TableHead className="rd-drop-md">Seat</TableHead>
                    <TableHead className="rd-num">Salary</TableHead>
                    <TableHead className="rd-drop-lg" style={{ minWidth: "9rem" }}>In the band</TableHead>
                    <TableHead>Runs out</TableHead>
                    <TableHead className="rd-drop-md">Starts</TableHead>
                    <TableHead className="rd-actions-head">Action</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {rows.map((row) => (
                    <TableRow key={row.application.id} className={row.answered ? "rd-row--recessed" : undefined}>
                      <TableCell>
                        <CandidateCell application={row.application} onNavigate={onNavigate}
                          meta={row.metExpectation ? row.application.candidate.headline : "Asked for " + money(row.application.salaryExpectationMinor)} />
                      </TableCell>
                      <TableCell className="rd-drop-md">
                        <button type="button" className="rd-link" onClick={() => onNavigate("/requisitions/" + row.requisition.id)}>{row.requisition.title}</button>
                        <span className="rd-sub">{row.requisition.ref}</span>
                      </TableCell>
                      <TableCell className="rd-num">{money(row.offer.salaryMinor)}</TableCell>
                      <TableCell className="rd-drop-lg">
                        <Bar ratio={row.position} />
                        <span className="rd-sub">{percent(row.position)} up {bandLabel(row.requisition)}</span>
                      </TableCell>
                      <TableCell>
                        {row.answered
                          ? <span className="rd-status"><Badge size="sm" variant="success">Accepted</Badge></span>
                          : (
                            <span className={"rd-clock" + (row.daysLeft <= RD_POLICY.offerExpiryWarnDays ? " rd-clock--warning" : "")} title={formatAbsolute(row.offer.expiresAt)}>
                              {durationWords(row.daysLeft)}
                              <span className="rd-sub">{formatDay(row.offer.expiresAt)}</span>
                            </span>
                          )}
                      </TableCell>
                      <TableCell className="rd-drop-md">
                        {formatDayShort(row.offer.startAt)}
                        <span className="rd-sub">{durationWords(row.daysToStart)}</span>
                      </TableCell>
                      <TableCell className="rd-actions">
                        <RowActions transitions={transitionsFor(row.application)} onRun={(t) => onApplicationTransition(row.application, t)}
                          label={"Actions for " + row.application.candidate.name}
                          extra={row.answered ? null : (close) => (
                            <>
                              <MenuItem onClick={() => { close(); onChaseOffer(row.application); }}>Chase the candidate</MenuItem>
                              <MenuItem onClick={() => { close(); onExtendOffer(row.application); }}>Extend the offer</MenuItem>
                            </>
                          )} />
                      </TableCell>
                    </TableRow>
                  ))}
                </TableBody>
              </Table>
            </div>
          )}
          {rows.length ? (
            <CardFooter className="rd-card-foot">
              <span className="rd-foot">
                {plural(rows.length, "offer", "offers")}, soonest to run out first. Committed salary counts accepted offers only, so this table and the tile above it agree.
              </span>
            </CardFooter>
          ) : null}
        </Card>
      </div>
    );
  }

  /* ── /compliance ───────────────────────────────────────────────────────── */
  function ComplianceScreen({ data, now, session, onNavigate, onVerifyRightToWork, onSubmitDbs, onChaseRegistration }) {
    const [only, setOnly] = React.useState("blockers");
    const rows = complianceRows(data.applications, data.requisitions, now);
    const urgent = rows.filter((r) => r.urgent);
    const clear = rows.filter((r) => r.clear);
    const shown = only === "blockers" ? rows.filter((r) => r.blockers.length) : only === "urgent" ? urgent : rows;
    const views = [
      { value: "blockers", label: "Anything outstanding", count: rows.filter((r) => r.blockers.length).length },
      { value: "urgent", label: "Close to starting", count: urgent.length },
      { value: "all", label: "Every live application", count: rows.length },
    ];

    return (
      <div className="rd-page">
        <PageHead path="/compliance" title="Compliance"
          note={"Right to work, DBS and professional registration across the " + plural(rows.length, "live application", "live applications")
            + ". Nobody starts without all three, so this is the screen a start date actually depends on."} />

        {urgent.length ? (
          <Alert variant="warning">
            <Icon name="shield-alert" size={16} />
            <AlertTitle>{plural(urgent.length, "person", "people")} at checks or beyond with something outstanding</AlertTitle>
            <AlertDescription>
              {urgent.map((row) => row.application.candidate.name + " — " + row.blockers.join(", ")).join(" · ")}.
              Urgency is the stage, not the count: the same gap at applied stops nothing yet.
            </AlertDescription>
          </Alert>
        ) : null}

        <div className="rd-metrics">
          <StatTile label="Nothing outstanding" value={clear.length + " of " + rows.length}
            qualifier="Right to work verified, DBS clear, and the seat's register in date where it asks for one" />
          <StatTile label="Right to work outstanding" value={rows.filter((r) => COMPLIANCE_FLAGS.rtwOutstanding(r.application)).length}
            qualifier={plural(rows.filter((r) => COMPLIANCE_FLAGS.needsSponsorship(r.application)).length, "of them needs", "of them need") + " sponsorship"} />
          <StatTile label="DBS not clear" value={rows.filter((r) => COMPLIANCE_FLAGS.dbsOutstanding(r.application)).length}
            qualifier={rows.filter((r) => r.application.dbs === "submitted").length
              ? rows.filter((r) => r.application.dbs === "submitted").length + " with the service, the rest not started"
              : "None with the service yet — the rest are not started"} />
          <StatTile label="Registration to chase" value={rows.filter((r) => COMPLIANCE_FLAGS.registrationOutstanding(r.application, r.requisition, now)).length}
            qualifier={"Renewing inside " + RD_POLICY.registrationWarnDays + " days, already lapsed, or none on file where the seat asks for one"} />
        </div>

        <Card>
          <div className="rd-card-tabs"><ViewTabs views={views} value={only} onSelect={setOnly} /></div>
          {shown.length === 0 ? (
            <NoResults title="Nothing outstanding" description="Every live application has its right to work verified, a clear DBS, and the register its seat asks for in date."
              action={<Button onClick={() => setOnly("all")}>Show every live application</Button>} />
          ) : (
            <div className="rd-card-table">
              <Table variant="card">
                <TableHeader>
                  <TableRow>
                    <TableHead>Candidate</TableHead>
                    <TableHead className="rd-drop-md">Stage</TableHead>
                    <TableHead>Right to work</TableHead>
                    <TableHead>DBS</TableHead>
                    <TableHead>Registration</TableHead>
                    <TableHead className="rd-actions-head">Action</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {shown.map((row) => {
                    const a = row.application;
                    const expiring = COMPLIANCE_FLAGS.registrationExpiring(a, now);
                    const expired = COMPLIANCE_FLAGS.registrationExpired(a, now);
                    return (
                      <TableRow key={a.id} className={row.clear ? "rd-row--recessed" : undefined}>
                        <TableCell>
                          <CandidateCell application={a} onNavigate={onNavigate}
                            meta={requisitionById(data.requisitions, a.requisitionId).title} />
                        </TableCell>
                        <TableCell className="rd-drop-md">
                          <span className="rd-status">
                            <StatusBadge values={APPLICATION_STAGE} value={a.stage} />
                            {row.urgent ? <Badge size="sm" variant="warning">Blocks a start date</Badge> : null}
                          </span>
                        </TableCell>
                        <TableCell><StatusBadge values={RIGHT_TO_WORK} value={a.rightToWork} /></TableCell>
                        <TableCell>
                          <StatusBadge values={DBS_STATUS} value={a.dbs} />
                          {a.dbsAt ? <span className="rd-sub">{formatDayShort(a.dbsAt)}</span> : null}
                        </TableCell>
                        <TableCell>
                          {a.registrationExpiresAt ? (
                            <>
                              <span className={"rd-clock" + (expired ? " rd-clock--danger" : expiring ? " rd-clock--warning" : "")} title={formatAbsolute(a.registrationExpiresAt)}>
                                {a.registration}
                              </span>
                              <span className="rd-sub">{expired ? "lapsed " + formatDayShort(a.registrationExpiresAt) : "renews " + formatDayShort(a.registrationExpiresAt) + " · " + durationWords(row.registrationDays)}</span>
                            </>
                          ) : row.registerNeeded
                            ? <span className="rd-clock rd-clock--warning">No {row.registerNeeded} number<span className="rd-sub">This seat asks for one</span></span>
                            : <span className="rd-muted">Not required<span className="rd-sub">This seat asks for no register</span></span>}
                        </TableCell>
                        <TableCell className="rd-actions">
                          <span className="rd-actions__row">
                            {COMPLIANCE_FLAGS.rtwOutstanding(a)
                              ? <Button size="xs" onClick={() => onVerifyRightToWork(a)}>Verify right to work</Button>
                              : COMPLIANCE_FLAGS.dbsOutstanding(a) && a.dbs === "not_started"
                                ? <Button size="xs" variant="outline" onClick={() => onSubmitDbs(a)}>Send to DBS</Button>
                                : expiring || expired
                                  ? <Button size="xs" variant="outline" onClick={() => onChaseRegistration(a)}>Ask for the renewal</Button>
                                  : <span className="rd-muted">—</span>}
                          </span>
                        </TableCell>
                      </TableRow>
                    );
                  })}
                </TableBody>
              </Table>
            </div>
          )}
          <CardFooter className="rd-card-foot">
            <span className="rd-foot">
              {only === "all" ? "Every live application, worst first. Rows with nothing outstanding are recessed." : plural(shown.length, "application", "applications") + " of the " + rows.length + " live ones."}
              {" "}Settled applications are not here: nothing is checked on somebody who is not being hired.
            </span>
            <ExportMenu scope={plural(shown.length, "row", "rows") + " as filtered"} onExport={() => {}} />
          </CardFooter>
        </Card>
      </div>
    );
  }

  Object.assign(window, { OffersScreen, ComplianceScreen });
})();
