"use client";

import React, { useEffect, useRef, useState } from "react";
import dynamic from "next/dynamic";

// Workflow 3 is the heaviest, last-on-page section (the Strategy 3D experience +
// its WebGL canvas chunk). It's kept OFF the initial render/compile critical path:
// dynamically imported (ssr:false) and only mounted once the user scrolls within
// ~1.5 viewports of it. Until then we reserve a min-height so the page scroll
// length stays roughly stable and the mount (which happens well below the fold)
// never shifts what the user is currently looking at.
const Workflow3 = dynamic(() => import("./Workflow3"), { ssr: false, loading: () => null });

export default function Workflow3Lazy() {
  const sentinelRef = useRef<HTMLDivElement>(null);
  const [show, setShow] = useState(false);

  useEffect(() => {
    const el = sentinelRef.current;
    if (!el) return;
    const io = new IntersectionObserver(
      (entries) => {
        if (entries.some((e) => e.isIntersecting)) {
          setShow(true);
          io.disconnect();
        }
      },
      // Mount well before it enters the viewport so the canvas + GLBs preload
      // and ScrollTrigger is ready by the time the user reaches it.
      { rootMargin: "150% 0px" },
    );
    io.observe(el);
    return () => io.disconnect();
  }, []);

  if (!show) {
    // Placeholder reserves a viewport of height; the real section (much taller)
    // expands below the fold once mounted, far from the user's current position.
    return <div ref={sentinelRef} aria-hidden style={{ minHeight: "100vh" }} />;
  }
  // `display: contents` so this wrapper adds no box of its own — Workflow3 keeps
  // its exact layout/seam with the section above it.
  return (
    <div ref={sentinelRef} style={{ display: "contents" }}>
      <Workflow3 />
    </div>
  );
}
