// Shared section shell + small primitives
const { useState, useEffect, useRef, useMemo } = React;

function Section({ id, refno, children, style }) {
  return (
    <section id={id} className="section" style={style}>
      <div className="section__rail">
        <span className="section__refno">{refno}</span>
      </div>
      <div className="section__inner">{children}</div>
    </section>
  );
}

function Label({ children }) {
  return (
    <div className="section-label">
      <span className="dot" />
      <span>{children}</span>
    </div>
  );
}

function IntroAtom() {
  // El intro solo corre UNA vez por sesión. En mobile, iOS Safari descarta la
  // pestaña de memoria tras inactividad y recarga la página al volver; sin esto
  // el átomo reaparecería a media lectura. sessionStorage sobrevive ese reload.
  const [done, setDone] = useState(() => {
    try { return sessionStorage.getItem('roark_intro_done') === '1'; }
    catch (e) { return false; }
  });

  const markDone = () => {
    try { sessionStorage.setItem('roark_intro_done', '1'); } catch (e) {}
    setDone(true);
  };

  // 36 ticks alrededor del perímetro — mismo vocabulario del HeroAtom
  const ticks = useMemo(() => {
    const arr = [];
    for (let i = 0; i < 36; i++) {
      const a = (i / 36) * Math.PI * 2;
      const r1 = 196;
      const r2 = i % 4 === 0 ? 208 : 202;
      arr.push({
        x1: 240 + Math.cos(a) * r1,
        y1: 240 + Math.sin(a) * r1,
        x2: 240 + Math.cos(a) * r2,
        y2: 240 + Math.sin(a) * r2,
        major: i % 4 === 0,
        delay: 200 + i * 6,
      });
    }
    return arr;
  }, []);

  useEffect(() => {
    if (done) return;
    if (typeof window !== 'undefined' && window.matchMedia &&
        window.matchMedia('(prefers-reduced-motion: reduce)').matches) {
      markDone();
      return;
    }
    const t = setTimeout(markDone, 1500);
    return () => clearTimeout(t);
  }, []);

  if (done) return null;

  return (
    <div className="intro-atom" aria-hidden="true">
      <div className="intro-atom__bg" />
      <div className="intro-atom__corners">
        <span className="intro-atom__corner intro-atom__corner--tl">FIG·00 · CALIBRANDO</span>
        <span className="intro-atom__corner intro-atom__corner--tr">R-MX · 2026</span>
        <span className="intro-atom__corner intro-atom__corner--bl">ESC 1:1</span>
        <span className="intro-atom__corner intro-atom__corner--br">SISTEMA·OPERACIONAL</span>
      </div>
      <svg className="intro-atom__svg" viewBox="0 0 480 480" xmlns="http://www.w3.org/2000/svg" aria-hidden="true">
        {/* crosshair lines — extienden desde el centro */}
        <line className="intro-atom__hair intro-atom__hair--h" x1="240" y1="240" x2="240" y2="240" stroke="#36342f" strokeWidth="0.6" strokeDasharray="2 4" />
        <line className="intro-atom__hair intro-atom__hair--v" x1="240" y1="240" x2="240" y2="240" stroke="#36342f" strokeWidth="0.6" strokeDasharray="2 4" />

        {/* outer ring — se dibuja */}
        <circle className="intro-atom__ring-outer" cx="240" cy="240" r="180" fill="none" stroke="#ffffff" strokeWidth="1" />

        {/* dashed inner ring */}
        <circle className="intro-atom__ring-dash" cx="240" cy="240" r="138" fill="none" stroke="#ffffff" strokeWidth="0.6" strokeDasharray="3 4" />

        {/* dos elipses cruzadas */}
        <ellipse className="intro-atom__ellipse intro-atom__ellipse--a" cx="240" cy="240" rx="200" ry="90" fill="none" stroke="#1f3c90" strokeWidth="0.8" strokeDasharray="2 3" transform="rotate(28 240 240)" />
        <ellipse className="intro-atom__ellipse intro-atom__ellipse--b" cx="240" cy="240" rx="200" ry="90" fill="none" stroke="#ffffff" strokeWidth="0.6" strokeDasharray="2 3" transform="rotate(-28 240 240)" />

        {/* tick marks alrededor */}
        <g className="intro-atom__ticks">
          {ticks.map((t, i) => (
            <line
              key={i}
              x1={t.x1} y1={t.y1} x2={t.x2} y2={t.y2}
              stroke={t.major ? "#ffffff" : "#5a5853"}
              strokeWidth={t.major ? 1 : 0.6}
              style={{ animationDelay: `${t.delay}ms` }}
            />
          ))}
        </g>

        {/* core */}
        <circle className="intro-atom__core" cx="240" cy="240" r="0" fill="#ffffff" />
        <circle className="intro-atom__core-pulse" cx="240" cy="240" r="46" fill="none" stroke="#ffffff" strokeWidth="1" />

        {/* 3 partículas orbitando */}
        <circle className="intro-atom__particle intro-atom__particle--1" cx="420" cy="240" r="4" fill="#e94e1b" />
        <circle className="intro-atom__particle intro-atom__particle--2" cx="120" cy="148" r="3" fill="#ffffff" />
        <circle className="intro-atom__particle intro-atom__particle--3" cx="332" cy="372" r="3" fill="#1f3c90" />
      </svg>
    </div>
  );
}

function ScrollHint() {
  const [visible, setVisible] = useState(true);

  useEffect(() => {
    const onScroll = () => {
      setVisible(window.scrollY < 80);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  return (
    <a
      href="#filtro"
      className={"scroll-hint" + (visible ? "" : " scroll-hint--hidden")}
      aria-label="Scroll hacia abajo"
    >
      <svg width="24" height="14" viewBox="0 0 24 14" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <polyline points="2 2 12 12 22 2" />
      </svg>
    </a>
  );
}

Object.assign(window, { Section, Label, IntroAtom, ScrollHint });
