import { useEffect, useRef } from "react";

interface Point {
  x: number;
  y: number;
  px: number;
  py: number;
}

export default function TubesCursor() {
  const canvasRef = useRef<HTMLCanvasElement | null>(null);

  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;

    const ctx = canvas.getContext("2d");
    if (!ctx) return;

    let width = (canvas.width = window.innerWidth);
    let height = (canvas.height = window.innerHeight);

    // Dynamic sizing helper
    const handleResize = () => {
      width = canvas.width = window.innerWidth;
      height = canvas.height = window.innerHeight;
    };
    window.addEventListener("resize", handleResize);

    // Simulation settings
    const pointsCount = 8;
    const trailPoints: Point[] = [];
    const mouse = { x: width / 2, y: height / 2, active: false };

    // Initialize points with default coordinates
    for (let i = 0; i < pointsCount; i++) {
      trailPoints.push({
        x: width / 2,
        y: height / 2,
        px: width / 2,
        py: height / 2,
      });
    }

    const handleMouseMove = (e: MouseEvent) => {
      mouse.x = e.clientX;
      mouse.y = e.clientY;
      mouse.active = true;
    };

    const handleMouseLeave = () => {
      mouse.active = false;
    };

    const handleTouchStart = (e: TouchEvent) => {
      if (e.touches.length > 0) {
        mouse.x = e.touches[0].clientX;
        mouse.y = e.touches[0].clientY;
        mouse.active = true;
      }
    };

    const handleTouchMove = (e: TouchEvent) => {
      if (e.touches.length > 0) {
        mouse.x = e.touches[0].clientX;
        mouse.y = e.touches[0].clientY;
        mouse.active = true;
      }
    };

    const handleTouchEnd = () => {
      mouse.active = false;
    };

    window.addEventListener("mousemove", handleMouseMove, { passive: true });
    document.addEventListener("mouseleave", handleMouseLeave, { passive: true });
    window.addEventListener("touchstart", handleTouchStart, { passive: true });
    window.addEventListener("touchmove", handleTouchMove, { passive: true });
    window.addEventListener("touchend", handleTouchEnd, { passive: true });

    let animationFrameId: number;
    let activeAlpha = 0;

    const render = () => {
      if (!ctx || !canvas) return;

      ctx.clearRect(0, 0, width, height);

      // Smooth opacity fade depending on interactive activity
      if (mouse.active) {
        activeAlpha = Math.min(1, activeAlpha + 0.08);
      } else {
        activeAlpha = Math.max(0, activeAlpha - 0.04);
      }

      // Spring physics to drag points smoothly like water/liquid in a flexible tube
      let targetX = mouse.x;
      let targetY = mouse.y;

      for (let i = 0; i < pointsCount; i++) {
        const pt = trailPoints[i];
        
        // Elastic drag factor: first elements follow mouse quickly, tail points drag slowly
        const strength = i === 0 ? 0.35 : 0.28;
        const dx = targetX - pt.x;
        const dy = targetY - pt.y;

        pt.px = pt.x;
        pt.py = pt.y;
        pt.x += dx * strength;
        pt.y += dy * strength;

        targetX = pt.x;
        targetY = pt.y;
      }

      // Draw the "tube" pipeline trail with highlights
      if (activeAlpha > 0) {
        // Draw 3 layers for 3D volumetric glass/metal metallic pipeline illusion

        // 1. Outer Glow Ray (Broad soft colored blur)
        ctx.beginPath();
        ctx.lineCap = "round";
        ctx.lineJoin = "round";
        ctx.lineWidth = 8;
        ctx.strokeStyle = `rgba(242, 183, 5, ${0.08 * activeAlpha})`;
        ctx.moveTo(trailPoints[0].x, trailPoints[0].y);
        for (let i = 1; i < pointsCount - 1; i++) {
          const xc = (trailPoints[i].x + trailPoints[i + 1].x) / 2;
          const yc = (trailPoints[i].y + trailPoints[i + 1].y) / 2;
          ctx.quadraticCurveTo(trailPoints[i].x, trailPoints[i].y, xc, yc);
        }
        ctx.stroke();

        // 2. Main Copper/Yellow Conduit Core
        ctx.beginPath();
        ctx.lineCap = "round";
        ctx.lineJoin = "round";
        ctx.lineWidth = 3.5;
        ctx.strokeStyle = `rgba(242, 183, 5, ${0.75 * activeAlpha})`;
        ctx.moveTo(trailPoints[0].x, trailPoints[0].y);
        for (let i = 1; i < pointsCount - 1; i++) {
          const xc = (trailPoints[i].x + trailPoints[i + 1].x) / 2;
          const yc = (trailPoints[i].y + trailPoints[i + 1].y) / 2;
          ctx.quadraticCurveTo(trailPoints[i].x, trailPoints[i].y, xc, yc);
        }
        ctx.stroke();

        // 3. Inner Specular liquid flow highlight (Bright white/gold core)
        ctx.beginPath();
        ctx.lineCap = "round";
        ctx.lineJoin = "round";
        ctx.lineWidth = 1;
        ctx.strokeStyle = `rgba(255, 255, 255, ${0.9 * activeAlpha})`;
        ctx.moveTo(trailPoints[0].x, trailPoints[0].y);
        for (let i = 1; i < pointsCount - 1; i++) {
          const xc = (trailPoints[i].x + trailPoints[i + 1].x) / 2;
          const yc = (trailPoints[i].y + trailPoints[i + 1].y) / 2;
          ctx.quadraticCurveTo(trailPoints[i].x, trailPoints[i].y, xc, yc);
        }
        ctx.stroke();

        // Draw a tiny subtle glowing "joint" or "fastener" ring at coordinates
        for (let i = 0; i < pointsCount - 1; i += 3) {
          const pt = trailPoints[i];
          ctx.beginPath();
          ctx.arc(pt.x, pt.y, 2.5, 0, Math.PI * 2);
          ctx.fillStyle = `rgba(255, 255, 255, ${activeAlpha})`;
          ctx.shadowBlur = 3 * activeAlpha;
          ctx.shadowColor = "#F2B705";
          ctx.fill();
          ctx.shadowBlur = 0; // reset
        }
      }

      animationFrameId = requestAnimationFrame(render);
    };

    render();

    return () => {
      window.removeEventListener("resize", handleResize);
      window.removeEventListener("mousemove", handleMouseMove);
      document.removeEventListener("mouseleave", handleMouseLeave);
      window.removeEventListener("touchstart", handleTouchStart);
      window.removeEventListener("touchmove", handleTouchMove);
      window.removeEventListener("touchend", handleTouchEnd);
      cancelAnimationFrame(animationFrameId);
    };
  }, []);

  return (
    <canvas
      ref={canvasRef}
      id="canvas-tubes-cursor"
      className="fixed inset-0 w-full h-full pointer-events-none z-50 mix-blend-screen opacity-90 hidden sm:block"
    />
  );
}
