// SRI — company profile. Opens from any business card in the Stimulus network.
// Every value states where it came from and who may see it; absences are stated, not hidden.
const KChip = (props) => { const C = (window.StimulusDesignSystem_bb8fa3 || {}).ConsentChip; return C ? React.createElement(C, props) : null; };

function CpTabs({ tabs, cur, onPick }) {
  return (
    <div className="cpTabs" role="tablist">
      {tabs.map((t) => (
        <button key={t.k} type="button" role="tab" aria-selected={cur === t.k}
          className={"cpTab" + (cur === t.k ? " isOn" : "")} onClick={() => onPick(t.k)}>
          {t.l}{t.n ? <span className="cpTabN tabular">{t.n}</span> : null}
        </button>
      ))}
    </div>
  );
}

const CP_GTYPE = { you: "var(--green-9)", client: "#0C447C", partner: "#1D9E75", vendor: "#854F0B", locked: "var(--muted-foreground)" };
const CP_GLEGEND = [["you", "Your org"], ["client", "Its clients"], ["partner", "Partners & co-bids"], ["vendor", "Its own suppliers"], ["locked", "Not shared with you"]];

const CP_MON = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
const cpMi = (d) => { const [y, m] = d.split("-").map(Number); return y * 12 + (m - 1); };
const cpFmt = (d) => { const [y, m] = d.split("-").map(Number); return CP_MON[m - 1] + " " + y; };

function CpGraph({ g }) {
  const [act, setAct] = React.useState(null);
  const [pin, setPin] = React.useState(null);
  const [mode, setMode] = React.useState("network");
  const [allLabels, setAllLabels] = React.useState(true);
  const [zoom, setZoom] = React.useState(1);
  const [pan, setPan] = React.useState({ x: 0, y: 0 });
  const dragRef = React.useRef(null);
  const svgRef = React.useRef(null);
  const onPanDown = (e) => {
    if (e.button !== 0) return;
    const r = svgRef.current.getBoundingClientRect();
    dragRef.current = { px: e.clientX, py: e.clientY, ox: pan.x, oy: pan.y, sx: (640 / zoom) / r.width, sy: (400 / zoom) / r.height };
    svgRef.current.setPointerCapture(e.pointerId);
  };
  const onPanMove = (e) => {
    const d = dragRef.current;
    if (!d) return;
    const nx = d.ox - (e.clientX - d.px) * d.sx;
    const ny = d.oy - (e.clientY - d.py) * d.sy;
    const lim = 320 - 320 / zoom + 60;
    setPan({ x: Math.max(-lim, Math.min(lim, nx)), y: Math.max(-lim, Math.min(lim, ny)) });
  };
  const onPanUp = () => { dragRef.current = null; };
  const resetView = () => { setZoom(1); setPan({ x: 0, y: 0 }); };
  React.useEffect(() => {
    const el = svgRef.current;
    if (!el || mode !== "network") return;
    const onWheel = (e) => {
      e.preventDefault();
      setZoom((z) => Math.min(2.4, Math.max(0.6, +(z - e.deltaY * 0.0015).toFixed(3))));
    };
    el.addEventListener("wheel", onWheel, { passive: false });
    return () => el.removeEventListener("wheel", onWheel);
  }, [mode, full]);
  const [full, setFull] = React.useState(false);
  React.useEffect(() => {
    if (!full) return;
    const esc = (e) => { if (e.key === "Escape") setFull(false); };
    window.addEventListener("keydown", esc);
    return () => window.removeEventListener("keydown", esc);
  }, [full]);
  const scrollRef = React.useRef(null);
  const nudge = (dir) => { const el = scrollRef.current; if (el) el.scrollBy({ left: dir * Math.max(el.clientWidth * 0.6, 160), behavior: "smooth" }); };
  const [hide, setHide] = React.useState({});
  const byId = {};
  g.nodes.forEach((n) => { byId[n.id] = n; });
  const sel = pin || act;
  const cur = sel ? byId[sel] : null;
  const on = (n) => !hide[n.type];
  const toggleType = (t) => setHide(Object.assign({}, hide, { [t]: !hide[t] }));
  const nodeProps = (n) => ({
    onMouseEnter: () => setAct(n.id), onMouseLeave: () => setAct(null),
    onFocus: () => setAct(n.id), onBlur: () => setAct(null),
    onClick: () => setPin(pin === n.id ? null : n.id), tabIndex: 0,
  });

  // timeline domain
  const dated = g.nodes.filter((n) => n.start);
  const now = "2026-09";
  const min = Math.min.apply(null, dated.map((n) => cpMi(n.start)));
  const max = cpMi(now) + 2;
  const span = Math.max(max - min, 12);
  const pos = (d) => ((cpMi(d) - min) / span) * 100;
  const years = [];
  for (let y = Math.floor(min / 12); y <= Math.floor(max / 12); y++) {
    const p = ((y * 12 - min) / span) * 100;
    if (p >= -9 && p <= 100) years.push([y, Math.max(p, 0)]);
  }
  const rows = dated.slice().sort((a, b) => cpMi(a.start) - cpMi(b.start));

  return (
    <div className={"cpGraphWrap" + (full ? " isFull" : "")}>
      {full && <div className="cpFullHead"><span className="cpFullTitle">{g.center.label} — {mode === "network" ? "network" : "chronological"}</span>
        <button type="button" className="cpGhostBtn" onClick={() => setFull(false)}><Icon name="minimize" size={12} /> Collapse</button></div>}
      <div className="cpGraphMain">
        <div className="cpGraphBar">
          <div className="cpSeg">
            <button type="button" className={"cpSegBtn" + (mode === "network" ? " isOn" : "")} onClick={() => setMode("network")}>
              <Icon name="share" size={12} /> Network</button>
            <button type="button" className={"cpSegBtn" + (mode === "time" ? " isOn" : "")} onClick={() => setMode("time")}>
              <Icon name="history" size={12} /> Chronological</button>
          </div>
          {mode === "network" && (
            <React.Fragment>
              <button type="button" className={"cpGhostBtn" + (allLabels ? " isOn" : "")} onClick={() => setAllLabels(!allLabels)}>
                {allLabels ? "Hide edge labels" : "Show all edge labels"}
              </button>
              <div className="cpZoom">
                <button type="button" className="cpZoomBtn" onClick={() => setZoom((z) => Math.max(0.6, +(z - 0.2).toFixed(2)))} aria-label="Zoom out" disabled={zoom <= 0.6}>−</button>
                <span className="cpZoomN tabular">{(Math.round(zoom * 10) / 10).toString().replace(/\.0$/, "") + "×"}</span>
                <button type="button" className="cpZoomBtn" onClick={() => setZoom((z) => Math.min(2.4, +(z + 0.2).toFixed(2)))} aria-label="Zoom in" disabled={zoom >= 2.4}>+</button>
                {(zoom !== 1 || pan.x !== 0 || pan.y !== 0) ? <button type="button" className="cpZoomReset" onClick={resetView}>Reset</button> : null}
              </div>
              {zoom > 1 && <span className="cpZoomHintTxt">Drag to pan · scroll to zoom</span>}
            </React.Fragment>
          )}
          {mode === "time" && (
            <div className="cpZoom">
              <button type="button" className="cpZoomBtn" onClick={() => nudge(-1)} aria-label="Scroll earlier"><Icon name="chevL" size={12} /></button>
              <span className="cpZoomHint">{years.length} years</span>
              <button type="button" className="cpZoomBtn" onClick={() => nudge(1)} aria-label="Scroll later"><Icon name="chevR" size={12} /></button>
            </div>
          )}
          {pin && <button type="button" className="cpGhostBtn" onClick={() => setPin(null)}>Clear selection</button>}
          <button type="button" className="cpGhostBtn cpFullBtn" onClick={() => setFull(!full)}>
            <Icon name={full ? "minimize" : "maximize"} size={12} /> {full ? "Collapse" : "Full screen"}
          </button>
        </div>

        {mode === "network" ? (
          <div className="cpGraphCanvas">
            <svg ref={svgRef} viewBox={[320 - 320 / zoom + pan.x, 196 - 200 / zoom + pan.y, 640 / zoom, 400 / zoom].join(" ")}
              className={"cpGraphSvg" + (zoom > 1 ? " isPannable" : "")} role="img" aria-label={"Relationship graph for " + g.center.label}
              onPointerDown={onPanDown} onPointerMove={onPanMove} onPointerUp={onPanUp} onPointerCancel={onPanUp}>
              {g.edges.map(([id, w]) => {
                const n = byId[id];
                if (!n || !on(n)) return null;
                const lit = !sel || sel === id;
                return <line key={id} x1="320" y1="196" x2={n.x} y2={n.y}
                  stroke={n.dashed ? "var(--muted-foreground)" : CP_GTYPE[n.type]}
                  strokeWidth={0.8 + w * 3.4} strokeDasharray={n.dashed ? "4 4" : null}
                  opacity={lit ? 0.32 + w * 0.4 : 0.08} />;
              })}
              {g.edges.map(([id, w]) => {
                const n = byId[id];
                if (!n || !on(n) || !n.edge) return null;
                const show = allLabels || sel === id;
                if (!show) return null;
                const mx = 320 + (n.x - 320) * 0.56, my = 196 + (n.y - 196) * 0.56;
                const wpx = n.edge.length * 5.3 + 14;
                return (
                  <g key={"l" + id} opacity={sel && sel !== id ? 0.35 : 1} pointerEvents="none">
                    <rect x={mx - wpx / 2} y={my - 9} width={wpx} height={18} rx="9"
                      fill="var(--card)" stroke="var(--border)" strokeWidth="1" />
                    <text x={mx} y={my + 4} textAnchor="middle" className="cpGEdgeT">{n.edge}</text>
                  </g>
                );
              })}
              <g>
                <circle cx="320" cy="196" r="36" fill="var(--foreground)" />
                <text x="320" y="201" textAnchor="middle" className="cpGCenterT">{g.center.init || g.center.label.slice(0, 2).toUpperCase()}</text>
              </g>
              {g.nodes.map((n) => {
                if (!on(n)) return null;
                const lit = !sel || sel === n.id;
                return (
                  <g key={n.id} className="cpGNode" {...nodeProps(n)}>
                    <circle cx={n.x} cy={n.y} r={n.r + 10} fill="transparent" />
                    <circle cx={n.x} cy={n.y} r={n.r} fill={n.type === "locked" ? "var(--muted)" : CP_GTYPE[n.type]}
                      stroke={sel === n.id ? "var(--foreground)" : "var(--card)"} strokeWidth={sel === n.id ? 2.5 : 2}
                      strokeDasharray={n.dashed ? "3 3" : null} opacity={lit ? 1 : 0.35} />
                    {n.type === "locked" && <circle cx={n.x} cy={n.y} r={n.r} fill="none" stroke="var(--muted-foreground)" strokeWidth="1.5" strokeDasharray="3 3" opacity={lit ? 1 : 0.35} />}
                    <text x={n.x} y={n.y + 4} textAnchor="middle" className="cpGInit"
                      style={{ fontSize: ((n.init || "").length > 3 ? 8.5 : (n.r >= 20 ? 10.5 : 9.5)) + "px" }}
                      fill={n.type === "locked" ? "var(--muted-foreground)" : "oklch(0.99 0.01 155)"} opacity={lit ? 1 : 0.4}>{n.init}</text>
                    <text x={n.x} y={n.y + n.r + 13} textAnchor="middle" className="cpGLabel"
                      fill={lit ? "var(--foreground)" : "var(--muted-foreground)"} opacity={lit ? 1 : 0.5}>{n.label}</text>
                  </g>
                );
              })}
            </svg>
          </div>
        ) : (
          <div className="cpTl">
            <div className="cpTlFrame" ref={scrollRef}>
              <div className="cpTlNames">
                <div className="cpTlNameHead"></div>
                {rows.map((n) => {
                  if (!on(n)) return null;
                  const lit = !sel || sel === n.id;
                  return (
                    <div key={n.id} className={"cpTlNameCell" + (sel === n.id ? " isSel" : "")} title={n.label} {...nodeProps(n)}>
                      <span style={{ opacity: lit ? 1 : 0.4, display: "flex", alignItems: "center", gap: 7, minWidth: 0 }}>
                        <span className="cpGDot" style={{ background: CP_GTYPE[n.type], borderStyle: n.type === "locked" ? "dashed" : "solid" }}></span>
                        <span className="cpTlName">{n.label}</span>
                      </span>
                    </div>
                  );
                })}
              </div>
              <div className="cpTlScroll">
                <div className="cpTlInner" style={{ minWidth: Math.max(years.length * 150, 420) + "px" }}>
                  <div className="cpTlAxisTrack">
                    {years.map(([y, p]) => (
                      <span key={y} className="cpTlYear" style={{ left: p + "%" }}><span className="cpTlTick"></span><span className="cpTlYearT tabular">{y}</span></span>
                    ))}
                  </div>
                  {rows.map((n) => {
                    if (!on(n)) return null;
                    const lit = !sel || sel === n.id;
                    const left = pos(n.start);
                    const right = pos(n.end || now);
                    const place = right < 66 ? "after" : (left > 30 ? "before" : "inside");
                    const when = n.unknown ? "dates not shared"
                      : (n.end ? cpFmt(n.start) + " – " + cpFmt(n.end) : cpFmt(n.start) + " → now");
                    return (
                      <div key={n.id} className={"cpTlTrack" + (sel === n.id ? " isSel" : "") + (n.unknown || n.dashed ? " isLight" : "")} {...nodeProps(n)}>
                        <div className={"cpTlBar" + (n.unknown ? " isUnknown" : "")}
                          style={{ left: left + "%", width: Math.max(right - left, 1.6) + "%",
                            background: n.unknown ? "var(--muted)" : CP_GTYPE[n.type], opacity: lit ? (n.dashed ? 0.45 : 1) : 0.3 }}></div>
                        <span className={"cpTlBarLbl is-" + place}
                          style={Object.assign({ opacity: lit ? 1 : 0.4 },
                            place === "after" ? { left: right + "%" }
                              : place === "before" ? { right: (100 - left) + "%" }
                                : { left: left + "%", width: (right - left) + "%" })}>
                          {n.unknown ? "Held from you" : n.edge}
                        </span>
                        <span className={"cpTlWhen tabular" + (left > 62 ? " isRight" : "")}
                          style={Object.assign({ opacity: lit ? 1 : 0.4 }, left > 62 ? { right: 0 } : { left: left + "%" })}>{when}</span>
                      </div>
                    );
                  })}
                </div>
              </div>
            </div>
            <div className="cpTlFoot">Bars run from the first event in the record to the last. Open-ended bars are still live as of September 2026. Scroll sideways for earlier years.</div>
          </div>
        )}
      </div>

      <div className="cpGraphSide">
        {cur ? (
          <React.Fragment>
            <div className="cpGSideType" style={{ color: CP_GTYPE[cur.type] }}>{cur.rel}</div>
            <div className="cpGSideName">{cur.label}</div>
            {cur.start && (
              <div className="cpGSideWhen tabular">{cpFmt(cur.start)} → {cur.unknown ? "not shared" : (cur.end ? cpFmt(cur.end) : "now")}</div>
            )}
            <div className="cpGSideNote">{cur.note}</div>
            {pin === cur.id && <div className="cpGSidePin">Pinned. Click the node again to release.</div>}
          </React.Fragment>
        ) : (
          <React.Fragment>
            <div className="cpGSideType">What this says</div>
            <div className="cpGSideNote">{g.read}</div>
            <div className="cpGSideNote">Hover any {mode === "network" ? "node" : "bar"} for the relationship; click to pin it.</div>
          </React.Fragment>
        )}
        <div className="cpGLegend">
          {CP_GLEGEND.map(([t, l]) => (
            <button key={t} type="button" className={"cpGLegendRow" + (hide[t] ? " isOff" : "")} onClick={() => toggleType(t)}>
              <span className="cpGDot" style={{ background: CP_GTYPE[t], borderStyle: t === "locked" ? "dashed" : "solid" }}></span>{l}
            </button>
          ))}
          <div className="cpGLegendHint">Click a kind to hide it.</div>
        </div>
      </div>
    </div>
  );
}

function CpFact({ f }) {
  if (f.locked) return (
    <div className="cpFact isLocked">
      <div className="cpFactV cpFactLock"><Icon name="lock" size={13} /><span>A fact exists here — not shared with you.</span></div>
      <div className="cpFactD"><span>{f.k}</span><KChip level="org" size="inline" /><span className="cpFactNote">{f.reason}</span></div>
    </div>
  );
  if (f.v == null) return (
    <div className="cpFact isEmpty">
      <div className="cpFactV cpFactAbsent">{f.empty || "Not in the record yet."}</div>
      <div className="cpFactD"><span>{f.k}</span></div>
    </div>
  );
  return (
    <div className="cpFact">
      <div className="cpFactV">{f.v}</div>
      <div className="cpFactD">
        <span>{f.k}</span>
        <KChip level={f.consent} size="inline" grantedBy={f.grantedBy} />
        <span className="cpFactSrc">{f.src} · {f.asOf}</span>
        {f.conf != null && <span className="mono cpFactConf">conf {f.conf.toFixed(2)}</span>}
      </div>
      {f.sub && <div className="cpFactSub">{f.sub}</div>}
    </div>
  );
}

function CpRating({ r }) {
  if (!r) return null;
  const max = Math.max.apply(null, r.bars.map((b) => b[1]));
  return (
    <div className="cpCard cpRating">
      <div className="cpRatingLeft">
        <div className="cpRatingN tabular">{r.score}</div>
        <div className="cpStars" aria-hidden="true">
          {[0, 1, 2, 3, 4].map((i) => <Icon key={i} name="star" size={12} />)}
        </div>
        <div className="cpRatingC">{r.count} Google reviews</div>
      </div>
      <div className="cpBars">
        {r.bars.map((b) => (
          <div key={b[0]} className="cpBarRow">
            <span className="cpBarK tabular">{b[0]}</span>
            <span className="cpBarTrack"><span className="cpBarFill" style={{ width: Math.round((b[1] / max) * 100) + "%" }}></span></span>
            <span className="cpBarN tabular">{b[1]}</span>
          </div>
        ))}
      </div>
      <div className="cpRatingSide">
        <div className="cpRatingTheme">{r.theme}</div>
        <div className="cpSrcLine"><KChip level="public" size="inline" /><span>{r.source} · read as of {r.asOf}</span></div>
      </div>
    </div>
  );
}

function CpFactsPanel({ c }) {
  const order = ["Identity and locations", "Scale and money", "Standing and credentials", "Reputation and activity", "Emergent signals"];
  const seen = {};
  c.allFacts.forEach((f) => { const g = f.group || "Other facts"; (seen[g] = seen[g] || []).push(f); });
  const sections = order.filter((g) => seen[g]).concat(Object.keys(seen).filter((g) => order.indexOf(g) < 0));
  const [shut, setShut] = React.useState({});
  return (
    <div className="cpCard cpFactsCard">
      <div className="cpH">Business facts
        <span className="cpCount">{c.factCount} facts{c.lockedCount ? " · " + c.lockedCount + " restricted" : ""}</span>
      </div>
      <p className="cpSubHead">Committed facts with their evidence, sharing boundary, date, and confidence. Nothing is inferred.</p>
      {sections.map((g) => (
        <div key={g} className="cpFactSec">
          <button type="button" className="cpFactSecH" onClick={() => setShut(Object.assign({}, shut, { [g]: !shut[g] }))}>
            <span className="cpFactSecT">{g}</span>
            <span className="cpFactSecN">{seen[g].length} {seen[g].length === 1 ? "fact" : "facts"}</span>
            <Icon name={shut[g] ? "chevD" : "chevR"} size={12} />
          </button>
          {!shut[g] && seen[g].map((f, i) => (
            <div key={i} className={"cpFRow" + (f.locked ? " isLocked" : "")}>
              <div className="cpFK">{f.k}</div>
              <div className="cpFConf">
                {f.conf != null ? (
                  <React.Fragment>
                    <span className="cpFConfN tabular">{Math.round(f.conf * 100)}%</span>
                    <span className="cpFConfTrack"><span className="cpFConfFill" style={{ width: Math.round(f.conf * 100) + "%" }}></span></span>
                  </React.Fragment>
                ) : <span className="cpFConfNone">No confidence recorded</span>}
              </div>
              {f.locked
                ? <div className="cpFV cpFactLock"><Icon name="lock" size={13} /> Not shared with you</div>
                : <div className="cpFV">{f.v}</div>}
              <div className="cpFSrcRow">
                <span className="cpFSrc">{f.locked ? f.reason : f.src}</span>
                <KChip level={f.consent} grantedBy={f.grantedBy} />
              </div>
              <div className="cpFDate">{f.asOf === "—" ? "No date in the record" : "Updated " + f.asOf}</div>
            </div>
          ))}
        </div>
      ))}
    </div>
  );
}

function CompanyProfile({ id, card, onBack, onAsk, backLabel }) {
  const c = (window.SRICompanies && window.SRICompanies.get(id, card)) || null;
  const [tab, setTab] = React.useState("overview");
  const [added, setAdded] = React.useState(false);
  React.useEffect(() => { setTab("overview"); setAdded(false); }, [id]);
  if (!c) return null;
  const rel = c.relationship;
  const tabs = [
    { k: "overview", l: "Overview" },
    { k: "journey", l: "Journey & network" },
    { k: "facts", l: "Facts & provenance", n: c.factCount },
    { k: "financials", l: "Financials" },
    { k: "people", l: "People", n: c.people.length || null },
    { k: "news", l: "News", n: c.news.length || null },
  ];

  return (
    <div className="cpRoot">
      <button type="button" className="cpBack" onClick={onBack}>
        <Icon name="chevL" size={12} /> {backLabel || "Stimulus network"}
      </button>

      <div className="cpHead">
        <div className={"cpLogo" + (c.inNetwork ? "" : " isExt")}>{c.logo}</div>
        <div className="cpHeadMain">
          <div className="cpNameRow">
            <h1 className="cpName">{c.name}</h1>
            {c.claimed
              ? <span className="cpClaim"><Icon name="check" size={11} /> <span>{"Claimed by " + c.claimed.by + ", " + c.claimed.on}</span></span>
              : <span className="cpClaim isUnclaimed">Unclaimed profile</span>}
            {c.inNetwork
              ? <span className="cpStateChip isIn">In your network</span>
              : <span className="cpStateChip"><Icon name="globe" size={11} /> Stimulus network</span>}
          </div>
          <p className="cpShort">{c.short}</p>
          <div className="cpMetaRow">
            <span><Icon name="briefcase" size={11} />{c.category}</span>
            {c.location && <span><Icon name="building" size={11} />{c.location}</span>}
            {c.domain && <span><Icon name="globe" size={11} />{c.domain}</span>}
            {c.contact && c.contact.phone && <span><Icon name="send" size={11} />{c.contact.phone}</span>}
            {c.contact && <a className="cpMetaLink" href={"mailto:" + c.contact.email}><Icon name="mail" size={11} />{c.contact.email}</a>}
          </div>
        </div>
        <div className="cpActions">
          {c.inNetwork ? (
            <button type="button" className="cpBtn isPrimary" onClick={() => onAsk && onAsk("What changed with " + c.name + " this quarter?")}>Ask about this relationship</button>
          ) : added ? (
            <span className="cpAdded"><Icon name="check" size={12} /> Added. A record is open.</span>
          ) : (
            <button type="button" className="cpBtn isPrimary" onClick={() => setAdded(true)}>Add to your network</button>
          )}
          <button type="button" className="cpBtn">Share</button>
          <button type="button" className="cpBtn">Export</button>
        </div>
      </div>

      <div className="cpProv">
        <span>Assembled from {c.sources} {c.sources === 1 ? "source" : "sources"}</span>
        <span className="cpProvDot">·</span>
        <span>{c.factCount} facts{c.lockedCount ? ", " + c.lockedCount + " not shared with you" : ", none withheld"}</span>
        <span className="cpProvDot">·</span>
        <span>as of {c.asOf}</span>
      </div>

      <CpTabs tabs={tabs} cur={tab} onPick={setTab} />

      <div className="cpMetrics">
        {c.metrics.map((m, i) => (
          <div key={i} className="cpMetric">
            <span className="cpMetricIcon"><Icon name={m.icon} size={16} /></span>
            <div className="cpMetricBody">
              <div className="cpMetricK">{m.k}</div>
              {m.v ? (
                <div className="cpMetricV tabular">{m.v}{m.rating && <Icon name="star" size={12} />}</div>
              ) : <div className="cpMetricAbsent">{m.note}</div>}
              {m.v && <div className="cpMetricNote">{m.note}{m.consent ? <KChip level={m.consent} size="inline" grantedBy={m.grantedBy} /> : null}</div>}
            </div>
          </div>
        ))}
      </div>

      <div className="cpCols">
        <div className="cpMain">
          {tab === "overview" && (
            <React.Fragment>
              <div className="cpCard">
                <div className="cpH">Overview</div>
                <p className="cpDesc">{c.description}</p>
                {c.contact && (
                  <div className="cpContact cpContactCols">
                    <div className="cpContactCol">
                      <div className="cpH cpHSub">Contact</div>
                      <div className="cpPersonLinks">
                        {c.contact.phone
                          ? <a className="cpPersonLink" href={"tel:" + c.contact.phone.replace(/[^+\d]/g, "")}><Icon name="phone" size={12} />{c.contact.phone}</a>
                          : <span className="cpPersonNone">No phone number shared</span>}
                        <a className="cpPersonLink" href={"mailto:" + c.contact.email}><Icon name="mail" size={12} />{c.contact.email}</a>
                      </div>
                      <div className="cpContactSrc">{c.contact.src} · {c.contact.asOf}<KChip level={c.contact.consent} size="inline" /></div>
                    </div>
                    {c.domain && (
                      <div className="cpContactCol">
                        <div className="cpH cpHSub">Website</div>
                        <div className="cpPersonLinks">
                          <a className="cpPersonLink" href={"https://" + c.domain} target="_blank" rel="noreferrer"><Icon name="globe" size={12} />{c.domain}</a>
                        </div>
                        <div className="cpContactSrc">Verified by domain check<KChip level="public" size="inline" /></div>
                      </div>
                    )}
                  </div>
                )}
                {c.naics && (
                  <div className="cpContact">
                    <div className="cpH cpHSub">Industry</div>
                    <div className="cpChips">
                      <span className="cpChip">{c.naics.split(" · ")[0]} — {c.naics.split(" · ")[1] || c.naics}</span>
                    </div>
                    <div className="cpContactSrc">NAICS · Stimulus classifier<KChip level="public" size="inline" /></div>
                  </div>
                )}
              </div>

              {c.locations && c.locations.length > 0 && (function () {
                const hq = c.locations.filter((l) => l.r === "Headquarters");
                const rest = c.locations.filter((l) => l.r !== "Headquarters");
                const states = {};
                c.locations.forEach((l) => { const m = (l.addr || "").match(/,\s*([A-Z]{2})\s*\d{5}/); if (m) states[m[1]] = 1; });
                const nStates = Object.keys(states).length;
                const row = (l, isHq) => (
                  <div key={l.n} className={"cpLoc" + (isHq ? " isHq" : "")}>
                    <span className="cpLocIcon"><Icon name={l.icon || "pin"} size={15} /></span>
                    <div className="cpLocBody">
                      <div className="cpLocHead">
                        <span className="cpLocN">{l.n}</span>
                        {isHq && <span className="cpLocHq">Headquarters</span>}
                      </div>
                      {l.addr && <div className="cpLocAddr">{l.addr}</div>}
                      <div className="cpLocMeta">
                        {!isHq && <span className="cpLocType">{l.r}</span>}
                        <span className="cpLocD">{l.d}</span>
                      </div>
                      <div className="cpLocSrc"><KChip level={l.consent} size="inline" grantedBy={l.grantedBy} /><span>{l.src}</span></div>
                    </div>
                  </div>
                );
                return (
                  <div className="cpCard cpLocCard">
                    <div className="cpH">Locations
                      <span className="cpCount">{c.locations.length} locations{nStates ? " · " + nStates + " states" : ""}</span>
                    </div>
                    <p className="cpSubHead">Verified places where {c.name.split(" ")[0]} is headquartered, stores equipment, or delivers active work.</p>
                    {hq.map((l) => row(l, true))}
                    {rest.length > 0 && <div className="cpLocDiv">Other operating locations</div>}
                    {rest.map((l) => row(l, false))}
                    <div className="cpLocFoot">A map would help when geography is the task. For four locations, this list is faster to scan.</div>
                  </div>
                );
              })()}

              {(c.products.length > 0 || c.services.length > 0) && (
                <div className="cpCard">
                  <div className="cpH">Products &amp; services</div>
                  <div className="cpChips">
                    {c.products.map((p) => <span key={p} className="cpChip">{p}</span>)}
                    {c.services.map((p) => <span key={p} className="cpChip isSvc">{p}</span>)}
                  </div>
                </div>
              )}

              {c.certifications.length > 0 && (
                <div className="cpCard">
                  <div className="cpH">Certifications &amp; credentials</div>
                  <div className="cpCerts">
                    {c.certifications.map((r) => (
                      <div key={r.n} className={"cpCert" + (r.ok ? "" : " isLocked")}>
                        <span className="cpCertMark"><Icon name={r.ok ? "check" : "lock"} size={12} /></span>
                        <div>
                          <div className="cpCertN">{r.n}</div>
                          <div className="cpCertS">{r.s}</div>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              )}

              {c.news.length > 0 && (
                <div className="cpCard">
                  <div className="cpH">News &amp; updates <button type="button" className="cpHLink" onClick={() => setTab("news")}>All {c.news.length}</button></div>
                  {c.news.slice(0, 3).map((n, i) => (
                    <div key={i} className="cpUpd">
                      <div className="cpUpdDate tabular">{n.t}</div>
                      <div className="cpUpdBody">
                        <div className="cpUpdH">{n.h}</div>
                        <div className="cpUpdM">
                          <a className="cpUpdSrc" href={n.url ? "https://" + n.url : "#"} target="_blank" rel="noreferrer">{n.s}<Icon name="open" size={10} /></a>
                          <span className="cpUpdW">{n.w}</span>
                        </div>
                      </div>
                      {n.sentiment && <span className={"cpSent is-" + n.sentiment.toLowerCase()}><Icon name="arrowUp" size={10} />{n.sentiment}</span>}
                    </div>
                  ))}
                </div>
              )}
            </React.Fragment>
          )}

          {tab === "journey" && (
            <React.Fragment>
              <div className="cpCard">
                <div className="cpH">Relationship history</div>
                <p className="cpSubHead">See how your organization’s relationship with this vendor began, developed, and changed over time.</p>
                {c.journey && c.journey.length > 0 ? (
                  <div className="cpJourney">
                    {c.journey.map((m, i) => (
                      <div key={i} className={"cpJStep" + (i === c.journey.length - 1 ? " isNow" : "")}>
                        <div className="cpJRail"><span className="cpJDot"></span>{i < c.journey.length - 1 && <span className="cpJLine"></span>}</div>
                        <div className="cpJBody">
                          <div className="cpJTop"><span className="cpJStepN tabular">{i + 1}</span><span className="cpJStage">{m.stage}</span><span className="cpJDate tabular">{m.t}</span></div>
                          <div className="cpJEvent">{m.e}</div>
                          <div className={"cpJWhy mono" + (m.emergent ? " isEmergent" : "")}>{m.why}</div>
                        </div>
                      </div>
                    ))}
                  </div>
                ) : <div className="cpFactAbsent">Nothing has happened yet. Adding this business writes the first event.</div>}
              </div>
              <div className="cpCard">
                <div className="cpH">Who this business is connected to</div>
                <p className="cpSubHead">Clients, co-bid partners, and its own suppliers. Line weight is relationship strength; a dashed edge means nothing has happened yet. Two views over the same connections — the network, or when each one started.</p>
                {c.graph ? <CpGraph g={c.graph} />
                  : <div className="cpFactAbsent">No connections in the record yet. Nobody has worked with this business inside Stimulus.</div>}
              </div>
            </React.Fragment>
          )}

          {tab === "facts" && <CpFactsPanel c={c} />}

          {tab === "financials" && (
            <div className="cpCard cpFinCard">
              <div className="cpH">Financials
                {c.financials.selfReported && <span className="cpSelfRep"><Icon name="alert" size={12} /> Self-reported · unaudited</span>}
              </div>
              <p className="cpSubHead">Reported financial indicators with source context. Figures are not audited by Stimulus.</p>
              {c.financials.hero && (
                <div className="cpFinHero">
                  <div className="cpFinHeroTop">
                    <div>
                      <div className="cpFinHeroK">{c.financials.hero.label}</div>
                      <div className="cpFinHeroV tabular">{c.financials.hero.v}
                        {c.financials.hero.d && <span className="cpFinHeroD">{c.financials.hero.d}</span>}</div>
                    </div>
                    <KChip level={c.financials.hero.consent} grantedBy={c.financials.hero.grantedBy} />
                  </div>
                  {(function () {
                    const rows = c.financials.rows.slice().reverse();
                    const max = Math.max.apply(null, rows.map((x) => x.n || 0)) || 1;
                    return (
                      <div className="cpFinBars">
                        {rows.map((x, i) => (
                          <div key={i} className="cpFinBarRow">
                            <span className="cpFinBarK tabular">{x.k.replace(/^[^,]+,\s*/, "")}</span>
                            <span className="cpFinBarTrack">
                              {x.n ? (
                                <span className={"cpFinBarFill" + (i === rows.length - 1 ? " isLatest" : "")} style={{ width: Math.round((x.n / max) * 100) + "%" }}>
                                  {x.d && <span className="cpFinBarD tabular">{x.d}</span>}
                                </span>
                              ) : <span className="cpFinBarNone">No figure recorded</span>}
                            </span>
                            <span className="cpFinBarV tabular">{x.v}</span>
                          </div>
                        ))}
                      </div>
                    );
                  })()}
                  <div className="cpFinSrc">Source: {c.financials.hero.source}</div>
                  <div className="cpFinLegend">Bar length is the reported figure. The number inside each bar is the increase over the prior year.</div>
                </div>
              )}
              <div className="cpFinPairs">
                {c.financials.side.filter((x) => x.v).map((x, i) => (
                  <div key={i} className="cpFinPair">
                    <div className="cpFinPairK">{x.k}</div>
                    <div className="cpFinPairV tabular">{x.v}</div>
                    <div className="cpFinPairN">{x.note}</div>
                  </div>
                ))}
              </div>
              {c.financials.side.filter((x) => !x.v).map((x, i) => (
                <div key={i} className="cpFinAbsent">
                  <span className="cpFinAbsentIcon"><Icon name={x.icon || "chart"} size={14} /></span>
                  <div>
                    <div className="cpFinAbsentK">{x.k}</div>
                    <div className="cpFinAbsentN">{x.note}</div>
                  </div>
                </div>
              ))}
              <div className="cpFinFoot">Missing data means “not recorded,” not a negative financial signal.</div>
            </div>
          )}

          {tab === "people" && (
            <div className="cpCard cpPeopleCard">
              <div className="cpH">People
                <span className="cpCount">{c.people.filter((p) => !p.locked).length} visible{c.restricted ? " · " + c.restricted + " restricted" : ""}</span>
              </div>
              <p className="cpSubHead">People named in evidence your organization can access. Roles and contact details are never inferred.</p>
              {c.people.length > 0 ? c.people.map((p, i) => (
                <div key={i} className={"cpPerson" + (p.locked ? " isLocked" : "")}>
                  <span className="cpAv">{p.av}</span>
                  <div className="cpPersonMain">
                    <div className="cpPersonHead">
                      <span className="cpPersonN">{p.n}</span>
                      {p.locked && <span className="cpPersonRestricted"><Icon name="lock" size={10} /> Not shared with you</span>}
                      {!p.locked && p.consent === "public" && <KChip level="public" />}
                    </div>
                    <div className="cpPersonR">{p.r}</div>
                    <div className="cpPersonEv">{p.note}</div>
                    {p.evidence && <div className="cpPersonEvSub">{p.evidence}</div>}
                    {!p.locked && p.consent !== "public" && (
                      <div className="cpPersonChip"><KChip level={p.consent} grantedBy={p.grantedBy} /></div>
                    )}
                    {!p.locked && (
                      <div className="cpPersonLinks">
                        {p.email
                          ? <a className="cpPersonLink" href={"mailto:" + p.email}><Icon name="mail" size={12} />{p.email}</a>
                          : <span className="cpPersonNone">No email shared</span>}
                        {p.phone
                          ? <a className="cpPersonLink" href={"tel:" + p.phone.replace(/[^+\d]/g, "")}><Icon name="phone" size={12} />{p.phone}</a>
                          : <span className="cpPersonNone">No phone number shared</span>}
                      </div>
                    )}
                  </div>
                </div>
              )) : <div className="cpFactAbsent">No people in the record yet.</div>}
            </div>
          )}

          {tab === "news" && (
            <div className="cpCard">
              <div className="cpH">News &amp; updates <span className="cpHSent">Sentiment</span></div>
              <p className="cpSubHead">Each item says why it matters to your org. Sentiment is read from the item, not from the relationship.</p>
              {c.news.length > 0 ? c.news.map((n, i) => (
                <div key={i} className="cpUpd">
                  <div className="cpUpdDate tabular">{n.t}</div>
                  <div className="cpUpdBody">
                    <div className="cpUpdH">{n.h}</div>
                    <div className="cpUpdM">
                      <a className="cpUpdSrc" href={n.url ? "https://" + n.url : "#"} target="_blank" rel="noreferrer">{n.s}<Icon name="open" size={10} /></a>
                      <span className="cpUpdW">{n.w}</span>
                    </div>
                    <div className="cpUpdProv"><KChip level={n.consent} size="inline" grantedBy={n.grantedBy} />{n.url && <span className="mono cpNewsUrl">{n.url}</span>}</div>
                  </div>
                  {n.sentiment && <span className={"cpSent is-" + n.sentiment.toLowerCase()}><Icon name="arrowUp" size={10} />{n.sentiment}</span>}
                </div>
              )) : <div className="cpFactAbsent">No news in the record yet.</div>}
            </div>
          )}
        </div>

        <aside className="cpRail">
          <div className="cpCard cpRelCard">
            <div className="cpRelState">{rel.state}</div>
            {rel.strength && (
              <div className="cpScore">
                <span className="cpScoreN tabular">{rel.strength.score}</span>
                <span className="cpScoreRead">{rel.strength.read}</span>
              </div>
            )}
            <p className="cpRelLine">{rel.line}</p>
          </div>
          {rel.warm.length > 0 && (
            <div className="cpCard">
              <div className="cpHSm">The warm path</div>
              {rel.warm.map((h, i) => (
                <div key={h.n} className="cpHop">
                  <div className="cpHopRail"><span className="cpHopDot"></span>{i < rel.warm.length - 1 && <span className="cpHopLine"></span>}</div>
                  <div>
                    <div className="cpHopN">{h.n}</div>
                    <div className="cpHopR">{h.r}</div>
                  </div>
                  {h.s != null && <span className="cpHopS tabular">{h.s}</span>}
                </div>
              ))}
              <button type="button" className="cpRailBtn" onClick={() => onAsk && onAsk("Draft an intro request for " + c.name)}>Ask for the intro</button>
            </div>
          )}
          <div className="cpCard">
            <div className="cpHSm">In the record</div>
            {rel.record.map((r, i) => (
              <div key={i} className="cpRec">
                <div className="cpRecE">{r.e}</div>
                <div className="cpRecM"><span className="tabular">{r.t}</span><span>{r.who}</span></div>
              </div>
            ))}
          </div>
        </aside>
      </div>
    </div>
  );
}

Object.assign(window, { CompanyProfile });
