/* global React, useInView, Check */
const { useState: useStatePhy, useEffect: useEffectPhy } = React;

/* ===================== Thermal heatmap ===================== */
function ThermalViz() {
  const cols = 16, rows = 10;
  const spots = [[11, 3, 1], [4, 6, 0.7]];
  const cells = [];
  for (let r = 0; r < rows; r++) for (let c = 0; c < cols; c++) {
    let v = 0;
    spots.forEach(([sx, sy, w]) => {
      const d2 = ((c - sx) ** 2) / 10 + ((r - sy) ** 2) / 6;
      v += w * Math.exp(-d2 * 0.7);
    });
    v = Math.min(1, v);
    const pct = Math.round(v * 100);
    cells.push(
      <i key={r + "-" + c} style={{ background: `color-mix(in oklab, var(--warm) ${pct}%, var(--bg-2))` }} />
    );
  }
  return (
    <div className="thermal" style={{ gridTemplateColumns: `repeat(${cols}, 1fr)` }}>
      {cells}
      <span className="thermal__tag mono">94.2&deg;C</span>
    </div>
  );
}

/* ===================== EM coupling ===================== */
function EmViz() {
  return (
    <svg viewBox="0 0 220 130" className="emviz" preserveAspectRatio="xMidYMid meet">
      {[1, 2, 3, 4].map((i) => (
        <circle key={i} cx="64" cy="65" r={i * 16} className="emviz__ring" style={{ animationDelay: i * 0.18 + "s" }} />
      ))}
      <line x1="64" y1="20" x2="64" y2="110" className="emviz__trace" />
      <line x1="150" y1="20" x2="150" y2="110" className="emviz__trace emviz__trace--victim" />
      <path d="M70,40 C110,40 110,72 144,72" className="emviz__couple" />
      <text x="48" y="124" className="emviz__lbl">aggressor</text>
      <text x="132" y="124" className="emviz__lbl">victim</text>
    </svg>
  );
}

/* ===================== Substrate noise ===================== */
function NoiseViz() {
  const W = 220, H = 120, mid = H / 2;
  let d = `M0,${mid}`;
  let seed = 7;
  const rnd = () => { seed = (seed * 9301 + 49297) % 233280; return seed / 233280; };
  for (let x = 0; x <= W; x += 4) {
    const env = Math.exp(-x / 150);
    const y = mid + (rnd() - 0.5) * 64 * env;
    d += ` L${x},${y.toFixed(1)}`;
  }
  return (
    <svg viewBox={`0 0 ${W} ${H}`} className="noiseviz" preserveAspectRatio="none">
      <line x1="0" y1={mid} x2={W} y2={mid} className="noiseviz__axis" />
      <path d={d} className="noiseviz__wave" />
    </svg>
  );
}

const PHYS = [
  { id: "thermal", title: "Thermal analysis", viz: <ThermalViz />, blurb: "Resolve junction hotspots and gradients across the die before they bite \u2014 self-heating modeled in-stack.", tags: ["FEM solver", "Self-heating"] },
  { id: "em", title: "High-speed EM", viz: <EmViz />, blurb: "Quantify electromagnetic interference and aggressor\u2013victim coupling on critical nets at frequency.", tags: ["Field solver", "Crosstalk"] },
  { id: "noise", title: "Substrate noise", viz: <NoiseViz />, blurb: "Trace substrate coupling from digital switching into sensitive analog nodes \u2014 no third-party export.", tags: ["Coupling", "Isolation"] },
];

function MultiPhysicsSection() {
  return (
    <section className="section" id="multiphysics">
      <div className="container">
        <div className="sec-head reveal">
          <Eyebrow>Layer 1 {"\u00b7"} Native multi-physics</Eyebrow>
          <h2 className="h2">The physics of silicon,<br /><em>in</em> the design loop.</h2>
          <p className="lead sec-head__lead">
            Modern analog and mixed-signal designs are exquisitely sensitive to their environment.
            A unified Python API simulates the parasitic effects that legacy flows force you to export &mdash;
            thermal, electromagnetic, and substrate noise &mdash; right in the stack.
          </p>
        </div>
        <div className="phys-grid">
          {PHYS.map((p, i) => (
            <article className="card phys reveal" data-d={i + 1} key={p.id}>
              <div className="phys__viz">{p.viz}</div>
              <h3 className="h3">{p.title}</h3>
              <p className="phys__blurb">{p.blurb}</p>
              <Tags items={p.tags} />
            </article>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ===================== AI core: place&route + predictive DRC ===================== */
function PlaceRouteViz() {
  const [ref, seen] = useInView(0.4);
  // blocks: before (scattered) -> after (packed) coords
  const blocks = [
    { b: [12, 14, 34, 26], a: [16, 18, 30, 24] },
    { b: [70, 10, 30, 22], a: [50, 18, 28, 22] },
    { b: [120, 40, 26, 30], a: [82, 18, 24, 24] },
    { b: [30, 60, 28, 24], a: [16, 48, 30, 26] },
    { b: [96, 70, 32, 24], a: [50, 48, 28, 26] },
    { b: [150, 16, 22, 26], a: [82, 48, 24, 26] },
  ];
  return (
    <div className="pr" ref={ref}>
      <svg viewBox="0 0 184 100" className={"pr__svg " + (seen ? "opt" : "")}>
        <rect x="8" y="8" width="168" height="84" rx="4" className="pr__die" />
        {blocks.map((bl, i) => {
          const [x, y, w, h] = seen ? bl.a : bl.b;
          return <rect key={i} x={x} y={y} width={w} height={h} rx="2.5" className="pr__blk" style={{ transitionDelay: i * 0.05 + "s" }} />;
        })}
      </svg>
      <div className="pr__metric mono">
        <span>wirelength</span>
        <b className={seen ? "drop" : ""}>{seen ? "\u221241%" : "\u00b7\u00b7\u00b7"}</b>
      </div>
    </div>
  );
}

const DRC = [
  ["min spacing m2", "pass"], ["via enclosure", "pass"], ["antenna ratio", "pass"],
  ["density m1", "flag"], ["LVS net match", "pass"], ["well tie distance", "flag"],
];
function DrcViz() {
  const [ref, seen] = useInView(0.4);
  return (
    <ul className="drc" ref={ref}>
      {DRC.map(([name, st], i) => (
        <li key={name} className={"drc__row " + (seen ? "is-in " : "") + "drc__row--" + st} style={{ transitionDelay: i * 0.07 + "s" }}>
          <span className="drc__ic">{st === "pass" ? <Check /> : "!"}</span>
          <span className="drc__name mono">{name}</span>
          <span className="drc__st mono">{st === "pass" ? "ok" : "predicted"}</span>
        </li>
      ))}
    </ul>
  );
}

function AiCoreSection() {
  return (
    <section className="section" id="ai-core">
      <div className="container">
        <div className="sec-head reveal">
          <Eyebrow>Layer 2 {"\u00b7"} AI optimization core</Eyebrow>
          <h2 className="h2">Fewer manual layout cycles.<br /><em>Caught</em> before extraction.</h2>
        </div>
        <div className="ai-grid">
          <article className="card ai reveal" data-d="1">
            <PlaceRouteViz />
            <h3 className="h3">ML-assisted place &amp; route</h3>
            <p className="phys__blurb">PyTorch / TensorFlow models run natively in the stack to optimize floorplanning and trace generation &mdash; tightening placement and shrinking wirelength.</p>
            <Tags items={["Placement", "Routing", "PyTorch"]} />
          </article>
          <article className="card ai reveal" data-d="2">
            <DrcViz />
            <h3 className="h3">Predictive DRC / LVS</h3>
            <p className="phys__blurb">Trained models flag likely physical violations and mismatches in real time &mdash; before you commit to computationally heavy full-chip extraction.</p>
            <Tags items={["Real-time", "DRC", "LVS"]} />
          </article>
        </div>
      </div>
    </section>
  );
}

/* ===================== Cloud execution engine ===================== */
const JOBS = [
  ["spice_ac.mc", "128 shards", 100],
  ["rc_extract.full", "running", 72],
  ["em_solve.crit", "running", 46],
  ["drc.signoff", "queued", 0],
];
function CloudSection() {
  const [ref, seen] = useInView(0.35);
  return (
    <section className="section cloud" id="cloud-sec">
      <div className="container">
        <div className="sec-head reveal">
          <Eyebrow>Layer 3 {"\u00b7"} Execution engine</Eyebrow>
          <h2 className="h2">Trigger a sign-off.<br />The <em>cloud</em> does the lifting.</h2>
          <p className="lead sec-head__lead">
            The Python orchestration layer farms intensive jobs to secure, elastic compute &mdash;
            accelerated SPICE and massive parasitic extraction &mdash; then parses raw solver data
            back into clean visualizations in your IDE. No local cluster required.
          </p>
        </div>
        <div className="window cloud__panel reveal" data-d="1" ref={ref}>
          <div className="window__bar">
            <span className="window__dots"><i /><i /><i /></span>
            <span className="window__title">orchestrator</span>
            <span className="spacer" />
            <span className="status-chip"><span className="dot-run" /> 248 vCPU {"\u00b7"} autoscaling</span>
          </div>
          <div className="cloud__jobs">
            {JOBS.map(([name, st, pct], i) => (
              <div className="job" key={name}>
                <span className="job__name mono">{name}</span>
                <span className="job__st mono">{st}</span>
                <div className="job__bar"><span className="job__fill" style={{ width: (seen ? pct : 0) + "%", transitionDelay: i * 0.12 + "s" }} /></div>
                <span className="job__pct mono">{pct}%</span>
              </div>
            ))}
          </div>
          <div className="cloud__stats">
            {[["throughput", "1.4M nets/s"], ["queue latency", "0.8s"], ["cost", "pay-per-run"]].map(([k, v]) => (
              <div className="cstat" key={k}><span className="cstat__v">{v}</span><span className="cstat__k mono">{k}</span></div>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { MultiPhysicsSection, AiCoreSection, CloudSection });
