/* Insights — the desk read sideways. Chart-led, not a table: the funnel is the
   display, and every figure on the screen derives from the same scoped array.
   The scope control sits ABOVE the figures and moves them (AGENTS §5.3); there
   is no list on this screen to narrow separately. */
(() => {
  const {
    Card, CardHeader, CardTitle, CardDescription, CardPanel, CardFooter,
    Table, TableHeader, TableBody, TableRow, TableHead, TableCell,
    Button, Badge, Separator, Alert, AlertTitle, AlertDescription,
  } = window.OriginDesignSystem_7c998b;

  function InsightsScreen({ data, now, onNavigate }) {
    const [requisition, setRequisition] = React.useState("all");
    const scoped = requisition === "all" ? data.applications : applicationsFor(data.applications, requisition);
    const chosen = requisition === "all" ? null : requisitionById(data.requisitions, requisition);
    const shape = funnel(scoped);
    const offers = offerOutcome(scoped);
    const speed = timeToOffer(scoped);
    const sources = sourceMix(scoped);
    const oldest = scoped.length ? Math.min.apply(null, scoped.map((a) => a.appliedAt)) : now;

    return (
      <div className="rd-page">
        <PageHead path="/insights" title="Insights"
          note={"Every figure here counts the same " + plural(scoped.length, "application", "applications") + " — live and settled, applied since " + formatDay(oldest) + "."} />

        <ScopeBar
          controls={[{ id: "req", label: "Requisition", value: requisition, onChange: setRequisition,
            items: [{ value: "all", label: "Every requisition" }].concat(data.requisitions.map((r) => ({ value: r.id, label: r.ref + " · " + r.title }))) }]}
          dirty={requisition !== "all"} onClear={() => setRequisition("all")}
          note={chosen
            ? "Scoped to " + chosen.ref + " · " + chosen.title + " — " + plural(scoped.length, "application", "applications") + " ever raised against it, " + plural(liveApplications(scoped).length, "still live", "still live") + "."
            : "Nothing is filtered out: all " + data.applications.length + " applications on the desk, across " + plural(data.requisitions.length, "requisition", "requisitions") + "."} />

        <div className="rd-metrics">
          <StatTile label="Applications" value={scoped.length}
            qualifier={liveApplications(scoped).length + " live, " + (scoped.length - liveApplications(scoped).length) + " settled"}
            onDrill={() => onNavigate("/applications")} drillLabel="Show the applications" />
          <StatTile label="Offers accepted" value={offers.accepted.length + " of " + offers.sent.length}
            qualifier={offers.sent.length ? percent(offers.rate) + " of the offers we sent" : "No offer has gone out yet"} />
          <StatTile label="Days to offer, median" value={speed.median === null ? "—" : speed.median}
            qualifier={speed.count ? "Over the " + plural(speed.count, "application", "applications") + " that reached an offer — fastest " + speed.fastest + ", slowest " + speed.slowest : "Nothing has reached an offer"} />
          <StatTile label="Waiting on the desk" value={awaitingUs(scoped).length}
            qualifier={"Of " + plural(liveApplications(scoped).length, "live application", "live applications") + " — the rest sit with referees or candidates"}
            onDrill={() => onNavigate("/applications")} drillLabel="Show what is waiting on the desk" />
        </div>

        <div className="rd-columns">
          <div className="rd-col">
            <Card>
              <CardHeader>
                <CardTitle>The funnel</CardTitle>
                <CardDescription>How many applications reached each step, including the ones that later stopped. A step counts everybody who got that far, so the numbers only fall.</CardDescription>
              </CardHeader>
              <CardPanel>
                <div className="rd-stack">
                  {shape.rows.map((row) => (
                    <span className="rd-part" key={row.stage}>
                      <span className="rd-spread">
                        <span className="rd-record__name">{row.label}</span>
                        <span className="rd-kv__value">{row.count}{row.fromPrevious === null ? "" : " · " + percent(row.fromPrevious) + " of the step before"}</span>
                      </span>
                      <Bar ratio={shape.total ? row.count / shape.total : 0} tone={row.stage === "hired" ? null : "soft"} />
                    </span>
                  ))}
                </div>
              </CardPanel>
              <CardFooter className="rd-card-foot">
                <span className="rd-foot">
                  {shape.rows[0].count} applied · {shape.rows[shape.rows.length - 1].count} hired.
                  The biggest drop is between {biggestDrop(shape).from} and {biggestDrop(shape).to}, where {biggestDrop(shape).lost} stopped.
                </span>
              </CardFooter>
            </Card>
          </div>

          <div className="rd-col">
            <Card>
              <CardHeader>
                <CardTitle>Where they come from</CardTitle>
                <CardDescription>{plural(sources.length, "source", "sources")} with at least one application in scope.</CardDescription>
              </CardHeader>
              <CardPanel>
                <div className="rd-card-table">
                  <Table variant="card">
                    <TableHeader>
                      <TableRow>
                        <TableHead>Source</TableHead>
                        <TableHead className="rd-num">Applications</TableHead>
                        <TableHead className="rd-num">Share</TableHead>
                        <TableHead className="rd-num">Reached an offer</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {sources.map((row) => (
                        <TableRow key={row.source.value}>
                          <TableCell>{row.source.label}</TableCell>
                          <TableCell className="rd-num">{row.count}</TableCell>
                          <TableCell className="rd-num">{percent(row.share)}</TableCell>
                          <TableCell className="rd-num">{row.offered}</TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </div>
              </CardPanel>
              <CardFooter className="rd-card-foot">
                <span className="rd-foot">Shares are of the {scoped.length} applications in scope, so they add to 100%.</span>
              </CardFooter>
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>Offers, one by one</CardTitle>
                <CardDescription>{plural(offers.sent.length, "offer", "offers")} sent in scope. Small numbers, so they are listed rather than averaged.</CardDescription>
              </CardHeader>
              <CardPanel>
                <div className="rd-list">
                  {offers.sent.map((application) => (
                    <div className="rd-list__row" key={application.id}>
                      <div className="rd-list__main">
                        <CandidateCell application={application} onNavigate={onNavigate} meta={requisitionById(data.requisitions, application.requisitionId).title} />
                      </div>
                      <div className="rd-list__side">
                        <span className="rd-kv__value">{money(application.offer.salaryMinor)}</span>
                        <span className="rd-foot">
                          {application.offer.acceptedAt ? "Accepted " + formatDayShort(application.offer.acceptedAt) : "Out since " + formatDayShort(application.offer.sentAt)}
                          {" · " + plural(daysBetween(application.appliedAt, application.offer.sentAt), "day", "days") + " from applying"}
                        </span>
                      </div>
                    </div>
                  ))}
                </div>
              </CardPanel>
            </Card>
          </div>
        </div>
      </div>
    );
  }

  /* The one derived claim the footer makes, computed rather than asserted. */
  function biggestDrop(shape) {
    let worst = { from: shape.rows[0].label, to: shape.rows[1] ? shape.rows[1].label : shape.rows[0].label, lost: 0 };
    for (let i = 1; i < shape.rows.length; i++) {
      const lost = shape.rows[i - 1].count - shape.rows[i].count;
      if (lost > worst.lost) worst = { from: shape.rows[i - 1].label.toLowerCase(), to: shape.rows[i].label.toLowerCase(), lost };
    }
    return worst;
  }

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