'use client';

import { useEffect, useRef } from 'react';

type OasisCanvasProps = {
  mode?: 'loop' | 'live';
};

export function OasisCanvas({ mode = 'loop' }: OasisCanvasProps) {
  const frameRef = useRef<HTMLIFrameElement | null>(null);

  useEffect(() => {
    if (mode !== 'live') return;

    const dispatchNativeMouseEvent = (type: 'mousemove' | 'mouseleave', event?: PointerEvent) => {
      const frameWindow = frameRef.current?.contentWindow;
      if (!frameWindow) return false;

      try {
        const nativeEvent = new MouseEvent(type, {
          bubbles: true,
          cancelable: false,
          clientX: event?.clientX ?? 99999,
          clientY: event?.clientY ?? 99999,
          screenX: event?.screenX ?? 99999,
          screenY: event?.screenY ?? 99999,
          buttons: event?.buttons ?? 0,
          view: frameWindow,
        });
        frameWindow.dispatchEvent(nativeEvent);
        return true;
      } catch {
        return false;
      }
    };

    const sendPointer = (type: 'pointermove' | 'pointerleave', event?: PointerEvent) => {
      const frameWindow = frameRef.current?.contentWindow;
      if (!frameWindow) return;
      dispatchNativeMouseEvent(type === 'pointermove' ? 'mousemove' : 'mouseleave', event);
      frameWindow.postMessage(
        {
          type: `skg-oasis-${type}`,
          x: event?.clientX ?? 99999,
          y: event?.clientY ?? 99999,
        },
        window.location.origin,
      );
    };

    const onPointerMove = (event: PointerEvent) => sendPointer('pointermove', event);
    const onPointerLeave = () => sendPointer('pointerleave');
    const listenerOptions = { capture: true, passive: true };

    document.addEventListener('pointermove', onPointerMove, listenerOptions);
    window.addEventListener('pointerleave', onPointerLeave, listenerOptions);
    return () => {
      document.removeEventListener('pointermove', onPointerMove, listenerOptions);
      window.removeEventListener('pointerleave', onPointerLeave, listenerOptions);
    };
  }, [mode]);

  if (mode === 'loop') {
    return (
      <div aria-hidden="true" className="login-oasis-loop">
        <div className="oasis-loop__sky" />
        <div className="oasis-loop__light" />
        <div className="oasis-loop__haze" />
        <div className="oasis-loop__grass oasis-loop__grass--back" />
        <div className="oasis-loop__grass oasis-loop__grass--front" />
        <div className="oasis-loop__grain" />
      </div>
    );
  }

  return (
    <iframe
      ref={frameRef}
      allow="webgpu; fullscreen"
      aria-hidden="true"
      className="login-oasis-canvas"
      loading="eager"
      src="/oasis-source/index.html?v=login-pointer-0515"
    />
  );
}
