// Veloen entry splash — covers from first render, draws SVG, shrinks to header

function VeloenSplash() {
  // Synchronously decide whether to show splash, so first paint covers main content
  const [stage, setStage] = React.useState(() => {
    try {
      if (sessionStorage.getItem("veloen-intro-shown") === "1") return "done";
    } catch (e) {}
    return "cover"; // dark overlay only, awaiting SVG
  });
  const [svgContent, setSvgContent] = React.useState("");
  const rootRef = React.useRef(null);

  // Load SVG asynchronously, then start animation
  React.useEffect(() => {
    if (stage === "done") return;
    fetch("photos/veloen-logo.svg")
      .then(r => r.text())
      .then(raw => {
        const m = raw.match(/<svg[\s\S]*<\/svg>/i);
        setSvgContent(m ? m[0] : raw);
        setStage("draw");
      })
      .catch(() => {
        setStage("done");
        try { sessionStorage.setItem("veloen-intro-shown", "1"); } catch (e) {}
      });
  }, []);

  // Once SVG is in DOM (stage=draw), measure paths and trigger animation
  React.useLayoutEffect(() => {
    if (stage !== "draw") return;
    const root = rootRef.current;
    if (!root) return;
    const paths = Array.from(root.querySelectorAll(".veloen-splash-logo path"));
    if (paths.length === 0) return;

    const arr = paths.map(p => {
      let x = 0;
      try { x = p.getBBox().x; } catch (e) {}
      return { p, x };
    }).sort((a, b) => a.x - b.x);

    const STAGGER_MS = 350;

    arr.forEach(({ p }, i) => {
      let len = 0;
      try { len = p.getTotalLength(); } catch (e) {}
      if (!len) len = 2000;
      p.style.setProperty("--len", len);
      p.style.setProperty("--delay", (i * STAGGER_MS) + "ms");
      p.style.strokeDasharray = len;
      p.style.strokeDashoffset = len;
      p.style.fillOpacity = 0;
    });

    void root.offsetWidth;
    root.classList.add("anim");

    const totalAnim = (arr.length - 1) * STAGGER_MS + 1800;

    const shrinkT = setTimeout(() => setStage("shrink"), totalAnim + 200);
    const doneT = setTimeout(() => {
      setStage("done");
      try { sessionStorage.setItem("veloen-intro-shown", "1"); } catch (e) {}
    }, totalAnim + 1400);

    return () => { clearTimeout(shrinkT); clearTimeout(doneT); };
  }, [stage]);

  if (stage === "done") return null;

  const cls = "veloen-splash stage-" + stage;

  return (
    <div ref={rootRef} className={cls}>
      {svgContent && (
        <div
          className="veloen-splash-logo"
          dangerouslySetInnerHTML={{ __html: svgContent }}
        />
      )}
    </div>
  );
}

window.VeloenSplash = VeloenSplash;
