import { useFrame } from "@react-three/fiber";
import { useEffect, useRef } from "react";
import * as THREE from "three"

export default function GroupStar() {  

  const loader = new THREE.TextureLoader();
  const flash1 = loader.load('/assets/textures/blueFlash.png');
  const flash2 = loader.load('/assets/textures/redFlash.png');

  const ref = useRef<any>(null)

  const flashMaterials = [
    new THREE.SpriteMaterial( { 
      map: flash1, 
      color:0xaaaabb,
    }),
    new THREE.SpriteMaterial( { 
      map: flash2, 
      color:0xeedddd,
    })
  ]

  useEffect(()=>{
    if(ref.current){
      if(ref.current.children.length === 0){
        for ( let i = 0; i < 400; i++ ) {
          let star = new THREE.Sprite(flashMaterials[i % 2]);
          star.scale.setScalar(3)
          star.position.x = Math.random() * 500 - 250
          star.position.y = Math.random() * 500 - 250
          star.position.z = Math.random() * 500 - 250
          star.renderOrder = 10
          ref.current.add(star)
        }
      }
    }
  },[])

  useFrame((state)=>{
    if(ref.current){
      const t = state.clock.getElapsedTime()
      ref.current.rotation.y = 0.3 * Math.sin(t*0.1)
    }
  })

  return (
    <group name="GroupStar" ref = {ref}/>
  )
}