"use client";

import React, { useEffect, useRef, useState } from 'react';

const CustomCursor = () => {
    const innerRef = useRef<HTMLDivElement | null>(null);
    const outerRef = useRef<HTMLDivElement | null>(null);
    const rafRef = useRef<number | null>(null);

    // Mouse position state
    const mouseX = useRef(0);
    const mouseY = useRef(0);

    // Smoothed outer cursor position
    const outerX = useRef(0);
    const outerY = useRef(0);

    const [isDown, setIsDown] = useState(false);
    const [isHidden, setIsHidden] = useState(false);
    const [isHoveringLink, setIsHoveringLink] = useState(false);

    // 1. Core Logic for Movement & State
    useEffect(() => {
        const inner = innerRef.current;
        const outer = outerRef.current;
        if (!inner || !outer) return;

        const onMove = (e: MouseEvent | TouchEvent) => {
            const clientX = 'touches' in e ? e.touches[0].clientX : e.clientX;
            const clientY = 'touches' in e ? e.touches[0].clientY : e.clientY;

            mouseX.current = clientX;
            mouseY.current = clientY;

            // Inner cursor follows immediately
            inner.style.transform = `translate3d(${clientX}px, ${clientY}px, 0) translate(-50%, -50%)`;

            // Check if hovering a clickable element (using closest for robustness)
            const target = e.target as HTMLElement;
            // Expanded list of interactive elements
            const clickable = target.closest('a, button, input, textarea, select, [role="button"], .clickable');
            setIsHoveringLink(!!clickable);
        };

        const onDown = () => setIsDown(true);
        const onUp = () => setIsDown(false);
        const onLeave = () => setIsHidden(true);
        const onEnter = () => setIsHidden(false);

        // Animation Loop for Smooth Outer Cursor
        const animate = () => {
            const ease = 0.15; // Viscosity
            outerX.current += (mouseX.current - outerX.current) * ease;
            outerY.current += (mouseY.current - outerY.current) * ease;

            outer.style.transform = `translate3d(${outerX.current}px, ${outerY.current}px, 0) translate(-50%, -50%)`;
            rafRef.current = requestAnimationFrame(animate);
        };
        rafRef.current = requestAnimationFrame(animate);

        // Listeners
        window.addEventListener("mousemove", onMove, { passive: true });
        window.addEventListener("mousedown", onDown);
        window.addEventListener("mouseup", onUp);
        document.addEventListener("mouseleave", onLeave);
        document.addEventListener("mouseenter", onEnter);

        return () => {
            window.removeEventListener("mousemove", onMove);
            window.removeEventListener("mousedown", onDown);
            window.removeEventListener("mouseup", onUp);
            document.removeEventListener("mouseleave", onLeave);
            document.removeEventListener("mouseenter", onEnter);
            if (rafRef.current) cancelAnimationFrame(rafRef.current);
        };
    }, []);

    return (
        <>
            {/* Global Cursor Reset */}
            <style jsx global>{`
                /* Hide default cursor on body */
                body {
                    cursor: none;
                }
                
                /* Force default hand on interactive elements */
                a, button, input, textarea, select, [role="button"], .clickable {
                    cursor: pointer !important;
                }
                
                /* Force default hand on interactive elements  under a */
                a span, a p,a h1,a h2,a h3,a h4,a h5,a h6 {
                   cursor: pointer !important;
                }
                
                /* Text selection cursor */
                p, h1, h2, h3, h4, h5, h6, span {
                    cursor: text;
                }
            `}</style>

            {/* OUTER RING */}
            <div
                ref={outerRef}
                className="pointer-events-none fixed top-0 left-0 z-[9999] rounded-full border border-[#4a00e0] mix-blend-difference transition-opacity duration-300"
                style={{
                    width: isDown ? 60 : 30,
                    height: isDown ? 60 : 30,
                    opacity: isHidden || isHoveringLink ? 0 : 1, // Hide when hovering link
                    transition: "width 0.3s ease, height 0.3s ease, opacity 0.2s ease",
                    willChange: "transform, width, height"
                }}
            />

            {/* INNER DOT */}
            <div
                ref={innerRef}
                className="pointer-events-none fixed top-0 left-0 z-[10000] rounded-full bg-[#4a00e0] mix-blend-difference transition-opacity duration-300"
                style={{
                    width: isDown ? 10 : 8,
                    height: isDown ? 10 : 8,
                    opacity: isHidden || isHoveringLink ? 0 : 1, // Hide when hovering link
                    transition: "width 0.2s ease, height 0.2s ease, opacity 0.2s ease",
                    willChange: "transform, width, height"
                }}
            />
        </>
    );
};

export default CustomCursor;