/* =========================================================
   chrome.jsx, masthead, trail spine, ledger drawer.
   Also: buildLedger() shared by the drawer and the receipt.
   ========================================================= */

/* ---------- derive ledger entries from marks ---------- */
function wpById(id) { return window.JOURNEY.waypoints.find((w) => w.id === id); }

function buildLedger(marks) {
  const J = window.JOURNEY;
  const groups = [];
  for (let i = 0; i < J.waypoints.length; i++) {
    const w = J.waypoints[i];
    const m = marks[w.id] || {};
    const entries = [];

    if (w.id === "listening") {
      Object.entries(m.signals || {}).forEach(([idx, tags]) => {
        if (tags && tags.length) {
          const s = w.signals[idx];
          entries.push({ k: tags.join(" · "), v: s.t, serif: false });
        }
      });
      if ((m.note || "").trim()) entries.push({ k: "What we hear", v: m.note, serif: true });
    }
    if (w.id === "framing") {
      if (m.frame != null) entries.push({ k: "Framing chosen", v: w.frames[m.frame].t });
      if ((m.note || "").trim()) entries.push({ k: "The challenge", v: m.note, serif: true });
    }
    if (w.id === "envisioning") {
      (m.signals || []).forEach((idx) => entries.push({ k: "Signal of arrival", v: w.arrivalSignals[idx].t }));
      if ((m.note || "").trim()) entries.push({ k: "Success looks like", v: m.note, serif: true });
    }
    if (w.id === "assumptions") {
      if (m.riskiest != null) entries.push({ k: "Riskiest belief", v: w.assumptions[m.riskiest].t });
      if ((m.note || "").trim()) entries.push({ k: "What would disconfirm it", v: m.note, serif: true });
    }
    if (w.id === "transformation") {
      Object.entries(m.scales || {}).forEach(([idx, val]) => {
        const s = w.scales[idx];
        const gap = Math.abs((val.tomorrow ?? s.tomorrow) - (val.today ?? s.today));
        entries.push({ k: s.name, v: `${val.today ?? s.today} → ${val.tomorrow ?? s.tomorrow}  ·  ${gap} to cross` });
      });
      if (!Object.keys(m.scales || {}).length && m.touched) {
        w.scales.forEach((s) => entries.push({ k: s.name, v: `${s.today} → ${s.tomorrow}` }));
      }
      if ((m.note || "").trim()) entries.push({ k: "The gap that matters most", v: m.note, serif: true });
    }
    if (w.id === "crux") {
      if (m.crux != null) entries.push({ k: "The crux", v: w.cruxes[m.crux].t });
      if ((m.note || "").trim()) entries.push({ k: "In our words", v: m.note, serif: true });
    }
    if (w.id === "integration") {
      if ((m.note || "").trim()) entries.push({ k: "What now feels obvious", v: m.note, serif: true });
    }

    if (entries.length) groups.push({ num: w.num, name: w.title, key: w.key, entries });
  }
  return groups;
}

/* ---------- MASTHEAD ---------- */
function Masthead() {
  const J = window.JOURNEY;
  const s = window.useJourney();
  return (
    <header className="masthead">
      <div className="masthead__brand">
        <button
          className="wordmark"
          style={{ background: "none", border: 0, cursor: "pointer", padding: 0 }}
          onClick={() => s.goTo("home")}
          aria-label="Return to trailhead"
        >
          DARK HORSE WORKS
        </button>
        <span className="masthead__sep" />
        <span className="masthead__session">{J.subject} · sense-making walk</span>
      </div>
      <div className="masthead__tools">
        <button
          className="chrome-btn"
          onClick={() => s.setLedgerOpen(true)}
          aria-label="Open field ledger"
        >
          <Icon name="ledger" size={15} />
          Ledger
          <span className={`count ${s.totalMarks ? "is-signal" : ""}`}>{s.totalMarks}</span>
        </button>
        <button
          className="chrome-btn chrome-btn--icon"
          onClick={() => s.setTheme(s.theme === "dark" ? "light" : "dark")}
          aria-label="Toggle light and dark"
          title="Toggle light / dark"
        >
          <Icon name={s.theme === "dark" ? "sun" : "moon"} size={15} />
        </button>
      </div>
    </header>
  );
}

/* ---------- TRAIL SPINE ---------- */
function TrailSpine() {
  const s = window.useJourney();
  const { WPS, view, maxReached } = s;
  const nodeRefs = React.useRef([]);
  const trailRef = React.useRef(null);
  const [walkedH, setWalkedH] = React.useState(0);

  const measure = React.useCallback(() => {
    const idx = typeof view === "number" ? view : -1;
    if (idx < 0) { setWalkedH(0); return; }
    const node = nodeRefs.current[idx];
    const trail = trailRef.current;
    if (node && trail) {
      const nr = node.getBoundingClientRect();
      const tr = trail.getBoundingClientRect();
      setWalkedH(nr.top - tr.top + nr.height / 2);
    }
  }, [view]);

  React.useLayoutEffect(() => { measure(); }, [measure, maxReached]);
  React.useEffect(() => {
    window.addEventListener("resize", measure);
    return () => window.removeEventListener("resize", measure);
  }, [measure]);

  return (
    <nav className="spine" aria-label="The trail">
      <div className="spine__head">
        <div className="spine__title">The Trail</div>
        <div className="spine__progress">
          {typeof view === "number" ? `Waypoint ${WPS[view].num} of 07` : "At the trailhead"}
        </div>
      </div>

      <div className="trail" ref={trailRef}>
        <div className="trail__line" />
        <div className="trail__line--walked" style={{ height: walkedH }} />
        {WPS.map((w, i) => {
          const done = s.stageComplete(w.id);
          const current = view === i;
          const locked = false; // free navigation, jump anywhere on the trail
          const cnt = s.stageMarkCount(w.id);
          return (
            <button
              key={w.id}
              ref={(el) => { /* row */ }}
              className={`waypoint ${current ? "is-current" : ""} ${done ? "is-done" : ""} ${locked ? "is-locked" : ""}`}
              onClick={() => s.goTo(i)}
              aria-current={current ? "step" : undefined}
            >
              <span className="node" ref={(el) => (nodeRefs.current[i] = el)} />
              <span className="waypoint__body">
                <span className="waypoint__num">{w.num} · {w.coord.split(" · ")[1] || ""}</span>
                <span className="waypoint__name">{w.title}</span>
                <span className="waypoint__key">{w.key}</span>
                {cnt > 0 && <span className="waypoint__marks">{cnt} {cnt === 1 ? "mark" : "marks"} left here</span>}
              </span>
            </button>
          );
        })}
      </div>

      <div className="spine__foot">
        <div className="spine__spineline">{window.JOURNEY.spine}</div>
        <div className="legal">
          <div className="legal__label">Confidential</div>
          <p className="legal__body">© 2026 Dark Horse Works. All rights reserved. This material and the ideas, frameworks, and methods within it are the confidential and proprietary intellectual property of Dark Horse Works. No part may be reproduced, distributed, or used without written permission.</p>
        </div>
      </div>
    </nav>
  );
}

/* ---------- LEDGER DRAWER ---------- */
function LedgerDrawer() {
  const s = window.useJourney();
  const groups = buildLedger(s.marks);
  return (
    <>
      <div className={`ledger-scrim ${s.ledgerOpen ? "open" : ""}`} onClick={() => s.setLedgerOpen(false)} />
      <aside className={`ledger ${s.ledgerOpen ? "open" : ""}`} aria-hidden={!s.ledgerOpen}>
        <div className="ledger__head">
          <div className="ledger__title">
            <h3>Field Ledger</h3>
            <span className="sub">{s.totalMarks} {s.totalMarks === 1 ? "mark" : "marks"} · accumulating</span>
          </div>
          <button className="chrome-btn chrome-btn--icon" onClick={() => s.setLedgerOpen(false)} aria-label="Close ledger">
            <Icon name="x" size={15} />
          </button>
        </div>
        <div className="ledger__body">
          {groups.length === 0 && (
            <p className="ledger__empty">
              Nothing gathered yet. As you move through the trail, every mark you leave is collected here, so you can always see where you have been.
            </p>
          )}
          {groups.map((g) => (
            <div className="ledger-group" key={g.num}>
              <div className="ledger-group__head">
                <span className="ledger-group__num">{g.num}</span>
                <span className="ledger-group__name">{g.name}</span>
              </div>
              {g.entries.map((e, i) => (
                <div className="ledger-entry" key={i}>
                  <span className="ledger-entry__k"><span className="dot">▪</span> {e.k}</span>
                  <span className={`ledger-entry__v ${e.serif ? "serif" : ""}`}>{e.v}</span>
                </div>
              ))}
            </div>
          ))}
        </div>
      </aside>
    </>
  );
}

Object.assign(window, { buildLedger, Masthead, TrailSpine, LedgerDrawer, wpById });
