"use client";

/**
 * @file hud.depth-sync.tsx
 * @description Neural Depth Sync Shader — Phase 007.2
 * Synchronizes glass parallax + glow motion across all HUD panels.
 */

import React, {
  createContext,
  useContext,
  useEffect,
  useState,
  PropsWithChildren,
} from "react";
import { motion } from "framer-motion";

interface DepthContextValue {
  x: number;
  y: number;
  intensity: number;
}
const DepthContext = createContext<DepthContextValue>({
  x: 0,
  y: 0,
  intensity: 0.5,
});

export const useDepthField = () => useContext(DepthContext);

/* 🌐 Provider: broadcasts unified neural lighting field */
export const DepthProvider: React.FC<PropsWithChildren> = ({ children }) => {
  const [coords, setCoords] = useState({ x: 0, y: 0, intensity: 0.5 });

  useEffect(() => {
    const handleMove = (e: MouseEvent) => {
      const { innerWidth, innerHeight } = window;
      const nx = (e.clientX / innerWidth) * 2 - 1;
      const ny = (e.clientY / innerHeight) * 2 - 1;
      const dist = Math.sqrt(nx * nx + ny * ny);
      setCoords({ x: nx, y: ny, intensity: 1 - Math.min(dist, 1) });
    };
    window.addEventListener("mousemove", handleMove);
    return () => window.removeEventListener("mousemove", handleMove);
  }, []);

  return (
    <DepthContext.Provider value={coords}>{children}</DepthContext.Provider>
  );
};

/* ✨ Hook: computes motion style */
export const useDepthMotion = (factor = 10): React.CSSProperties => {
  const { x, y, intensity } = useDepthField();
  const translateX = x * factor;
  const translateY = y * factor;
  const glow = 0.3 + intensity * 0.4;

  return {
    transform: `translate3d(${translateX}px, ${translateY}px, 0)`,
    boxShadow: `0 0 ${25 + intensity * 40}px rgba(0,255,255,${glow})`,
    transition: "transform 0.2s ease-out, box-shadow 0.3s ease-out",
  };
};

/* 🎛️ DepthReactiveGlass */
export const DepthReactiveGlass: React.FC<
  PropsWithChildren<{ strength?: number }>
> = ({ children, strength = 10 }) => {
  const depthStyle = useDepthMotion(strength);
  return (
    <motion.div
      className="relative rounded-[24px] bg-[rgba(0,12,24,0.65)]
                 backdrop-blur-[20px] backdrop-saturate-[180%]
                 ring-1 ring-cyan-400/10 shadow-[0_0_30px_rgba(0,255,255,0.25)]
                 overflow-hidden"
      style={depthStyle}
    >
      {children}
    </motion.div>
  );
};
