/* WorkflowRail — status lifecycle (§5) with server-style gate enforcement,
   the changes-requested correction loop, role assignment, scheduling
   (§6A via ScheduleControls) and the metrics pull seam (M10). */
(function () {
  const D = window.CROPR_DATA;
  const S = window.CroprStore;

  // Progress across the EDITABLE workflow stages (from the store), so the rail and
  // the board always show the same flow.
  function Stepper({ status }) {
    const wf = S.getWorkflow();
    const idx = wf.findIndex((s) => s.key === status);
    return (
      <div style={{ display: "flex", alignItems: "center", gap: 4, marginBottom: 4, flexWrap: "wrap" }}>
        {wf.map((s, i) => (
          <span key={s.key} style={{ fontSize: 10.5, fontWeight: 600, padding: "2px 7px", borderRadius: 999, whiteSpace: "nowrap",
            background: i === idx ? "var(--accent)" : (i < idx ? "var(--accent-weak)" : "var(--bg-muted)"),
            color: i === idx ? "#fff" : (i < idx ? "var(--accent)" : "var(--fg4)") }}>{s.name}</span>
        ))}
      </div>
    );
  }

  function MetricsRow({ metrics }) {
    const items = [["Impressions", metrics.impressions], ["Engagements", metrics.engagements], ["Saves", metrics.saves],
      ["Reshares", metrics.reshares], ["Follows", metrics.follows], ["Clicks", metrics.clicks]];
    return (
      <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 8, marginTop: 8 }}>
        {items.map(([l, v]) => (
          <div key={l} style={{ background: "var(--bg-subtle)", borderRadius: 10, padding: "8px 10px" }}>
            <div style={{ fontSize: 10, color: "var(--fg3)", fontWeight: 600, textTransform: "uppercase", letterSpacing: ".04em" }}>{l}</div>
            <div style={{ fontSize: 16, fontWeight: 700, fontVariantNumeric: "tabular-nums" }}>{v != null ? Number(v).toLocaleString("en-GB") : "—"}</div>
          </div>
        ))}
      </div>
    );
  }

  function WorkflowRail({ post, ruleCheck, onToast, onNav }) {
    const next = S.nextStage(post.status);
    const nextGate = next ? S.canTransition(post, next) : { ok: false };
    const nextName = next ? S.stageLabel(next) : null;
    const nextOwner = next ? (S.getStageOwner(post, next) || "") : "";
    // The responsible person is a workspace member — stage-owner notifications
    // resolve against the workspace team (memberByName), and the workflow itself
    // is global — so offer the full team, not the (possibly empty) client scope.
    const team = (S.getTeam ? S.getTeam() : []) || [];
    const teamOpts = [{ value: "", label: "— unassigned" }, ...team.map((m) => ({ value: m.name, label: m.name }))];
    const stageOpts = S.getWorkflow().filter((s) => s.key !== post.status).map((s) => ({ value: s.key, label: s.name }));
    const showSchedule = post.status === "approved" || post.status === "scheduled" || next === "scheduled";
    const showMetrics = post.status === "published" || post.status === "amplify" || post.status === "tracked";

    const advance = () => { if (!next) return; const owner = S.getStageOwner(post, next); const r = S.transition(post.id, next); onToast(r.ok ? `Moved to ${S.stageLabel(next)}` + (owner ? ` — ${owner} notified` : "") : r.reason, r.ok ? "ok" : "error"); };
    const moveTo = (to) => { if (!to || to === post.status) return; const owner = S.getStageOwner(post, to); const r = S.transition(post.id, to); onToast(r.ok ? `Moved to ${S.stageLabel(to)}` + (owner ? ` — ${owner} notified` : "") : r.reason, r.ok ? "ok" : "error"); };

    return (
      <div>
        <div style={{ display: "flex", alignItems: "center", gap: 8, marginBottom: 12 }}>
          <Icon name="git-branch" size={18} color="var(--accent)" />
          <span style={{ fontSize: 13, fontWeight: 700 }}>Workflow</span>
          <div style={{ flex: 1 }} />
          <StatusBadge status={post.status} />
        </div>
        <Stepper status={post.status} />

        {/* Responsible person for the next stage — they're notified on advance */}
        {next ? (
          <div style={{ margin: "14px 0" }}>
            <Field label={`Responsible for “${nextName}” (next stage)`} hint="They're notified when the post reaches this stage.">
              <Select value={nextOwner} onChange={(v) => S.assignStageOwner(post.id, next, v)} options={teamOpts} />
            </Field>
          </div>
        ) : (
          <div style={{ margin: "14px 0", fontSize: 12, color: "var(--fg3)" }}>This is the final stage in the workflow.</div>
        )}

        {/* Advance + move-to-any-stage (uniform for every stage) */}
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {next && <Button variant="primary" iconRight="arrow-right" full disabled={!nextGate.ok} onClick={advance}>Advance to {nextName}</Button>}
          {next && !nextGate.ok && <div style={{ fontSize: 11.5, color: "#B25E09", display: "flex", gap: 6 }}><Icon name="lock" size={14} color="#B25E09" />{nextGate.reason}</div>}
          {stageOpts.length > 0 && (
            <Field label="Or move to any stage" hint="Assign that stage's owner first to notify them.">
              <Select value="" onChange={moveTo} options={[{ value: "", label: "Move to…" }, ...stageOpts]} />
            </Field>
          )}
        </div>

        {showSchedule && (
          <div style={{ borderTop: "1px solid var(--border)", paddingTop: 14, marginTop: 14 }}>
            <ScheduleControls post={post} onToast={onToast} />
          </div>
        )}

        {showMetrics && (
          <div style={{ borderTop: "1px solid var(--border)", paddingTop: 14, marginTop: 14 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
              <span style={{ fontSize: 12, fontWeight: 700 }}>Performance</span>
              <div style={{ flex: 1 }} />
              {/* Live: metrics sync from the platform automatically (worker) — no
                  manual pull. Offline demo: the synthetic pull keeps it alive. */}
              {window.LeapAPI && window.LeapAPI.configured()
                ? <span style={{ fontSize: 11, color: "var(--fg3)", display: "flex", alignItems: "center", gap: 5 }}><Icon name="refresh-cw" size={12} color="var(--fg3)" />Auto-synced</span>
                : <Button size="sm" variant="secondary" icon="download-cloud" onClick={() => { S.pullMetrics(post.id); onToast("Metrics pulled (simulated)"); }}>Pull metrics</Button>}
            </div>
            {post.metrics && Object.keys(post.metrics).length
              ? <MetricsRow metrics={post.metrics} />
              : <div style={{ fontSize: 11.5, color: "var(--fg3)", marginTop: 6 }}>{window.LeapAPI && window.LeapAPI.configured() ? "Metrics sync automatically a few minutes after publishing." : "No metrics yet — pull once the post has aged."}</div>}
          </div>
        )}

        {post.correctionNotes && post.correctionNotes.length > 0 && (
          <div style={{ marginTop: 14, borderTop: "1px solid var(--border)", paddingTop: 12 }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: "var(--fg3)", textTransform: "uppercase", letterSpacing: ".05em", marginBottom: 8 }}>Correction notes</div>
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              {post.correctionNotes.map((n, i) => (
                <div key={i} style={{ background: "var(--warning-bg)", borderRadius: 10, padding: "8px 10px" }}>
                  <div style={{ fontSize: 12.5, color: "var(--fg1)" }}>{n.note}</div>
                  <div style={{ fontSize: 10.5, color: "var(--fg3)", marginTop: 3 }}>{n.by} · {new Date(n.at).toLocaleString("en-GB", { day: "2-digit", month: "short", hour: "2-digit", minute: "2-digit" })}</div>
                </div>
              ))}
            </div>
          </div>
        )}
      </div>
    );
  }
  window.WorkflowRail = WorkflowRail;
})();
