// Mission 001 v2 — panels: masthead, telemetry strip, route card, candidates, feed, scrubber, share card
const { useState: useSt, useEffect: useEff } = React;

function useClock() {
  // Real elapsed time since mission declaration (MD.t0). Not a simulation.
  const [now, setNow] = useSt(Date.now());
  useEff(() => { const id = setInterval(() => setNow(Date.now()), 1000); return () => clearInterval(id); }, []);
  const s = Math.max(0, Math.floor((now - MD.t0) / 1000));
  const p = (n) => String(n).padStart(2, "0");
  return `T+${p(Math.floor(s / 86400))}:${p(Math.floor(s / 3600) % 24)}:${p(Math.floor(s / 60) % 60)}:${p(s % 60)}`;
}

const Masthead = ({ st, onShare }) => {
  const clock = useClock();
  return (
    <header className="mh" data-comment-anchor="masthead">
      <div className="mh-row">
        <div className="mh-kicker">
          <span className={"mh-livedot" + (st.complete ? " ok" : "")}></span>
          {MD.brand} · {MD.mission} · <span className="mh-clock">{clock}</span>
        </div>
        <button className="mh-share" onClick={onShare}>SHARE CARD</button>
      </div>
      <h1 className="mh-title">“{MD.objective}”</h1>
      <p className="mh-explainer">{MD.explainer}</p>
    </header>
  );
};

const StatusStrip = ({ st }) => {
  const dest = st.dest ? MD.DEST_NAMES[st.dest] : null;
  return (
    <div className="strip" data-comment-anchor="status-band">
      <div className="strip-cell">
        <div className="strip-label">STAGE · DAY {String(st.day).padStart(2, "0")}</div>
        <div className="strip-val">{st.stageLabel}</div>
        <div className="strip-sub">{st.statusLine.toLowerCase()}</div>
      </div>
      <div className="strip-cell">
        <div className="strip-label">BEST DESTINATION</div>
        <div className="strip-val">{dest ? dest.short.toUpperCase() : "UNDER EVALUATION"}</div>
        <div className="strip-sub">{dest ? dest.full : (st.destNote || "scanning for candidates")}</div>
      </div>
      <div className="strip-cell">
        <div className="strip-label">ROUTE CONFIDENCE</div>
        <div className={"strip-val num" + (st.complete ? " ok" : "")}>
          {st.conf == null ? "——" : st.conf + "%"}
          {st.confDelta != null && st.confDelta !== 0 && (
            <em className={st.confDelta > 0 ? "up" : "down"}>{st.confDelta > 0 ? "▲ +" : "▼ "}{st.confDelta}</em>
          )}
        </div>
        <div className="strip-sub">
          {st.hops == null ? "no route yet" : st.complete ? "route closed — target reached" :
            st.hopsPrev ? <span><s>{st.hopsPrev}</s> → {st.hops} steps in best route</span> : `${st.hops} steps in best route`}
        </div>
      </div>
      <div className="strip-cell wide">
        <div className="strip-label">LAST UPDATE</div>
        <div className="strip-update"><b>{st.lastUpdate.t}</b> {st.lastUpdate.txt}</div>
      </div>
    </div>
  );
};

const RouteCard = ({ st }) => {
  const dest = st.dest ? MD.DEST_NAMES[st.dest] : null;
  return (
    <section className="rp" data-comment-anchor="route-panel">
      <div className="panel-head">CURRENT BEST ROUTE</div>
      {dest ? (
        <div>
          <div className="rp-dest">{dest.full}</div>
          <div className={"rp-prob" + (st.complete ? " ok" : "")}>
            {st.conf}<span>%</span>
            {st.confDelta != null && st.confDelta !== 0 && (
              <em className={st.confDelta > 0 ? "up" : "down"}>{st.confDelta > 0 ? "▲ +" : "▼ "}{st.confDelta} today</em>
            )}
          </div>
          <div className="rp-steps">
            {st.route.steps.map((s, i) => (
              <div key={i} className={"rp-step " + s.state}>
                <span className="rp-n">{String(i + 1).padStart(2, "0")}</span>
                <i></i>
                <div><b>{s.txt}</b><span>{s.sub}</span></div>
              </div>
            ))}
          </div>
        </div>
      ) : (
        <div className="rp-empty">
          NO ROUTE SELECTED<span>{st.key === "declared" ? "the agent is scoring destinations from public sources — it has no view of anyone's network" : "candidates found — ranking routes by expected value"}</span>
        </div>
      )}
    </section>
  );
};

const Candidates = ({ st }) => (
  <section className="cd" data-comment-anchor="candidates">
    <div className="panel-head">CANDIDATE DESTINATIONS</div>
    {st.candidates.length === 0 ? (
      <div className="cd-empty">SCANNING<span>first discovery sprint in progress — candidates appear here when scored</span></div>
    ) : (
      <div className="cd-list">
        {st.candidates.map((c, i) => (
          <div key={c.id} className={"cd-row " + c.state.toLowerCase()}>
            <span className="cd-rank">{String(i + 1).padStart(2, "0")}</span>
            <span className="cd-name">{c.short}</span>
            <span className="cd-state">{c.state}</span>
            <span className="cd-bar"><i style={{ width: c.prob + "%" }}></i></span>
            <span className="cd-prob">{c.prob}%</span>
          </div>
        ))}
      </div>
    )}
  </section>
);

const Feed = ({ st, limit = 4 }) => (
  <section className="fd" data-comment-anchor="feed">
    <div className="panel-head">RECENT DISCOVERIES</div>
    <div className="fd-list">
      {st.log.slice(0, limit).map((l, i) => (
        <div key={i} className="fd-row">
          <b>{l.t}</b>
          <p>{l.txt} {l.delta && <em className={l.delta.startsWith("−") ? "down" : "up"}>{l.delta}</em>}</p>
        </div>
      ))}
    </div>
    {st.deadEnds.length > 0 && (
      <div className="fd-dead">
        <div className="panel-head warn">DEAD ENDS</div>
        {st.deadEnds.map((d, i) => (
          <div key={i} className="fd-dead-row"><i>✕</i><s>{d.txt}</s></div>
        ))}
      </div>
    )}
  </section>
);

const NextAction = ({ st }) => (
  <section className={"na" + (st.complete ? " ok" : "")} data-comment-anchor="next-action">
    <div className="panel-head">{st.complete ? "OUTCOME" : "NEXT ACTION"}</div>
    <p>{st.nextAction}</p>
  </section>
);

const Scrubber = ({ stage, setStage }) => {
  useEff(() => {
    const onKey = (e) => {
      if (e.key === "ArrowRight") setStage(Math.min(stage + 1, MD.STAGES.length - 1));
      if (e.key === "ArrowLeft") setStage(Math.max(stage - 1, 0));
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [stage, setStage]);
  return (
    <nav className="sc" aria-label="Mission timeline" data-comment-anchor="scrubber">
      <div className="sc-label">MISSION TIMELINE</div>
      <div className="sc-track">
        <div className="sc-line"><i style={{ width: (stage / (MD.STAGES.length - 1)) * 100 + "%" }}></i></div>
        {MD.STAGES.map((s, i) => (
          <button key={s.key} className={"sc-stop" + (i === stage ? " on" : "") + (i < stage ? " past" : "")}
            onClick={() => setStage(i)} aria-label={`${s.tick} ${s.tickLabel}`}>
            <i></i>
            <b>{s.tick}</b>
            <span>{s.tickLabel}</span>
          </button>
        ))}
      </div>
      <div className="sc-hint">◂ ▸ REPLAY</div>
    </nav>
  );
};

// 1200×630 social share card, scaled to fit the viewport
const ShareCard = ({ st, stage, onClose }) => {
  const [scale, setScale] = useSt(1);
  useEff(() => {
    const fit = () => setScale(Math.min((window.innerWidth - 64) / 1200, (window.innerHeight - 140) / 630, 1));
    fit();
    window.addEventListener("resize", fit);
    return () => window.removeEventListener("resize", fit);
  }, []);
  const dest = st.dest ? MD.DEST_NAMES[st.dest] : null;
  return (
    <div className="shc-overlay" onClick={onClose}>
      <div className="shc-hint">screenshot this card · click anywhere to close</div>
      <div className="shc-sizer" style={{ width: 1200 * scale + "px", height: 630 * scale + "px" }}>
        <div className="shc-card" style={{ transform: `scale(${scale})` }} onClick={(e) => e.stopPropagation()}>
        <div className="shc-graph"><NetGraph stage={stage} density="dense" mini /></div>
        <div className="shc-content">
          <div className="shc-kicker">
            <span className={"mh-livedot" + (st.complete ? " ok" : "")}></span>
            {MD.brand} · {MD.mission} · DAY {String(st.day).padStart(2, "0")}
          </div>
          <div className="shc-title">“{MD.objective}”</div>
          <div className="shc-stats">
            <div>
              <b>STAGE</b>
              <span>{st.stageLabel}</span>
            </div>
            <div>
              <b>BEST DESTINATION</b>
              <span>{dest ? dest.short.toUpperCase() : "UNDER EVALUATION"}</span>
            </div>
            <div>
              <b>ROUTE CONFIDENCE</b>
              <span className={st.complete ? "ok" : "blue"}>{st.conf == null ? "——" : st.conf + "%"}</span>
            </div>
          </div>
          <div className="shc-foot">{st.statusLine.toUpperCase()} — PUBLIC EXPERIMENT · EVERY NUMBER REGISTERED BEFORE ACTING</div>
        </div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { Masthead, StatusStrip, RouteCard, Candidates, Feed, NextAction, Scrubber, ShareCard, useClock });
