/* global React, usePartnerModal */

// ============ 7-Layer Ontology Stack ============
function OntologyStack() {
  const { open: openPartner } = usePartnerModal();
  const layers = [
    { n: 7, name: "Goals & Governance",         zone: 0, note: "What the organisation is trying to achieve, and the rules it must live within." },
    { n: 6, name: "Decisions & Trace",          zone: 0, note: "Every action recorded with reasoning and a SHA-256 lineage. The audit boundary." },
    { n: 5, name: "Policies, Rules & Security", zone: 1, note: "Causal, regulatory, and security constraints the agent reasons against. The policy and access boundary." },
    { n: 4, name: "Agents & Tasks",             zone: 1, note: "SuperAgents operating against the world model." },
    { n: 3, name: "World Model",                zone: 2, note: "A living digital twin of operations, entities and relationships." },
    { n: 2, name: "Ontology",                   zone: 2, note: "Domain entities, attributes, and the language of the work." },
    { n: 1, name: "Signal & Data",              zone: 2, note: "Raw events from systems, sensors, ledgers, partners." },
  ];
  const zones = [
    { id: "intent",    label: "Intent & Accountability" },
    { id: "reasoning", label: "Reasoning & Policy" },
    { id: "domain",    label: "Domain & Data" },
  ];
  const revealed = false;
  const [hover, setHover] = React.useState(0);
  const safeHover = !revealed && hover > 2 ? 0 : hover;
  return (
    <div className={"ontology" + (revealed ? " is-revealed" : " is-teased")}>
      <div className="ontology-stack-wrap">
        <div className="ontology-stack">
          {zones.map((z, zi) => (
            <div key={z.id} className={"ontology-zone ontology-zone-" + z.id}>
              <div className={"ontology-zone-label" + (!revealed && zi > 0 ? " is-blurred" : "")}>
                <span className="ontology-zone-num">{String(3 - zi).padStart(2, "0")}</span>
                <span className="ontology-zone-name">{z.label}</span>
              </div>
              {layers.map((l, i) => (
                l.zone === zi && (
                  <div
                    key={l.n}
                    className={"layer" + (safeHover === i ? " on" : "") + (!revealed && i > 2 ? " is-blurred" : "")}
                    onMouseEnter={() => { if (revealed || i <= 2) setHover(i); }}
                    aria-hidden={!revealed && i > 2 ? "true" : undefined}
                  >
                    <div className="layer-n">L{l.n}</div>
                    <div className="layer-name">{l.name}</div>
                    <div className="layer-bar"><span style={{ width: `${30 + (l.n / 7) * 70}%` }}></span></div>
                  </div>
                )
              ))}
            </div>
          ))}
        </div>
        {!revealed && (
          <div className="ontology-cta-overlay">
            <div className="ontology-cta-meta">
              <span className="ontology-cta-count">Structure runs deeper</span>
              <span className="ontology-cta-dot">·</span>
              <span className="ontology-cta-hint">four layers beneath</span>
            </div>
            <button
              type="button"
              className="ontology-cta"
              onClick={openPartner}
            >
              <span>Know more</span>
              <svg width="14" height="10" viewBox="0 0 14 10" fill="none" aria-hidden="true">
                <path d="M1 5h12M9 1l4 4-4 4" stroke="currentColor" strokeWidth="1.4" strokeLinecap="square" />
              </svg>
            </button>
          </div>
        )}
      </div>
      <div className="ontology-detail">
        <div className="ontology-detail-eyebrow">Layer {layers[safeHover].n} / 7</div>
        <div className="ontology-detail-name">{layers[safeHover].name}</div>
        <div className="ontology-detail-note">{layers[safeHover].note}</div>
        {!revealed && (
          <div className="ontology-detail-teaser">
            The full seven-layer stack — including the world model, ontology and
            signal layers — is available on request.
          </div>
        )}
        <div className="ontology-trace">
          <span className="k">trace</span>
          <span className="v">sha256:{("acef214b" + (safeHover * 911).toString(16) + "8d3f29e1c47ba9").slice(0, 32)}…</span>
        </div>
      </div>
    </div>
  );
}

// ============ Work 2.0 vs 3.0 split ============
function WorkSplit() {
  return (
    <div className="worksplit">
      <div className="ws-col ws-old">
        <div className="ws-label">Work 2.0</div>
        <div className="ws-title">Process automation</div>
        <ol>
          <li>Define the process</li>
          <li>Hard-code the steps</li>
          <li>Automate the steps</li>
          <li>Measure throughput</li>
          <li>Review quarterly</li>
        </ol>
        <svg className="ws-diagram" viewBox="0 0 280 80" aria-hidden="true">
          {[0,1,2,3,4].map((i) => (
            <g key={i}>
              <rect x={4 + i * 56} y="28" width="44" height="24" fill="none" stroke="currentColor" strokeWidth="1" />
              <text x={26 + i * 56} y="44" textAnchor="middle" fontFamily="var(--mono)" fontSize="9" fill="currentColor" letterSpacing="0.05em">{i+1}</text>
              {i < 4 && <line x1={48 + i * 56} y1="40" x2={60 + i * 56} y2="40" stroke="currentColor" strokeWidth="1" />}
            </g>
          ))}
        </svg>
        <div className="ws-foot">Capped by its slowest mandatory step.</div>
      </div>

      <div className="ws-divider" aria-hidden="true">
        <span>vs</span>
      </div>

      <div className="ws-col ws-new">
        <div className="ws-label">Work 3.0</div>
        <div className="ws-title">Goal-directed reasoning</div>
        <ol>
          <li>Declare the goal</li>
          <li>Reason about constraints</li>
          <li>Discover the workflow</li>
          <li>Trace every decision</li>
          <li>Learn from every run</li>
        </ol>
        <svg className="ws-diagram ws-graph" viewBox="0 0 280 80" aria-hidden="true">
          {/* central goal node */}
          <circle cx="140" cy="40" r="6" fill="currentColor" />
          {/* satellite nodes */}
          {[
            [40, 20], [40, 60], [240, 20], [240, 60], [140, 8], [140, 72]
          ].map(([x, y], i) => (
            <g key={i}>
              <line x1="140" y1="40" x2={x} y2={y} stroke="currentColor" strokeWidth="0.6" opacity="0.55" />
              <circle cx={x} cy={y} r="3" fill="none" stroke="currentColor" strokeWidth="1" />
            </g>
          ))}
        </svg>
        <div className="ws-foot">The workflow emerges from the goal.</div>
      </div>
    </div>
  );
}

// ============ Limestreet leakage visualisation ============
function LeakageViz() {
  // 12 catalogue lanes, with leakage points
  const lanes = Array.from({ length: 14 }, (_, i) => i);
  // pre-computed deterministic positions
  const leaks = [
    { lane: 0, x: 22 }, { lane: 1, x: 48 }, { lane: 2, x: 71 },
    { lane: 3, x: 35 }, { lane: 4, x: 62 }, { lane: 5, x: 18 },
    { lane: 6, x: 54 }, { lane: 7, x: 78 }, { lane: 8, x: 41 },
    { lane: 9, x: 27 }, { lane: 10, x: 66 }, { lane: 11, x: 84 },
    { lane: 12, x: 33 }, { lane: 13, x: 58 },
    // some lanes have multiple
    { lane: 2, x: 36 }, { lane: 5, x: 62 }, { lane: 8, x: 75 }, { lane: 11, x: 30 },
  ];
  return (
    <div className="leakage">
      <div className="leakage-head">
        <div>
          <div className="leakage-eyebrow">Catalogue revenue</div>
          <div className="leakage-figure">8 – 20%</div>
          <div className="leakage-note">leaks before it reaches the rights-holder. Mismatched metadata, opaque splits, untracked usage, uncollected royalties.</div>
        </div>
        <div className="leakage-legend">
          <span><i className="dot earned" /> earned</span>
          <span><i className="dot leak" /> leaked</span>
        </div>
      </div>
      <div className="leakage-lanes">
        {lanes.map((i) => (
          <div className="lane" key={i}>
            <div className="lane-label">CAT-{(101 + i).toString().padStart(3, "0")}</div>
            <div className="lane-track">
              {leaks
                .filter((l) => l.lane === i)
                .map((l, k) => (
                  <div key={k} className="leak" style={{ left: l.x + "%" }} />
                ))}
            </div>
            <div className="lane-num">{(96 - (i % 5) * 1.5).toFixed(1)}%</div>
          </div>
        ))}
      </div>
      <div className="leakage-foot">
        <span>Limestreet ▸ active scan</span>
        <span className="muted">17,402 contracts indexed · 41 leakage patterns matched</span>
      </div>
    </div>
  );
}

// ============ Digital Twin graph ============
function TwinGraph() {
  // Nodes: a small graph of bank entities and relationships
  const nodes = [
    { id: "core",   x: 50, y: 50, label: "Core",         kind: "k" },
    { id: "ledger", x: 25, y: 28, label: "Ledger",       kind: "n" },
    { id: "kyc",    x: 22, y: 70, label: "KYC",          kind: "n" },
    { id: "card",   x: 72, y: 30, label: "Card",         kind: "n" },
    { id: "lend",   x: 78, y: 64, label: "Lending",      kind: "n" },
    { id: "rule",   x: 50, y: 18, label: "Rules",        kind: "p" },
    { id: "trace",  x: 50, y: 82, label: "Trace",        kind: "p" },
    { id: "agent1", x: 12, y: 50, label: "Agent · risk", kind: "a" },
    { id: "agent2", x: 88, y: 48, label: "Agent · ops",  kind: "a" },
  ];
  const edges = [
    ["core","ledger"], ["core","kyc"], ["core","card"], ["core","lend"],
    ["core","rule"], ["core","trace"], ["agent1","core"], ["agent2","core"],
    ["ledger","trace"], ["card","ledger"], ["lend","ledger"], ["kyc","rule"],
    ["lend","rule"], ["card","rule"],
  ];
  const nodeById = Object.fromEntries(nodes.map((n) => [n.id, n]));
  return (
    <svg className="twin-graph" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid meet">
      <defs>
        <radialGradient id="coreGlow" cx="50%" cy="50%" r="50%">
          <stop offset="0%" stopColor="var(--accent)" stopOpacity="0.35" />
          <stop offset="100%" stopColor="var(--accent)" stopOpacity="0" />
        </radialGradient>
      </defs>
      <circle cx="50" cy="50" r="22" fill="url(#coreGlow)" />
      {edges.map(([a, b], i) => {
        const A = nodeById[a], B = nodeById[b];
        return (
          <line
            key={i}
            x1={A.x} y1={A.y} x2={B.x} y2={B.y}
            stroke="var(--ink-mute)" strokeWidth="0.25" opacity="0.6"
          />
        );
      })}
      {nodes.map((n) => (
        <g key={n.id}>
          {n.kind === "k" && (
            <>
              <circle cx={n.x} cy={n.y} r="4.2" fill="var(--ink)" />
              <circle cx={n.x} cy={n.y} r="1.6" fill="var(--accent)" />
            </>
          )}
          {n.kind === "n" && <circle cx={n.x} cy={n.y} r="2.4" fill="var(--paper)" stroke="var(--ink)" strokeWidth="0.4" />}
          {n.kind === "p" && <rect x={n.x - 2.4} y={n.y - 2.4} width="4.8" height="4.8" fill="var(--paper)" stroke="var(--ink)" strokeWidth="0.4" />}
          {n.kind === "a" && (
            <g>
              <polygon
                points={`${n.x},${n.y - 2.8} ${n.x + 2.6},${n.y + 1.6} ${n.x - 2.6},${n.y + 1.6}`}
                fill="var(--paper)" stroke="var(--ink)" strokeWidth="0.4"
              />
            </g>
          )}
          <text
            x={n.x}
            y={n.y + 7.5}
            textAnchor="middle"
            fontFamily="var(--mono)"
            fontSize="2.4"
            letterSpacing="0.12em"
            fill="var(--ink-mute)"
            style={{ textTransform: "uppercase" }}
          >
            {n.label}
          </text>
        </g>
      ))}
    </svg>
  );
}

Object.assign(window, { OntologyStack, WorkSplit, LeakageViz, TwinGraph, Figure });

// ============ Abstract image moment ============
function Figure({ src, alt, caption, fig, ratio = "21 / 9" }) {
  return (
    <figure className="fig" style={{ aspectRatio: ratio }}>
      <img src={src} alt={alt} loading="lazy" />
      <figcaption>
        <span className="fig-n">Fig. {fig}</span>
        <span className="fig-c">{caption}</span>
      </figcaption>
    </figure>
  );
}
