// Alpha Z · Hero figure
// 5×5 active matrix on a wide lattice that fades radially outward.
// Animation: cells light up sequentially in the locked path order.

const HF_COLS = 5;
const HF_ROWS = 5;

// All 11 cells, numbered in reading order (top to bottom, left to right)
const HF_CELLS = [
  { num: "01", c: 2, r: 0, kind: "path"  },
  { num: "02", c: 1, r: 1, kind: "path"  },
  { num: "03", c: 0, r: 2, kind: "alpha" },
  { num: "04", c: 2, r: 1, kind: "path"  },
  { num: "05", c: 2, r: 2, kind: "path"  },
  { num: "06", c: 4, r: 2, kind: "path"  },
  { num: "07", c: 3, r: 2, kind: "path"  },
  { num: "08", c: 3, r: 3, kind: "path"  },
  { num: "09", c: 3, r: 4, kind: "path"  },
  { num: "10", c: 2, r: 4, kind: "path"  },
  { num: "11", c: 4, r: 4, kind: "omega" },
];

// Path order — locked
const HF_PATH_NUMS = ["03", "02", "01", "04", "05", "07", "06", "08", "10", "09", "11"];

// Wide lattice; 5×5 active near the right with 4 cols of breathing room beyond it.
// OX shifted from 19 → 17 (two cells left) to balance against the left-aligned hero copy.
const FULL_C = 26;
const FULL_R = 11;
const OX = 17;
const OY = 3;

function HeroFigure() {
  const [step, setStep] = React.useState(-1);

  React.useEffect(() => {
    const reduced = window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    // Mobile: skip the loop, render the final state (all 11 cells lit) statically.
    // The wide lattice is a desktop-only ornament; on phone the motion competes with
    // the type. Keep the visual, drop the loop.
    const isMobile = window.matchMedia('(max-width: 767px)').matches;
    if (reduced || isMobile) { setStep(HF_PATH_NUMS.length - 1); return; }

    const STEP_MS  = 320;
    const HOLD_MS  = 1400;
    const RESET_MS = 700;
    const N = HF_PATH_NUMS.length;
    const CYCLE_MS = N * STEP_MS + HOLD_MS + RESET_MS;

    let raf;
    let lastStep = -2;
    const t0 = performance.now();
    const tick = (now) => {
      const elapsed = (now - t0) % CYCLE_MS;
      let s;
      if (elapsed < N * STEP_MS)              s = Math.floor(elapsed / STEP_MS);
      else if (elapsed < N * STEP_MS + HOLD_MS) s = N - 1;
      else                                     s = -1;
      if (s !== lastStep) { lastStep = s; setStep(s); }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  const litNums = React.useMemo(
    () => new Set(step >= 0 ? HF_PATH_NUMS.slice(0, step + 1) : []),
    [step]
  );

  // Build full lattice — fade radiates from the 5×5 centre
  const cx = OX + 2;
  const cy = OY + 2;
  const activeMap = new Map(HF_CELLS.map(cell => [`${cell.c + OX},${cell.r + OY}`, cell]));
  const cells = [];
  for (let r = 0; r < FULL_R; r++) {
    for (let c = 0; c < FULL_C; c++) {
      const active = activeMap.get(c + "," + r);
      if (active) {
        cells.push({ kind: "active", c, r, ref: active });
        continue;
      }
      const inside = c >= OX && c < OX + 5 && r >= OY && r < OY + 5;
      if (inside) {
        cells.push({ kind: "empty", c, r });
      } else {
        const dx = c - cx;
        const dy = r - cy;
        const dist = Math.sqrt(dx * dx + dy * dy);
        const opacity = Math.max(0, Math.exp(-(dist - 1.6) / 2));
        cells.push({ kind: "ext", c, r, opacity });
      }
    }
  }

  return (
    <svg className="hero-figure"
         viewBox={`0 0 ${FULL_C * 10} ${FULL_R * 10}`}
         preserveAspectRatio="xMaxYMid slice"
         aria-label="Alpha Z mark — cells lighting up in α to Z order">
      {cells.map((cell, i) => {
        const x = cell.c * 10 + 1;
        const y = cell.r * 10 + 1;
        if (cell.kind === "ext") {
          return <rect key={i} className="hf-ext"
                       x={x} y={y} width="8" height="8"
                       style={{ opacity: cell.opacity }} />;
        }
        if (cell.kind === "empty") {
          return <rect key={i} className="hf-empty"
                       x={x} y={y} width="8" height="8" />;
        }
        const ref = cell.ref;
        const isLit = litNums.has(ref.num);
        return (
          <g key={i} className={"hf-cell-grp " + (isLit ? "is-lit" : "is-dim")}>
            <rect className={`hf-${ref.kind}`} x={x} y={y} width="8" height="8" />
          </g>
        );
      })}
    </svg>
  );
}

Object.assign(window, { HeroFigure });
