/* Hero "connection" variants - how the Clay arch and the Claude Code pig
   relate to each other in the hero. Three linked concepts + the original
   free-floating corners. Switched via the Tweaks panel (heroLink).

   - corners : original - both objects drift in opposite corners, no link
   - wire    : both grounded bottom-left/right, a sagging dashed wire runs
               between them with the system's parts threaded on as chips
   - circuit : corners kept, an orthogonal routed circuit line connects them
               around the text (technical-drawing language)
   - loop    : a dashed orbit ellipse around the headline; both objects sit
               ON the path with the other system parts as labeled nodes     */

const HV_CLAY = (window.__resources || {}).clayArch || "assets/clay-arch-t.png";   // 227×173  → h = w * 0.762
const HV_PIG = (window.__resources || {}).ccPig || "assets/cc-pig-t.png";       // 896×561  → h = w * 0.626
const HV_CLAY_R = 0.762;
const HV_PIG_R = 0.626;
/* the 4 signal colours from the section-seam pixels */
const HV_SIGNAL = ["#E0379E", "#37D6D6", "#52C964", "#6E7BE6"];

function useHvBox() {
  const ref = React.useRef(null);
  const [box, setBox] = React.useState({ w: 0, h: 0 });
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const measure = () => setBox((prev) => {
      const w = el.clientWidth, h = el.clientHeight;
      return (prev.w === w && prev.h === h) ? prev : { w, h };
    });
    const ro = new ResizeObserver(measure);
    ro.observe(el);
    measure();
    const raf = requestAnimationFrame(measure);
    window.addEventListener("load", measure);
    /* throttled/hidden iframes can miss every one-shot re-measure AND the
       RO transition - poll until a non-zero size lands, then let RO own it */
    let pollId;
    const poll = () => {
      measure();
      if (el.clientWidth > 0 && el.clientHeight > 0) return;
      pollId = setTimeout(poll, 220);
    };
    pollId = setTimeout(poll, 80);
    return () => { ro.disconnect(); cancelAnimationFrame(raf); clearTimeout(pollId); window.removeEventListener("load", measure); };
  }, []);
  return [ref, box];
}

/* matchMedia hook - true below the phone breakpoint */
function useIsMobile(q = "(max-width: 640px)") {
  const get = () => (typeof window !== "undefined" && window.matchMedia ? window.matchMedia(q).matches : false);
  const [m, setM] = React.useState(get);
  React.useEffect(() => {
    const mq = window.matchMedia(q);
    const on = () => setM(mq.matches);
    on();
    mq.addEventListener ? mq.addEventListener("change", on) : mq.addListener(on);
    return () => { mq.removeEventListener ? mq.removeEventListener("change", on) : mq.removeListener(on); };
  }, [q]);
  return m;
}

/* point on a cubic bezier */
function hvCubic(p0, p1, p2, p3, t) {
  const u = 1 - t;
  return {
    x: u * u * u * p0.x + 3 * u * u * t * p1.x + 3 * u * t * t * p2.x + t * t * t * p3.x,
    y: u * u * u * p0.y + 3 * u * u * t * p1.y + 3 * u * t * t * p2.y + t * t * t * p3.y,
  };
}

/* ---- original: free corners, gentle bob ---- */
function HvCorners() {
  return (
    <React.Fragment>
      <div className="sd-mhero-float sd-mhero-float-clay" aria-hidden="true"><img src={HV_CLAY} alt="" /></div>
      <div className="sd-mhero-float sd-mhero-float-cc" aria-hidden="true"><img src={HV_PIG} alt="" /></div>
    </React.Fragment>
  );
}

/* ---- grounded duo + sagging wire with system chips threaded on ---- */
function HvWire() {
  const [ref, { w, h }] = useHvBox();
  const clayW = Math.min(150, Math.max(108, w * 0.105));
  const pigW = Math.min(185, Math.max(122, w * 0.12));
  const clayH = clayW * HV_CLAY_R;
  const pigH = pigW * HV_PIG_R;
  const baseY = h - 34; // object feet
  const p0 = { x: clayW + 16, y: baseY - clayH * 0.52 };
  const p3 = { x: w - pigW - 20, y: baseY - pigH * 0.55 };
  const sag = h - 14;
  const p1 = { x: p0.x + (p3.x - p0.x) * 0.28, y: sag };
  const p2 = { x: p0.x + (p3.x - p0.x) * 0.72, y: sag };
  const chipsAll = [
    ["CRM WORKFLOWS", 0.15], ["ADS", 0.33], ["ABM ASSETS", 0.5],
    ["ENABLEMENT", 0.67], ["FEEDBACK", 0.85],
  ];
  const chips = w >= 1150 ? chipsAll : [["CRM", 0.22], ["ABM ASSETS", 0.5], ["FEEDBACK", 0.78]];
  return (
    <div ref={ref} className="sd-hv sd-hv--wire" aria-hidden="true">
      {w > 0 && (
        <svg width={w} height={h} viewBox={"0 0 " + w + " " + h}>
          <path className="sd-hv-wirepath" d={"M " + p0.x + " " + p0.y + " C " + p1.x + " " + p1.y + ", " + p2.x + " " + p2.y + ", " + p3.x + " " + p3.y} />
          <rect className="sd-hv-node" x={p0.x - 3} y={p0.y - 3} width="6" height="6" />
          <rect className="sd-hv-node" x={p3.x - 3} y={p3.y - 3} width="6" height="6" />
        </svg>
      )}
      {w > 0 && chips.map(([label, t]) => {
        const pt = hvCubic(p0, p1, p2, p3, t);
        return (
          <span key={label} className="sd-hv-chip" style={{ left: pt.x, top: pt.y }}>
            <span className="pt"></span>{label}
          </span>
        );
      })}
      <div className="sd-hv-obj" style={{ width: clayW, left: 0, bottom: 34, transform: "rotate(-6deg)" }}><img src={HV_CLAY} alt="" /></div>
      <div className="sd-hv-obj" style={{ width: pigW, right: 0, bottom: 34, transform: "rotate(4deg)" }}><img src={HV_PIG} alt="" /></div>
      <span className="sd-hv-cap" style={{ left: clayW / 2, bottom: 6, transform: "translateX(-50%)" }}>CLAY · DATA & ORCHESTRATION</span>
      <span className="sd-hv-cap" style={{ right: 0, bottom: 6, width: pigW, textAlign: "center" }}>CLAUDE CODE · AGENTS</span>
    </div>
  );
}

/* ---- corners + orthogonal routed circuit line around the text ---- */
function HvCircuit() {
  const [ref, { w, h }] = useHvBox();
  const clayW = Math.min(160, Math.max(96, w * 0.105));
  const pigW = Math.min(190, Math.max(104, w * 0.12));
  const clayH = clayW * HV_CLAY_R;
  const pigH = pigW * HV_PIG_R;
  const clayL = w * 0.07, clayT = h * 0.13;
  const cx = clayL + clayW / 2;
  const pigL = w - w * 0.06 - pigW;
  const pigT = h - h * 0.11 - pigH;
  const pigCy = pigT + pigH / 2;
  const xEnd = pigL - 16;
  const y0 = clayT + clayH + 14;
  const yb = Math.max(pigCy, h * 0.8);
  const d = "M " + cx + " " + y0 + " L " + cx + " " + (yb - 18) + " Q " + cx + " " + yb + " " + (cx + 18) + " " + yb + " L " + xEnd + " " + yb;
  return (
    <div ref={ref} className="sd-hv sd-hv--circuit" aria-hidden="true">
      {w > 0 && (
        <svg width={w} height={h} viewBox={"0 0 " + w + " " + h}>
          <path className="sd-hv-wirepath" d={d} />
          <rect className="sd-hv-node" x={cx - 3} y={y0 - 3} width="6" height="6" />
          <rect className="sd-hv-node" x={xEnd - 3} y={yb - 3} width="6" height="6" />
        </svg>
      )}
      <div className="sd-hv-obj" style={{ width: clayW, left: clayL, top: clayT, transform: "rotate(-8deg)" }}><img src={HV_CLAY} alt="" /></div>
      <div className="sd-hv-obj" style={{ width: pigW, left: pigL, top: pigT, transform: "rotate(6deg)" }}><img src={HV_PIG} alt="" /></div>
      <span className="sd-hv-cap" style={{ left: clayL, top: clayT - 24, width: clayW, textAlign: "center" }}>CLAY · DATA & ORCH.</span>
      <span className="sd-hv-cap" style={{ left: pigL, top: pigT + pigH + 12, width: pigW, textAlign: "center" }}>CLAUDE CODE · AGENTS</span>
    </div>
  );
}

/* ---- orbit: dashed ellipse around the headline, objects ON the path ---- */
function HvLoop() {
  const [ref, { w, h }] = useHvBox();
  const cx = w / 2, cy = h / 2;
  const rx = w / 2 - 6, ry = h / 2 - 6;
  const pt = (deg) => {
    const a = (deg * Math.PI) / 180;
    return { x: cx + rx * Math.cos(a), y: cy + ry * Math.sin(a), cos: Math.cos(a), sin: Math.sin(a) };
  };
  const clayW = Math.min(140, Math.max(95, w * 0.115));
  const pigW = Math.min(172, Math.max(105, w * 0.135));
  const clayH = clayW * HV_CLAY_R;
  const pigH = pigW * HV_PIG_R;
  const clayP = pt(207);
  const pigP = pt(27);
  const nodes = [
    ["TAM MAPPING", 240], ["ENRICHMENT", 273], ["SCORING", 306], ["SIGNALS", 339],
    ["CRM WORKFLOWS", 57], ["ADS", 87], ["ABM ASSETS", 117], ["ENABLEMENT", 147], ["SALES FEEDBACK LOOPS", 177],
  ];
  /* labels always show; verticals get pushed clear of the headline/CTA band -
     on short containers they align to common lines above/below the ellipse so
     they can't land behind the headline glyphs or the CTA buttons. The far-left
     node centers under its dot so it can't run off-canvas. */
  const short = h < 560;
  const place = (p) => {
    if (p.cos < -0.92) return { anchor: "middle", lx: p.x, ly: p.y + 22 };
    if (p.sin > 0.75) return { anchor: "middle", lx: p.x, ly: short ? h + 27 : p.y + 26 };
    if (p.sin < -0.75) return { anchor: "middle", lx: p.x, ly: short ? -8 : p.y - 14 };
    return { anchor: p.cos > 0 ? "start" : "end", lx: p.x + (p.cos > 0 ? 17 : -17), ly: p.y + p.sin * 15 + 4 };
  };
  return (
    <div ref={ref} className="sd-hv sd-hv--loop" aria-hidden="true">
      {w > 0 && (
        <svg width={w} height={h} viewBox={"0 0 " + w + " " + h}>
          <ellipse className="sd-hv-loopline" cx={cx} cy={cy} rx={rx} ry={ry} />
          {nodes.map(([label, deg], i) => {
            const p = pt(deg);
            const { anchor, lx, ly } = place(p);
            return (
              <g key={label}>
                <rect className="sd-hv-node" style={{ fill: HV_SIGNAL[i % 4] }} x={p.x - 3.5} y={p.y - 3.5} width="7" height="7" />
                <text className="sd-hv-svglabel" x={lx} y={ly} textAnchor={anchor}>{label}</text>
              </g>
            );
          })}
        </svg>
      )}
      {w > 0 && (
        <React.Fragment>
          <div className="sd-hv-obj" style={{ width: clayW, left: clayP.x - clayW / 2, top: clayP.y - clayH / 2, transform: "rotate(-8deg)" }}><img src={HV_CLAY} alt="" /></div>
          <div className="sd-hv-obj" style={{ width: pigW, left: pigP.x - pigW / 2, top: pigP.y - pigH / 2, transform: "rotate(6deg)" }}><img src={HV_PIG} alt="" /></div>
          <span className="sd-hv-cap" style={{ left: clayP.x - 80, top: clayP.y + clayH / 2 + 8, width: 160, textAlign: "center" }}>CLAY · DATA<br />& ORCHESTRATION</span>
          <span className="sd-hv-cap" style={{ left: pigP.x - 80, top: pigP.y + pigH / 2 + 8, width: 160, textAlign: "center" }}>CLAUDE CODE · AGENTS</span>
        </React.Fragment>
      )}
    </div>
  );
}

/* ---- mobile: a compact centred "bridge" above the headline. The two
   product marks (Clay + Claude Code) linked by a short dashed wire - the
   same two-pillar story as the desktop variants, but flow-safe so it never
   collides with the centred copy on a narrow screen. ---- */
function HvMobile() {
  return (
    <div className="sd-hv-mob" aria-hidden="true">
      <figure className="hvm-obj hvm-clay">
        <span className="hvm-img"><img src={HV_CLAY} alt="" /></span>
        <figcaption>CLAY · DATA</figcaption>
      </figure>
      <span className="hvm-link"><span className="hvm-dot" /></span>
      <figure className="hvm-obj hvm-cc">
        <span className="hvm-img"><img src={HV_PIG} alt="" /></span>
        <figcaption>CLAUDE CODE</figcaption>
      </figure>
    </div>
  );
}

function HeroFloats({ variant }) {
  const mobile = useIsMobile("(max-width: 900px)");
  if (mobile) return <HvMobile />;
  if (variant === "wire") return <HvWire />;
  if (variant === "circuit") return <HvCircuit />;
  if (variant === "loop") return <HvLoop />;
  return <HvCorners />;
}

Object.assign(window, { HeroFloats });
