/* Journeys — the automations, as list-detail.
   Commit model: INSTANT. Publish, pause and resume apply immediately and raise
   an undo toast; stopping a journey is irreversible and opens a confirm dialog.
   Data state: one branch — populated. A journey is always selected, so the
   detail column has no empty state to render.
   Primary display: a step ladder, not a table. The question a journey answers is
   "where do people stop", and each step carries its own drop-off meter whose
   track is exactly the number that entered that step.
   Recession, not disabling (§5.4): a draft or stopped journey keeps its link,
   its badge and its numbers on a muted surface — there is nothing to act on
   until somebody publishes it. */
(() => {
  const { Badge, Button } = window.OriginDesignSystem_7c998b;

  function StepRow({ step, journey }) {
    const kind = STEP_KINDS.find((k) => k.value === step.kind) || { label: step.kind, icon: "circle" };
    const failureRate = stepFailureRate(step);
    const failing = isOverFailureThreshold(step.failed, step.entered);
    const ran = step.entered > 0;
    const pct = (n) => (step.entered ? (n / step.entered) * 100 : 0);
    return (
      <div className={"md-step" + (ran ? "" : " md-step--recessed")}>
        <span className="md-step__rail">
          <span className="md-step__line" aria-hidden="true" />
          <span className="md-step__dot"><Icon name={kind.icon} size={14} /></span>
        </span>
        <div className="md-step__body">
          <div className="md-step__head">
            <span className="md-step__label">{step.label}</span>
            <span className="md-step__kind">{kind.label}{step.waitHours ? " · " + (step.waitHours >= 48 ? step.waitHours / 24 + " days" : step.waitHours + " hours") : ""}</span>
            {failing ? <Badge size="sm" variant="destructive">{formatPercent(failureRate)} failing</Badge> : null}
            {step.ready === false ? <Badge size="sm" variant="warning">No subject line yet</Badge> : null}
          </div>
          {ran ? (
            <Meter
              label={formatCount(step.completed) + " continued · " + formatCount(step.at) + " waiting here · " + formatCount(step.failed) + " failed · " + formatCount(step.exited) + " left"}
              parts={[
                { key: "completed", percent: pct(step.completed) },
                { key: "failed", tone: "danger", percent: pct(step.failed) },
                { key: "exited", tone: "soft", percent: pct(step.exited) },
              ]}
            />
          ) : (
            <span className="md-footnote">Nobody has entered this step — the journey has never run.</span>
          )}
        </div>
        <div className="md-step__side">
          <span className="md-amount">{formatCount(step.entered)}</span>
          <span className="md-footnote">entered</span>
        </div>
      </div>
    );
  }

  function JourneysScreen({ data, now, path, selectedId, onNavigate, onJourneyTransition }) {
    const journey = data.journeys.find((j) => j.id === selectedId) || data.journeys[0];
    const audience = audienceById(data.audiences, journey.audienceId);
    const enrolled = journeyEnrolled(journey);
    const holding = journey.steps.filter((s) => s.at > 0);
    const failed = journeyFailed(journey);
    const worstStep = journey.steps.slice().sort((a, b) => b.failed - a.failed)[0];
    const sendEntered = sumBy(journeySendSteps(journey), "entered");

    return (
      <>
        <PageHeader
          path={path === "/journeys" ? "/journeys" : "/journeys/:id"}
          params={{ id: journey.id }}
          title={path === "/journeys" ? "Journeys" : journey.name}
          crumb={path === "/journeys" ? null : journey.name}
          actions={<Button size="sm" onClick={() => onNavigate("/journeys/new")}><Icon name="plus" />New journey</Button>}
        />

        <section className="md-band md-band--fill">
          <div className="md-split">
            <div className="md-picklist">
              {data.journeys.map((row) => {
                const concern = journeyConcern(row, now);
                const recessed = JOURNEY_FLAGS.isRecessed(row);
                return (
                  <button
                    type="button"
                    key={row.id}
                    className={"md-pick" + (row.id === journey.id ? " md-pick--on" : "") + (recessed ? " md-pick--recessed" : "")}
                    aria-current={row.id === journey.id ? "true" : undefined}
                    onClick={() => onNavigate("/journeys/" + row.id)}
                  >
                    <span className="md-pick__name">{row.name}</span>
                    <span className="md-pick__side">
                      {JOURNEY_FLAGS.needsAttention(row, now) ? <Icon name="triangle-alert" size={14} /> : null}
                      <StatusBadge values={JOURNEY_STATUS} value={row.status} />
                    </span>
                    <span className="md-pick__meta">
                      {concern || (row.status === "draft"
                        ? "Never published · " + row.steps.length + " steps written"
                        : formatCount(journeyEnrolled(row)) + " enrolled · " + formatPercent(journeyConversion(row)) + " reach the end")}
                    </span>
                  </button>
                );
              })}
            </div>

            <div className="md-split__detail">
              <div className="md-band__head" style={{ padding: "var(--space-6) var(--gutter-page) 0" }}>
                <div>
                  <h2 className="md-band__title">{journey.name}</h2>
                  <p className="md-band__note">
                    {journey.status === "paused"
                      ? "Paused by " + journey.pausedBy + " " + formatWhen(journey.pausedAt, now) + ". Everyone enrolled is holding where they were."
                      : journey.status === "draft"
                        ? "Written but never published. Nothing enters it and nothing sends."
                        : journeyConcern(journey, now) || "Sending normally. Last send " + formatWhen(journey.lastSendAt, now) + "."}
                  </p>
                </div>
                <div className="md-page-header__actions">
                  <StatusBadge values={JOURNEY_STATUS} value={journey.status} />
                  {journey.status === "draft" ? (
                    <Button variant="outline" size="sm" onClick={() => onNavigate("/journeys/" + journey.id + "/steps")}><Icon name="pencil" />Edit steps</Button>
                  ) : null}
                  <Transitions transitions={journeyTransitions(journey, data.content)} onRun={(t) => onJourneyTransition(journey, t)} />
                </div>
              </div>

              <dl className="md-facts" style={{ borderTop: 0 }}>
                <div>
                  <dt>Trigger</dt>
                  <dd>{journey.trigger}</dd>
                </div>
                <div>
                  <dt>Audience</dt>
                  <dd>
                    <button type="button" className="md-link" onClick={() => onNavigate("/audiences")}>{audience.name}</button>
                    <span className="md-muted"> · {formatCount(audience.size)} in it now</span>
                  </dd>
                </div>
                <div>
                  <dt>Owner</dt>
                  <dd>{memberName(data.members, journey.ownerId)}</dd>
                </div>
                <div>
                  <dt>Published</dt>
                  <dd title={journey.publishedAt ? formatAbsolute(journey.publishedAt) : ""}>{journey.publishedAt ? formatWhen(journey.publishedAt, now) : "Never"}</dd>
                </div>
                <div>
                  <dt>Last send</dt>
                  <dd title={journey.lastSendAt ? formatAbsolute(journey.lastSendAt) : ""}>{formatWhen(journey.lastSendAt, now)}</dd>
                </div>
              </dl>

              <Figures three items={[
                {
                  label: "Enrolled now",
                  value: formatCount(enrolled),
                  qualifier: holding.length
                    ? holding.map((s) => formatCount(s.at) + " at “" + s.label + "”").join(" · ")
                    : "Nobody is sitting at any step",
                },
                {
                  label: "Reached the end",
                  value: formatCount(journeyFinished(journey)),
                  qualifier: journeyEntered(journey)
                    ? formatPercent(journeyConversion(journey)) + " of the " + formatCount(journeyEntered(journey)) + " who have ever entered"
                    : "Nobody has entered it yet",
                },
                {
                  label: "Delivery failures",
                  value: formatCount(failed),
                  qualifier: failed
                    ? formatCount(worstStep.failed) + " of them on “" + worstStep.label + "” · " + formatPercent(rate(failed, sendEntered)) + " of every send attempt"
                    : "Every send attempt was accepted",
                },
              ]} />

              <div className="md-ladder">
                {journey.steps.map((step) => <StepRow key={step.id} step={step} journey={journey} />)}
              </div>

              <p className="md-footnote" style={{ padding: "var(--space-4) var(--gutter-page) var(--space-6)" }}>
                Each meter's track is the number that entered that step, so the tail is whoever is still waiting there. Entered on a step is what continued from the one above it.
              </p>
            </div>
          </div>
        </section>
      </>
    );
  }

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