import React, { useRef, useMemo } from 'react';
import { useFrame, useThree } from '@react-three/fiber';
import { Mesh } from 'three';

export const GelColon: React.FC<{ position: [number, number, number] }> = ({ position }) => {
    const { viewport } = useThree();
    const isPortrait = viewport.height > viewport.width;

    const dotsRef = useRef<(Mesh | null)[]>([]);

    useFrame(({ clock }) => {
        const time = clock.getElapsedTime() * 3;

        dotsRef.current.forEach((dot, index) => {
            if (!dot) return;

            const phase = index * 0.5;
            const wave = Math.sin(time - phase);
            const opacity = 0.3 + (wave + 1) * 0.35;

            if (dot.material && 'opacity' in dot.material) {
                // @ts-ignore
                dot.material.opacity = opacity;
            }
        });
    });

    const dotConfig = useMemo(() => {
        if (isPortrait) {
            return [
                { id: 0, pos: [-0.6, 0, 0] },
                { id: 1, pos: [-0.2, 0, 0] },
                { id: 2, pos: [0.2, 0, 0] },
                { id: 3, pos: [0.6, 0, 0] },
            ];
        } else {
            return [
                { id: 0, pos: [0, 0.5, 0] },
                { id: 1, pos: [0, -0.5, 0] },
            ];
        }
    }, [isPortrait]);

    return (
        <group position={position}>
            {dotConfig.map((config, index) => (
                <mesh
                    key={config.id}
                    ref={(el) => (dotsRef.current[index] = el)}
                    position={config.pos as [number, number, number]}
                >
                    <sphereGeometry args={[0.25, 32, 32]} />
                    <meshPhysicalMaterial
                        color="#F48FB1"
                        emissive="#F06292"
                        emissiveIntensity={0.2}
                        transmission={0.95}
                        roughness={0.15}
                        thickness={2.5}
                        clearcoat={1}
                        clearcoatRoughness={0.2}
                        transparent
                    />
                </mesh>
            ))}
        </group>
    );
};
