/* Shared atoms — logo, marker, reveal hook */
const Logo = ({ size = 18 }) => (
  <span className="logo-mark" style={{ width: size, height: size }}>
    <svg viewBox="0 0 18 18" fill="none">
      <rect x="0.5" y="0.5" width="17" height="17" stroke="currentColor" strokeWidth="1" />
      <rect x="4.5" y="4.5" width="9" height="9" stroke="currentColor" strokeWidth="1" />
      <rect x="8" y="8" width="2" height="2" fill="currentColor" />
    </svg>
  </span>
);

const Marker = ({ section, label }) => (
  <div className="marker">
    <span className="glyph">§</span>
    <span>{section}</span>
    <span style={{ color: "var(--fg-faint)" }}>/</span>
    <span>{label}</span>
  </div>
);

const Status = ({ tone = "ok", children }) => (
  <span className={`status ${tone === "ok" ? "" : tone}`}>
    <span className="dot" />
    {children}
  </span>
);

const useReveal = () => {
  React.useEffect(() => {
    const els = document.querySelectorAll(".reveal");
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) {
            e.target.classList.add("in");
            io.unobserve(e.target);
          }
        });
      },
      { threshold: 0.12, rootMargin: "0px 0px -8% 0px" }
    );
    els.forEach((el) => io.observe(el));
    return () => io.disconnect();
  }, []);
};

const useScrollProgress = (ref) => {
  const [p, setP] = React.useState(0);
  React.useEffect(() => {
    const onScroll = () => {
      if (!ref.current) return;
      const r = ref.current.getBoundingClientRect();
      const vh = window.innerHeight;
      // 0 when section top hits bottom of viewport, 1 when section bottom hits top
      const total = r.height + vh;
      const traveled = vh - r.top;
      const v = Math.max(0, Math.min(1, traveled / total));
      setP(v);
    };
    onScroll();
    window.addEventListener("scroll", onScroll, { passive: true });
    window.addEventListener("resize", onScroll);
    return () => {
      window.removeEventListener("scroll", onScroll);
      window.removeEventListener("resize", onScroll);
    };
  }, [ref]);
  return p;
};

const Crosshairs = ({ corners = "all" }) => {
  const positions = {
    tl: { top: -4, left: -4 },
    tr: { top: -4, right: -4 },
    bl: { bottom: -4, left: -4 },
    br: { bottom: -4, right: -4 },
  };
  const which = corners === "all" ? ["tl", "tr", "bl", "br"] : corners;
  return (
    <>
      {which.map((c) => (
        <span key={c} className="crosshair" style={positions[c]} />
      ))}
    </>
  );
};

Object.assign(window, { Logo, Marker, Status, useReveal, useScrollProgress, Crosshairs });
