// Convergence loader — beams slide in, white inset opens, shu key locks.

const LoaderConvergence = ({ size = 120, t, bg = "#FAF7F0" }) => {
  const easeOut = (x) => 1 - Math.pow(1 - Math.max(0, Math.min(1, x)), 3);
  const beamP = easeOut(t / 900);
  const wellP = easeOut((t - 700) / 350);
  const keyP = easeOut((t - 950) / 400);
  const off = (1 - beamP) * 70;

  return (
    <svg viewBox="0 0 100 100" width={size} height={size}>
      <rect x={37} y={-off} width={26} height={100 + off * 2} fill="#1B2845" opacity={beamP} />
      <rect x={-off} y={37} width={100 + off * 2} height={26} fill="#1B2845" opacity={beamP} />
      {wellP > 0 && (
        <rect
          x={50 - 15 * wellP}
          y={50 - 15 * wellP}
          width={30 * wellP}
          height={30 * wellP}
          fill={bg}
        />
      )}
      {keyP > 0 && (
        <rect
          x={50 - 9 * keyP}
          y={50 - 9 * keyP}
          width={18 * keyP}
          height={18 * keyP}
          fill="#B04A3A"
        />
      )}
    </svg>
  );
};

const Loader = ({ size = 120, bg = "#FAF7F0" }) => {
  const [t, setT] = React.useState(0);
  React.useEffect(() => {
    const start = performance.now();
    let raf;
    const tick = (now) => {
      setT(now - start);
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);
  return <LoaderConvergence size={size} t={t} bg={bg} />;
};

const LoaderScreen = ({ onDone, duration = 1800, bg = "#FAF7F0" }) => {
  const [done, setDone] = React.useState(false);

  // Single source of truth: parent's `loading` state controls when this
  // component unmounts (via onDone). We only drive the fade locally.
  React.useEffect(() => {
    const t1 = setTimeout(() => setDone(true), duration);
    const t2 = setTimeout(() => {
      onDone && onDone();
    }, duration + 600);
    return () => {
      clearTimeout(t1);
      clearTimeout(t2);
    };
  }, [duration]);

  return (
    <div
      style={{
        position: "fixed",
        inset: 0,
        background: bg,
        zIndex: 9999,
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        justifyContent: "center",
        gap: "32px",
        opacity: done ? 0 : 1,
        transition: "opacity 600ms cubic-bezier(.22,1,.36,1)",
        pointerEvents: done ? "none" : "auto",
      }}
    >
      <Loader size={140} bg={bg} />
      <div
        style={{
          fontFamily: '"IBM Plex Mono", monospace',
          fontSize: "10px",
          letterSpacing: "1.5px",
          color: "#8B8276",
          textTransform: "uppercase",
        }}
      >
        kigumi · structure without force
      </div>
    </div>
  );
};

Object.assign(window, { Loader, LoaderScreen });
