/* Requisitions — the seats, the board behind one of them, and the form that
   raises a new one. Instant on the list and the record; /requisitions/new is
   Staged. Every figure derives from applicationsFor(...) on the same array. */
(() => {
  const {
    Card, CardHeader, CardTitle, CardDescription, CardPanel, CardFooter,
    Table, TableHeader, TableBody, TableRow, TableHead, TableCell,
    Button, Badge, Avatar, Alert, AlertTitle, AlertDescription, Separator, Progress, MenuItem,
    Field, FieldLabel, FieldDescription, FieldError, Input, Textarea, Select, NumberField,
  } = window.OriginDesignSystem_7c998b;

  const ALL = "all";

  function RequisitionsScreen({ data, now, session, onNavigate, onRequisitionTransition, pushToast }) {
    const [query, setQuery] = React.useState("");
    const [status, setStatus] = React.useState(ALL);
    const [site, setSite] = React.useState(ALL);
    const dirty = !!query || status !== ALL || site !== ALL;
    const clear = () => { setQuery(""); setStatus(ALL); setSite(ALL); };

    const rows = data.requisitions.filter((requisition) => {
      if (status !== ALL && requisition.status !== status) return false;
      if (site !== ALL && requisition.site !== site) return false;
      if (!query) return true;
      return (requisition.title + " " + requisition.ref + " " + labelOf(DEPARTMENTS, requisition.department)).toLowerCase().indexOf(query.trim().toLowerCase()) > -1;
    }).sort((a, b) => a.openedAt - b.openedAt);
    const openRows = rows.filter(REQUISITION_FLAGS.isOpen);
    const seats = sumBy(openRows, (r) => requisitionHealth(data.applications, r, now).seatsLeft);

    return (
      <div className="rd-page">
        <PageHead path="/requisitions" title="Requisitions"
          note={plural(openRows.length, "requisition", "requisitions") + " open in this view, " + plural(seats, "seat", "seats") + " still unfilled."}
          actions={<Button size="sm" onClick={() => onNavigate("/requisitions/new")}><Icon name="plus" size={14} />New requisition</Button>} />

        <FilterBar query={query} onQuery={setQuery} placeholder="Search a title, a reference or a department…" dirty={dirty} onClear={clear}
          selects={[
            { id: "status", label: "Status", value: status, onChange: setStatus,
              items: [{ value: ALL, label: "Any status" }].concat(REQUISITION_STATUS.map((s) => ({ value: s.id, label: s.label }))) },
            { id: "site", label: "Site", value: site, onChange: setSite,
              items: [{ value: ALL, label: "Every site" }].concat(SITES.map((s) => ({ value: s.value, label: s.label }))) },
          ]} />

        <Card>
          {rows.length === 0 ? (
            <NoResults title="No requisition matches that" description={"Clearing the filters brings back " + plural(data.requisitions.length, "requisition", "requisitions") + "."} onClear={clear} />
          ) : (
            <div className="rd-card-table">
              <Table variant="card">
                <TableHeader>
                  <TableRow>
                    <TableHead>Requisition</TableHead>
                    <TableHead className="rd-drop-md">Manager</TableHead>
                    <TableHead>Status</TableHead>
                    <TableHead className="rd-num">Seats</TableHead>
                    <TableHead style={{ minWidth: "12rem" }}>Live pipeline</TableHead>
                    <TableHead className="rd-drop-lg">Open</TableHead>
                    <TableHead className="rd-drop-lg">Target start</TableHead>
                    <TableHead className="rd-actions-head">Action</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {rows.map((requisition) => {
                    const health = requisitionHealth(data.applications, requisition, now);
                    const manager = staffById(data.staff, requisition.hiringManagerId);
                    const settled = requisition.status === "closed" || requisition.status === "filled";
                    return (
                      <TableRow key={requisition.id} className={settled ? "rd-row--recessed" : undefined}>
                        <TableCell>
                          <button type="button" className="rd-link rd-record__name" onClick={() => onNavigate("/requisitions/" + requisition.id)}>{requisition.title}</button>
                          <span className="rd-sub">{requisition.ref} · {labelOf(SITES, requisition.site)} · {labelOf(EMPLOYMENT_TYPES, requisition.employmentType)}</span>
                        </TableCell>
                        <TableCell className="rd-drop-md"><StaffCell person={manager} meta={labelOf(DEPARTMENTS, requisition.department)} /></TableCell>
                        <TableCell>
                          <span className="rd-status">
                            <StatusBadge values={REQUISITION_STATUS} value={requisition.status} />
                            {health.thin ? <Badge size="sm" variant="warning">Thin</Badge> : null}
                          </span>
                        </TableCell>
                        <TableCell className="rd-num">{health.accepted} of {health.seats}</TableCell>
                        <TableCell><StageStrip applications={data.applications} requisitionId={requisition.id} /></TableCell>
                        <TableCell className="rd-drop-lg">
                          <span className={health.aging ? "rd-clock rd-clock--warning" : "rd-clock"} title={formatAbsolute(requisition.openedAt)}>
                            {requisition.status === "open" ? plural(health.openDays, "day", "days") : formatDayShort(requisition.openedAt)}
                          </span>
                          {health.aging ? <span className="rd-sub">past {RD_POLICY.agingDays} days</span> : null}
                        </TableCell>
                        <TableCell className="rd-drop-lg">{formatDayShort(requisition.targetStartAt)}</TableCell>
                        <TableCell className="rd-actions">
                          <RowActions transitions={requisitionTransitions(requisition)} onRun={(t) => onRequisitionTransition(requisition, t)} label={"Actions for " + requisition.title}
                            extra={(close) => <MenuItem onClick={() => { close(); onNavigate("/requisitions/" + requisition.id); }}>Open the pipeline</MenuItem>} />
                        </TableCell>
                      </TableRow>
                    );
                  })}
                </TableBody>
              </Table>
            </div>
          )}
          {rows.length ? (
            <CardFooter className="rd-card-foot">
              <span className="rd-foot">Showing all {rows.length} of {data.requisitions.length} requisitions. Seats count accepted offers against headcount, not applications.</span>
              <ExportMenu scope={plural(rows.length, "requisition", "requisitions")} onExport={(format) => pushToast({ title: format + " export started", description: "The file lands in your downloads." })} />
            </CardFooter>
          ) : null}
        </Card>
      </div>
    );
  }

  /* ── One requisition: the board is the display, because the question here is
     "where is everybody", not "list them". ─────────────────────────────────── */
  function RequisitionScreen({ requisition, data, now, session, onNavigate, onRequisitionTransition, onApplicationTransition }) {
    const health = requisitionHealth(data.applications, requisition, now);
    const advert = advertFor(data.adverts, requisition.id);
    const board = pipelineBoard(data.applications, requisition.id);
    const manager = staffById(data.staff, requisition.hiringManagerId);
    const recruiter = staffById(data.staff, requisition.recruiterId);

    return (
      <div className="rd-page">
        <PageHead path="/requisitions/:id" params={{ id: requisition.id }} labels={{ "/requisitions/:id": requisition.title }}
          title={requisition.title}
          note={requisition.ref + " · " + labelOf(SITES, requisition.site) + " · " + labelOf(EMPLOYMENT_TYPES, requisition.employmentType) + " · " + bandLabel(requisition)}
          actions={<Transitions size="sm" transitions={requisitionTransitions(requisition)} onRun={(t) => onRequisitionTransition(requisition, t)} />} />

        {/* Views within the record, both registered routes — never a second set
            of top-level destinations. */}
        <div className="rd-card-tabs">
          <ViewTabs value="pipeline" onSelect={(v) => { if (v === "advert") onNavigate("/requisitions/" + requisition.id + "/advert"); }}
            views={[
              { value: "pipeline", label: "Pipeline", count: health.live.length },
              { value: "advert", label: "Advert", count: advert ? advert.postedTo.length : 0 },
            ]} />
        </div>

        {requisition.status === "on_hold" ? (
          <Alert variant="warning">
            <Icon name="pause" size={16} />
            <AlertTitle>On hold</AlertTitle>
            <AlertDescription>{requisition.holdNote}</AlertDescription>
          </Alert>
        ) : null}
        {health.thin ? (
          <Alert variant="warning">
            <Icon name="triangle-alert" size={16} />
            <AlertTitle>{plural(health.live.length, "live application", "live applications")} for {plural(health.seatsLeft, "unfilled seat", "unfilled seats")}</AlertTitle>
            <AlertDescription>Under {RD_POLICY.thinPipeline} live applications per requisition is where seats start slipping. The target start is {formatDay(requisition.targetStartAt)}, {durationWords(health.daysToTarget)}.</AlertDescription>
          </Alert>
        ) : null}

        <div className="rd-anchor">
          <span className="rd-part">
            <span className="rd-anchor__label">Seats filled</span>
            <span className="rd-anchor__figure">{health.accepted} of {health.seats}</span>
            <span className="rd-tile__qual">Accepted offers, not applications</span>
          </span>
          <span className="rd-part">
            <span className="rd-anchor__label">Live applications</span>
            <span className="rd-anchor__figure">{health.live.length}</span>
            <span className="rd-tile__qual">{health.awaitingUs} waiting on the desk</span>
          </span>
          <span className="rd-part">
            <span className="rd-anchor__label">Over their service level</span>
            <span className="rd-anchor__figure">{health.stalled}</span>
            <span className="rd-tile__qual">Per stage, on this requisition only</span>
          </span>
          <span className="rd-part">
            <span className="rd-anchor__label">Open</span>
            <span className="rd-anchor__figure">{health.openDays}</span>
            <span className="rd-tile__qual">days since {formatDay(requisition.openedAt)}{health.aging ? " — past " + RD_POLICY.agingDays : ""}</span>
          </span>
        </div>

        <Card>
          <CardHeader>
            <CardTitle>The brief</CardTitle>
            <CardDescription>Target start {formatDay(requisition.targetStartAt)} · {plural(requisition.headcount, "seat", "seats")}{requisition.registration ? " · " + requisition.registration + " registration required" : " · no professional register required"}</CardDescription>
          </CardHeader>
          <CardPanel>
            <div className="rd-stack">
              <p className="rd-note__text">{requisition.brief || requisition.holdNote}</p>
              <Separator />
              <div className="rd-kv">
                <span className="rd-part"><span className="rd-kv__label">Hiring manager</span><StaffCell person={manager} /></span>
                <span className="rd-part"><span className="rd-kv__label">Recruiter</span><StaffCell person={recruiter} /></span>
                <span className="rd-part"><span className="rd-kv__label">Band</span><span className="rd-kv__value">{bandLabel(requisition)}</span></span>
                <span className="rd-part"><span className="rd-kv__label">Department</span><span className="rd-kv__value">{labelOf(DEPARTMENTS, requisition.department)}</span></span>
              </div>
            </div>
          </CardPanel>
        </Card>

        <Card>
          <CardHeader>
            <CardTitle>The pipeline</CardTitle>
            <CardDescription>{plural(health.all.length, "application", "applications")} in all, {health.live.length} of them live. One column per step of the process.</CardDescription>
          </CardHeader>
          <CardPanel>
            <div className="rd-board">
              {board.map((column) => (
                <div className="rd-lane" key={column.stage}>
                  <div className="rd-lane__head">
                    <span className="rd-lane__title">{column.label}<span className="rd-lane__count">{column.items.length}</span></span>
                    <span className="rd-lane__figure">{column.means}</span>
                  </div>
                  <div className="rd-lane__list">
                    {column.items.length
                      ? column.items.map((application) => <AppCard key={application.id} application={application} data={data} now={now} onNavigate={onNavigate} />)
                      : <p className="rd-lane__empty">Nobody at this step.</p>}
                  </div>
                </div>
              ))}
            </div>
          </CardPanel>
          <CardFooter className="rd-card-foot">
            <span className="rd-foot">Settled applications are not on the board. {plural(health.all.filter((a) => !APPLICATION_FLAGS.isLive(a)).length, "application", "applications")} declined, withdrawn or hired.</span>
            <Button variant="outline" size="sm" onClick={() => onNavigate("/applications")}>See them in the queue</Button>
          </CardFooter>
        </Card>
      </div>
    );
  }

  /* ── /requisitions/new — Staged, its own route, opens as a draft. ──────── */
  function NewRequisitionScreen({ data, now, session, onNavigate, onCreateRequisition }) {
    const [values, setValues] = React.useState({
      title: "", department: "nursing", site: "community", employmentType: "permanent",
      headcount: "1", bandLow: "", bandHigh: "", registration: "NMC", hiringManagerId: "p-esme", targetStart: "", brief: "",
    });
    const [dirty, setDirty] = React.useState(false);
    const [submitted, setSubmitted] = React.useState(false);
    const set = (id, value) => { setDirty(true); setValues((v) => Object.assign({}, v, { [id]: value })); };

    const low = Math.round(parseFloat(values.bandLow.replace(/[^0-9.]/g, "")) * 100);
    const high = Math.round(parseFloat(values.bandHigh.replace(/[^0-9.]/g, "")) * 100);
    const errors = {};
    if (!values.title.trim()) errors.title = "What is the seat called? It is what candidates search for.";
    if (!values.bandLow || isNaN(low)) errors.bandLow = "Bottom of the band, whole pounds.";
    if (!values.bandHigh || isNaN(high)) errors.bandHigh = "Top of the band, whole pounds.";
    else if (low && high && high < low) errors.bandHigh = "The top of the band cannot be below the bottom.";
    if (!values.targetStart) errors.targetStart = "When does this seat need somebody in it?";
    else if (new Date(values.targetStart + "T00:00:00").getTime() < now) errors.targetStart = "That date has passed.";
    if (!Number(values.headcount) || Number(values.headcount) < 1) errors.headcount = "At least one seat.";
    const valid = Object.keys(errors).length === 0;

    return (
      <div className="rd-page">
        <PageHead path="/requisitions/new" title="New requisition"
          note="It opens as a draft. Nothing can be applied to a draft — opening it is a second, deliberate action from the requisition itself." />
        <div className="rd-columns">
          <Card>
            <CardHeader><CardTitle>The seat</CardTitle></CardHeader>
            <CardPanel>
              <div className="rd-fields">
                <Field>
                  <FieldLabel htmlFor="rq-title">Title</FieldLabel>
                  <Input id="rq-title" value={values.title} invalid={submitted && !!errors.title} placeholder="Community staff nurse" onChange={(e) => set("title", e.target.value)} />
                  {submitted && errors.title ? <FieldError>{errors.title}</FieldError> : null}
                </Field>
                <Field>
                  <FieldLabel htmlFor="rq-dept">Department</FieldLabel>
                  <Select id="rq-dept" value={values.department} items={DEPARTMENTS.map((d) => ({ value: d.value, label: d.label }))} onValueChange={(v) => set("department", v)} />
                </Field>
                <Field>
                  <FieldLabel htmlFor="rq-site">Site</FieldLabel>
                  <Select id="rq-site" value={values.site} items={SITES.map((s) => ({ value: s.value, label: s.label }))} onValueChange={(v) => set("site", v)} />
                </Field>
                <Field>
                  <FieldLabel htmlFor="rq-type">Employment type</FieldLabel>
                  <Select id="rq-type" value={values.employmentType} items={EMPLOYMENT_TYPES.map((t) => ({ value: t.value, label: t.label }))} onValueChange={(v) => set("employmentType", v)} />
                </Field>
                <Field>
                  <FieldLabel htmlFor="rq-register">Professional register</FieldLabel>
                  <Select id="rq-register" value={values.registration} items={REGISTERS.map((r) => ({ value: r.value, label: r.label }))} onValueChange={(v) => set("registration", v)} />
                  <FieldDescription>Whether this seat may only be filled by somebody on a register. Compliance holds a start date on it; a seat that asks for none is not blocked by it.</FieldDescription>
                </Field>
                <Field>
                  <FieldLabel htmlFor="rq-heads">Seats</FieldLabel>
                  <Input id="rq-heads" value={values.headcount} invalid={submitted && !!errors.headcount} onChange={(e) => set("headcount", e.target.value)} />
                  {submitted && errors.headcount ? <FieldError>{errors.headcount}</FieldError> : <FieldDescription>How many people this requisition may hire. Seats fill on accepted offers.</FieldDescription>}
                </Field>
              </div>
            </CardPanel>
          </Card>
          <Card>
            <CardHeader><CardTitle>Money, dates and the brief</CardTitle></CardHeader>
            <CardPanel>
              <div className="rd-fields">
                <Field>
                  <FieldLabel htmlFor="rq-low">Band, bottom</FieldLabel>
                  <Input id="rq-low" value={values.bandLow} invalid={submitted && !!errors.bandLow} placeholder="31049" onChange={(e) => set("bandLow", e.target.value)} />
                  {submitted && errors.bandLow ? <FieldError>{errors.bandLow}</FieldError> : null}
                </Field>
                <Field>
                  <FieldLabel htmlFor="rq-high">Band, top</FieldLabel>
                  <Input id="rq-high" value={values.bandHigh} invalid={submitted && !!errors.bandHigh} placeholder="37796" onChange={(e) => set("bandHigh", e.target.value)} />
                  {submitted && errors.bandHigh ? <FieldError>{errors.bandHigh}</FieldError> : <FieldDescription>Every offer is shown as a position inside this band.</FieldDescription>}
                </Field>
                <Field>
                  <FieldLabel htmlFor="rq-manager">Hiring manager</FieldLabel>
                  <Select id="rq-manager" value={values.hiringManagerId}
                    items={data.staff.filter((p) => p.role === "hiring_manager").map((p) => ({ value: p.id, label: p.name + " · " + p.title }))}
                    onValueChange={(v) => set("hiringManagerId", v)} />
                </Field>
                <Field>
                  <FieldLabel htmlFor="rq-start">Target start</FieldLabel>
                  <Input id="rq-start" type="date" value={values.targetStart} invalid={submitted && !!errors.targetStart} onChange={(e) => set("targetStart", e.target.value)} />
                  {submitted && errors.targetStart ? <FieldError>{errors.targetStart}</FieldError> : null}
                </Field>
                <Field>
                  <FieldLabel htmlFor="rq-brief">Brief</FieldLabel>
                  <Textarea id="rq-brief" rows={4} value={values.brief} placeholder="What the seat is, what is essential, what is desirable, anything unusual about the rota." onChange={(e) => set("brief", e.target.value)} />
                </Field>
              </div>
            </CardPanel>
          </Card>
        </div>
        <FormBar dirty={dirty} label="Save requisition" onCancel={() => onNavigate("/requisitions")}
          note={dirty ? "Saved as a draft, owned by you. It appears on Requisitions immediately and accepts nothing until it is opened." : "Nothing is saved yet."}
          onSave={() => { setSubmitted(true); if (valid) onCreateRequisition(Object.assign({}, values, { bandMinor: [low, high] })); }} />
      </div>
    );
  }

  Object.assign(window, { RequisitionsScreen, RequisitionScreen, NewRequisitionScreen });
})();
