/* The advert behind one requisition — a view WITHIN the record, reached by the
   requisition's own tabs, not a destination.
   Instant commit model: posting and unpublishing apply immediately with an undo
   toast; editing the wording opens a staged dialog, because it is a real piece
   of writing and nobody wants it half-saved.
   Views are the only figure that comes from outside the desk. Every other number
   here counts the applications array by `source`, which is why the channel table
   and the funnel on /insights cannot disagree. */
(() => {
  const {
    Card, CardHeader, CardTitle, CardDescription, CardPanel, CardFooter,
    Table, TableHeader, TableBody, TableRow, TableHead, TableCell,
    Button, Badge, Alert, AlertTitle, AlertDescription, Separator, MenuItem,
  } = window.OriginDesignSystem_7c998b;

  function AdvertScreen({ requisition, advert, data, now, session, onNavigate, onEditAdvert, onPostAdvert, onUnpostAdvert }) {
    const totals = advertTotals(advert, data.applications, now);
    const health = requisitionHealth(data.applications, requisition, now);
    const author = staffById(data.staff, advert.updatedById);
    const unposted = SOURCES.filter((source) => source.value !== "pool" && !advert.postedTo.some((p) => p.channel === source.value));
    const best = totals.rows.filter((row) => row.rate !== null).sort((a, b) => b.rate - a.rate)[0];

    return (
      <div className="rd-page">
        <PageHead path="/requisitions/:id/advert" params={{ id: requisition.id }}
          labels={{ "/requisitions/:id": requisition.title }} title={requisition.title + " — advert"}
          note={requisition.ref + " · " + labelOf(SITES, requisition.site) + " · " + bandLabel(requisition) + " · last edited " + formatDay(advert.updatedAt) + " by " + author.name}
          actions={
            <>
              <Button variant="outline" size="sm" onClick={() => onEditAdvert(requisition, advert)}><Icon name="pencil" size={14} />Edit the wording</Button>
              <Button size="sm" disabled={!unposted.length || requisition.status !== "open"} onClick={() => onPostAdvert(requisition, advert)}>
                <Icon name="megaphone" size={14} />Post to a channel
              </Button>
            </>
          } />

        <div className="rd-card-tabs">
          <ViewTabs value="advert" onSelect={(v) => { if (v === "pipeline") onNavigate("/requisitions/" + requisition.id); }}
            views={[
              { value: "pipeline", label: "Pipeline", count: health.live.length },
              { value: "advert", label: "Advert", count: totals.posted },
            ]} />
        </div>

        {requisition.status !== "open" ? (
          <Alert variant="warning">
            <Icon name="eye-off" size={16} />
            <AlertTitle>Not live anywhere</AlertTitle>
            <AlertDescription>
              {requisition.ref} is {statusValue(REQUISITION_STATUS, requisition.status).label.toLowerCase()}, so the advert cannot be posted.
              {requisition.holdNote ? " " + requisition.holdNote : ""} The wording is kept so it is not written twice.
            </AlertDescription>
          </Alert>
        ) : null}

        <div className="rd-metrics">
          <StatTile label="Views" value={formatCount(totals.views)}
            qualifier={totals.posted ? "Across " + plural(totals.posted, "channel", "channels") + ", since the earliest posting" : "Not posted anywhere"} />
          <StatTile label="Applications from the advert" value={totals.applications}
            qualifier={totals.elsewhere ? totals.elsewhere + " more arrived another way — referral, the pool, an event" : "Every application on this seat came through a posted channel"} />
          <StatTile label="Views to application" value={percent(totals.rate, true)}
            qualifier={totals.views ? totals.applications + " of " + formatCount(totals.views) + " people who read it applied" : "No views yet"} />
          <StatTile label="Best channel" value={best ? best.source.label : "—"}
            qualifier={best ? percent(best.rate, true) + " of its views applied — " + plural(best.applications, "application", "applications") : "Nothing to compare yet"} />
        </div>

        <div className="rd-columns">
          <div className="rd-col">
            <Card>
              <CardHeader>
                <CardTitle>The wording</CardTitle>
                <CardDescription>What a candidate reads. The essentials are what the screening step actually filters on.</CardDescription>
              </CardHeader>
              <CardPanel>
                <div className="rd-stack">
                  <h2 className="rd-advert__headline">{advert.headline}</h2>
                  {advert.body.split("\n\n").map((paragraph, i) => <p className="rd-advert__body" key={i}>{paragraph}</p>)}
                  <Separator />
                  <div className="rd-columns rd-columns--even">
                    <span className="rd-part">
                      <span className="rd-kv__label">Essential</span>
                      <ul className="rd-advert__list">
                        {advert.essentials.map((item) => <li key={item}><Icon name="check" size={13} />{item}</li>)}
                      </ul>
                    </span>
                    <span className="rd-part">
                      <span className="rd-kv__label">Desirable</span>
                      <ul className="rd-advert__list rd-advert__list--soft">
                        {advert.desirables.map((item) => <li key={item}><Icon name="plus" size={13} />{item}</li>)}
                      </ul>
                    </span>
                  </div>
                </div>
              </CardPanel>
              <CardFooter className="rd-card-foot">
                <span className="rd-foot">
                  {plural(advert.essentials.length, "essential", "essentials")} and {plural(advert.desirables.length, "desirable", "desirables")}.
                  Band and target start come from the requisition, so the advert cannot state a different figure.
                </span>
              </CardFooter>
            </Card>
          </div>

          <div className="rd-col">
            <Card>
              <CardHeader>
                <CardTitle>Where it is posted</CardTitle>
                <CardDescription>
                  {totals.posted ? plural(totals.posted, "channel", "channels") + ". Applications are counted from the applications on this requisition, by source and after the posting date." : "Not posted anywhere yet."}
                </CardDescription>
              </CardHeader>
              {totals.rows.length ? (
                <div className="rd-card-table">
                  <Table variant="card">
                    <TableHeader>
                      <TableRow>
                        <TableHead>Channel</TableHead>
                        <TableHead className="rd-num">Views</TableHead>
                        <TableHead className="rd-num">Applications</TableHead>
                        <TableHead className="rd-num rd-drop-md">Live</TableHead>
                        <TableHead className="rd-num">Rate</TableHead>
                        <TableHead className="rd-actions-head">Action</TableHead>
                      </TableRow>
                    </TableHeader>
                    <TableBody>
                      {totals.rows.map((row) => (
                        <TableRow key={row.posting.channel}>
                          <TableCell>
                            {row.source.label}
                            <span className="rd-sub">posted {formatDayShort(row.posting.postedAt)} · {plural(row.days, "day", "days")} up</span>
                          </TableCell>
                          <TableCell className="rd-num">{formatCount(row.views)}</TableCell>
                          <TableCell className="rd-num">{row.applications}</TableCell>
                          <TableCell className="rd-num rd-drop-md">{row.live || "—"}</TableCell>
                          <TableCell className="rd-num">{percent(row.rate, true)}</TableCell>
                          <TableCell className="rd-actions">
                            <Button variant="destructive-outline" size="xs" onClick={() => onUnpostAdvert(requisition, advert, row)}>Unpublish</Button>
                          </TableCell>
                        </TableRow>
                      ))}
                    </TableBody>
                  </Table>
                </div>
              ) : (
                <CardPanel>
                  <p className="rd-foot">
                    Nothing is live. {requisition.status === "open"
                      ? "Post it to a channel and applications from that channel are counted from the day it goes up."
                      : "It cannot be posted while the requisition is " + statusValue(REQUISITION_STATUS, requisition.status).label.toLowerCase() + "."}
                  </p>
                </CardPanel>
              )}
              {totals.rows.length ? (
                <CardFooter className="rd-card-foot">
                  <span className="rd-foot">
                    Rate is applications as a share of that channel's views. Views come from the channel itself; everything else on this screen counts the {plural(health.all.length, "application", "applications")} on {requisition.ref}.
                  </span>
                </CardFooter>
              ) : null}
            </Card>

            <Card>
              <CardHeader>
                <CardTitle>What the advert produced</CardTitle>
                <CardDescription>The people behind the numbers, newest first.</CardDescription>
              </CardHeader>
              <CardPanel>
                {totals.applications ? (
                  <div className="rd-list">
                    {totals.rows.reduce((all, row) => all.concat(row.rows), []).sort((a, b) => b.appliedAt - a.appliedAt).slice(0, 6).map((application) => (
                      <div className="rd-list__row" key={application.id}>
                        <div className="rd-list__main">
                          <CandidateCell application={application} onNavigate={onNavigate}
                            meta={labelOf(SOURCES, application.source) + " · applied " + formatDayShort(application.appliedAt)} />
                        </div>
                        <div className="rd-list__side">
                          <StatusBadge values={APPLICATION_STAGE} value={application.stage} />
                        </div>
                      </div>
                    ))}
                  </div>
                ) : <p className="rd-foot">No applications from a posted channel yet.</p>}
              </CardPanel>
              {totals.applications > 6 ? (
                <CardFooter className="rd-card-foot">
                  <span className="rd-foot">Showing 6 of {totals.applications}.</span>
                  <Button variant="outline" size="sm" onClick={() => onNavigate("/requisitions/" + requisition.id)}>Open the pipeline</Button>
                </CardFooter>
              ) : null}
            </Card>
          </div>
        </div>
      </div>
    );
  }

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