// Canvas Directions v2 — generative-UI blocks that compose IN the thread.
// A block is live (mutates in place, shows freshness) until superseded — then it
// freezes into a one-line chip. State renders once, agent-natively.
// Loads after canvas-parts.jsx / canvas-stage.jsx.

const BConsentChip = (props) => { const C = (window.StimulusDesignSystem_bb8fa3 || {}).ConsentChip; return C ? React.createElement(C, props) : null; };

function BlockShell({ title, meta, frozen, time, onReopen, onOpenFull, openLabel, badge, children }) {
  if (frozen) {
    return (
      <button type="button" className="cvFrozen" onClick={onReopen}
        title="This view was superseded — reopen it as it is now">
        <Icon name="history" size={12} />
        <span className="cvFrozenT">{title}</span>
        {meta && <span className="cvFrozenM">{meta}</span>}
        <span className="cvFrozenTime">as it was at {time}</span>
        <span className="cvFrozenAct">Reopen</span>
      </button>
    );
  }
  return (
    <div className="cvBlock" data-part="block">
      <div className="cvBlockHead">
        <span className="cvBlockLive" title="This view is live — it mutates in place, it is not a transcript">
          <span className="cvBlockDot" aria-hidden="true"></span> live
        </span>
        <span className="cvBlockTitle">{title}</span>
        {meta && <span className="cvBlockMeta tabular">{meta}</span>}
        {badge}
        {onOpenFull && (
          <button type="button" className="cvBlockOpen" onClick={onOpenFull}>
            {openLabel || "Open full view"} <Icon name="chevR" size={11} />
          </button>
        )}
      </div>
      <div className="cvBlockBody">{children}</div>
    </div>
  );
}

// ── Morning brief, composed in-thread — the agent-native home ────────────
function BriefBlock({ role, onAsk, frozen, time, onReopen }) {
  const items = role === "sam" ? [
    { t: "Marco Silva opened your last email twice yesterday", d: "Meridian founder · your strength 84", a: "Draft the nudge" },
    { t: "Procurement's shortlist carries 2 of your relationships", d: "Q3 caterers · your intro could accelerate both", a: "See which ones" },
    { t: "Skyline AV meeting notes are unfiled", d: "Tuesday's meeting · filing keeps the score honest", a: "File them" },
  ] : [
    { t: "9 catering vendors have been quiet since 2024", d: "FIFA-era relationships going cold · re-engagement window open", a: "See the nine" },
    { t: "Meridian's FIFA contract window is closing", d: "from imported terms · warm path available via Sam Cole", a: "How did we get here?" },
    { t: "31 interest-form leads never contacted", d: "oldest from July 2025 · a sweep can draft the first touch", a: "Propose the sweep" },
  ];
  return (
    <BlockShell title="Today, before 10 AM" meta={items.length + " items"} frozen={frozen} time={time} onReopen={onReopen}>
      {items.map((it) => (
        <div key={it.t} className="cvBlockRow">
          <div className="cvBlockRowMain">
            <span className="cvBlockRowT">{it.t}</span>
            <span className="cvBlockRowD">{it.d}</span>
          </div>
          <button type="button" className="cvBtnQuiet" onClick={() => onAsk(it.a)}>{it.a}</button>
        </div>
      ))}
    </BlockShell>
  );
}

// ── Compact live table — the agent composing over the working set ────────
function TableBlock({ rows, label, frozen, time, onReopen, onOpenFull, onOpenEntity }) {
  const shown = rows.slice(0, 6);
  return (
    <BlockShell title={"Businesses — " + label} meta={rows.length + " match"} frozen={frozen} time={time}
      onReopen={onReopen} onOpenFull={onOpenFull} openLabel="Open full table">
      <table className="cvBlockTable">
        <tbody>
          {shown.map((r) => (
            <tr key={r.id}>
              <td>
                <button type="button" className="cvBizName" onClick={() => r.entity && onOpenEntity(r.id)}>
                  {r.name}{r.warmPath && <span className="cvWarmDot" title="Warm intro available"></span>}
                </button>
              </td>
              <td className="cvCellMut">{r.stage}</td>
              <td className="cvCellMut">{r.lastTouch}</td>
              <td className="cvThNum"><StrengthCell score={r.strength} trend={r.trend} why={r.why} /></td>
              <td><BConsentChip level={r.consent} size="inline" grantedBy={r.grantedBy} /></td>
            </tr>
          ))}
        </tbody>
      </table>
      {rows.length > shown.length && (
        <button type="button" className="cvBlockMore" onClick={onOpenFull}>+ {rows.length - shown.length} more — open the full table</button>
      )}
    </BlockShell>
  );
}

// ── Shortlist block — the demo jewel, composed in-thread ─────────────────
function ShortlistBlock({ rows, shared, frozen, time, onReopen, onOpenFull, onOpenEntity, onShare }) {
  const shown = rows.slice(0, 4);
  return (
    <BlockShell title="Q3 caterers — re-engagement shortlist" meta={rows.length + " businesses"}
      frozen={frozen} time={time} onReopen={onReopen} onOpenFull={onOpenFull} openLabel="Open the shortlist"
      badge={shared && <span className="cvBlockShared"><BConsentChip level="shared" size="inline" /> shared to Legacy Sports</span>}>
      {shown.map((r, i) => (
        <div key={r.id} className="cvBlockRow">
          <span className="cvShortRank tabular">{i + 1}</span>
          <div className="cvBlockRowMain">
            <button type="button" className="cvBizName" onClick={() => r.entity && onOpenEntity(r.id)}>{r.name}</button>
            <span className="cvBlockRowD">{r.why}</span>
            {r.warmPath && <WarmPath path={window.CanvasData.meridian.warmPath} />}
          </div>
          <span className="cvShortDorm">{r.dormantSince ? <span>quiet since <b>{r.dormantSince}</b></span> : "active thread"}</span>
        </div>
      ))}
      <div className="cvBlockFoot">
        <button type="button" className="cvBlockMore" onClick={onOpenFull}>+ {rows.length - shown.length} more rows</button>
        {!shared && <button type="button" className="cvBtnPrimary" onClick={onShare}>Share as list</button>}
      </div>
    </BlockShell>
  );
}

// ── Entity card block — Meridian at a glance, full profile one click away ─
function EntityCardBlock({ e, frozen, time, onReopen, onOpenFull }) {
  return (
    <BlockShell title={e.name} meta={e.stage} frozen={frozen} time={time} onReopen={onReopen}
      onOpenFull={onOpenFull} openLabel="Open the profile">
      <div className="cvBlockEntity">
        <div className="cvBlockEntityScore">
          <span className="cvEntityScoreN tabular">{e.strength.score}</span>
          <span className="cvEntityScoreRead">{e.strength.read}</span>
        </div>
        <div className="cvBlockEntityFacts">
          <div className="cvBlockRowD">{e.facts[0].value} <BConsentChip level="shared" size="inline" grantedBy="FIFA" /></div>
          <div className="cvBlockRowD cvBlockLock"><Icon name="lock" size={11} /> One more fact exists here — not shared with you.</div>
          <WarmPath path={e.warmPath} />
        </div>
      </div>
    </BlockShell>
  );
}

// ── Journey block — the relationship's story, list-first, every moment cites its fact ─
// The graph stays backend: this is its intelligence surfaced as a story, not nodes.
function JourneyBlock({ e, frozen, time, onReopen, onOpenFull }) {
  const j = e.journey;
  const first = j[0].s, last = j[j.length - 1].s;
  return (
    <BlockShell title={e.name + " — how we got here"} meta={first + " → " + last + " since June"}
      frozen={frozen} time={time} onReopen={onReopen} onOpenFull={onOpenFull} openLabel="Open the profile">
      <div className="cvJourney">
        {j.map((m, i) => (
          <div key={m.t + m.e} className="cvJRow">
            <div className="cvJRail">
              <span className={"cvJDot" + (i === j.length - 1 ? " isNow" : "")}></span>
              {i < j.length - 1 && <span className="cvJLine"></span>}
            </div>
            <div className="cvJMain">
              <div className="cvJTop">
                <span className="cvJDate tabular">{m.t}</span>
                <span className="cvJStage">{m.stage}</span>
              </div>
              <div className="cvJEvent">{m.e}</div>
              <div className="cvJWhy mono">{m.why}</div>
            </div>
            <div className="cvJScore">
              <span className="tabular cvJScoreN">{m.s}</span>
              {m.d && <span className="cvJDelta tabular">{m.d}</span>}
            </div>
          </div>
        ))}
      </div>
    </BlockShell>
  );
}

// ── The reveal (J2) — the canvas wakes composed. "You already have this." ─
// Assembles progressively: sentence → metrics → proof rows → actions. Every claim
// carries its receipt (origin + last touch) — it reads as audit, not magic.
// Role-projected live: toggling the viewer re-projects this block in place.
function RevealBlock({ role, built, onAct, acted, frozen, time, onReopen }) {
  const d = role === "sam" ? window.SRIData.revealSam : window.SRIData.reveal;
  const proof = window.SRIData.businesses.filter((b) => d.proofIds.includes(b.id));
  const b = built == null ? 3 : built;
  return (
    <BlockShell title={role === "sam" ? "Your reveal — projected to partnerships" : "Your reveal — from this morning's build"}
      meta="nothing committed" frozen={frozen} time={time} onReopen={onReopen}>
      <p className="svRevealLede"><b>{d.headline}</b> {d.sentence}</p>
      {b >= 1 ? (
        <div className="svRevealMetrics">
          {d.metrics.map((m) => (
            <div key={m.label} className="svRevealMetric">
              <span className="n tabular">{m.n}</span><span className="l">{m.label}</span><span className="s">{m.sub}</span>
            </div>
          ))}
        </div>
      ) : <div className="svRevealAssembling">Assembling from your files — the rest streams in…</div>}
      {b >= 2 && (
        <React.Fragment>
          <div className="svRevealProofH">The proof — every claim, its receipt</div>
          {proof.map((r) => (
            <div key={r.id} className="cvBlockRow">
              <div className="cvBlockRowMain">
                <span className="cvBlockRowT">{r.name}</span>
                <span className="cvBlockRowD">{r.why}</span>
              </div>
              <span className="svRevealProv">{r.origin} · {r.lastTouch}</span>
            </div>
          ))}
        </React.Fragment>
      )}
      {b >= 3 && (
        <React.Fragment>
          <div className="svRevealActs">
            {d.acts.map((a) => (
              <button key={a.id} type="button" className={a.primary ? "cvBtnPrimary" : "cvBtnQuiet"}
                onClick={() => onAct(a.id)} disabled={acted === a.id}>{a.label}</button>
            ))}
          </div>
          <div className="svRevealWall">{d.wall}</div>
        </React.Fragment>
      )}
    </BlockShell>
  );
}

Object.assign(window, { BlockShell, BriefBlock, TableBlock, ShortlistBlock, EntityCardBlock, JourneyBlock, RevealBlock });
