import React, { useEffect, useRef } from 'react';

const ParticlesBackground: React.FC = () => {
    const canvasRef = useRef<HTMLCanvasElement>(null);
    const prevWidth = useRef(window.innerWidth);

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

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

        let animationFrameId: number;
        let particles: Particle[] = [];

        class Particle {
            x: number;
            y: number;
            size: number;
            speedX: number;
            speedY: number;
            color: string;

            constructor() {
                this.x = Math.random() * (canvas?.width || window.innerWidth);
                this.y = Math.random() * (canvas?.height || window.innerHeight);
                this.size = Math.random() * 4 + 2;
                this.speedX = Math.random() * 1 - 0.5;
                this.speedY = Math.random() * 1 - 0.5;
                this.color = `rgba(255, 255, 255, ${Math.random() * 0.3 + 0.1})`;
            }

            update() {
                // update position
                this.x += this.speedX;
                this.y += this.speedY;


                //size
                let sizeRng = Math.random();
                if (sizeRng > 0.75) {
                    this.size += Math.random() / 2;
                } else if (sizeRng < 0.25) {
                    this.size -= Math.random() / 2;
                }
                if (this.size < 2) {
                    this.size = 2;
                } else if (this.size > 6) {
                    this.size = 6;
                }

                if (canvas) {
                    if (this.x > canvas.width) this.x = 0;
                    if (this.x < 0) this.x = canvas.width;
                    if (this.y > canvas.height) this.y = 0;
                    if (this.y < 0) this.y = canvas.height;
                }
            }

            draw() {
                if (!ctx) return;
                ctx.fillStyle = this.color;
                ctx.beginPath();
                ctx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
                ctx.fill();
            }
        }

        const init = () => {
            if (!canvas) return;
            canvas.width = window.innerWidth;
            // Use logical height that works well with the 120vh style
            canvas.height = window.innerHeight;

            // Calculate particle count based on screen area (resolution)
            // Formula: sqrt(width * height) / factor
            // Desktop (1920x1080) -> ~120 particles
            // Mobile (390x844) -> ~48 particles
            // Mobile Landscape (844x390) -> ~48 particles (Same as portrait!)
            const area = canvas.width * canvas.height;
            const particleCount = Math.floor(Math.sqrt(area) / 12);

            particles = [];
            for (let i = 0; i < particleCount; i++) {
                particles.push(new Particle());
            }
        };

        const animate = () => {
            if (!ctx || !canvas) return;
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            // Draw a subtle gradient background for the canvas itself if needed, or keep transparent
            // For now, let's keep it transparent so we can style the container behind it if we want,
            // OR we can make this the definitive background.
            // Let's add a deep gradient here to match the user's previous aesthetic but cooler.
            const gradient = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
            gradient.addColorStop(0, '#0f0c29');
            gradient.addColorStop(0.5, '#302b63');
            gradient.addColorStop(1, '#24243e');
            ctx.fillStyle = gradient;
            ctx.fillRect(0, 0, canvas.width, canvas.height);


            particles.forEach((particle) => {
                particle.update();
                particle.draw();
            });

            // Connect particles with lines if close
            connect();

            animationFrameId = requestAnimationFrame(animate);
        };

        const connect = () => {
            if (!ctx) return;
            for (let a = 0; a < particles.length; a++) {
                for (let b = a; b < particles.length; b++) {
                    const dx = particles[a].x - particles[b].x;
                    const dy = particles[a].y - particles[b].y;
                    const distance = Math.sqrt(dx * dx + dy * dy);
                    const sizeAverage = (particles[a].size + particles[b].size) / 2;
                    // Scale from 100 to 300 based on size average (2 to 6)
                    const distanceThreshold = 100 + (sizeAverage - 2) * 50;

                    if (distance < distanceThreshold) {
                        ctx.strokeStyle = `rgba(255, 255, 255, ${(distanceThreshold * (2 / 3) * .001) - distance / 1000})`;
                        ctx.lineWidth = sizeAverage;
                        ctx.beginPath();
                        ctx.moveTo(particles[a].x, particles[a].y);
                        ctx.lineTo(particles[b].x, particles[b].y);
                        ctx.stroke();
                    }
                }
            }
        }

        init();
        animate();

        const handleResize = () => {
            // Ignore vertical-only resizes (addressing mobile browser bar toggle issue)
            if (window.innerWidth === prevWidth.current) {
                return;
            }
            prevWidth.current = window.innerWidth;
            init();
        }

        window.addEventListener('resize', handleResize);

        return () => {
            window.removeEventListener('resize', handleResize);
            cancelAnimationFrame(animationFrameId);
        };
    }, []);

    return (
        <canvas
            ref={canvasRef}
            style={{
                position: 'fixed',
                top: 0,
                left: 0,
                width: '100%',
                height: '120vh', // Extend well below viewport to cover mobile browser bar retraction
                zIndex: -1, // Behind everything
            }}
        />
    );
};

export default ParticlesBackground;
