'use client'

import { useMemo, useRef } from 'react'
import * as THREE from 'three'
import { buildChunkMesh } from '@/engine/voxel/meshBuilder'
import type { ChunkData } from '@/types'

interface ChunkMeshProps {
  chunk: ChunkData
  atlasTexture?: THREE.Texture | null
}

export function ChunkMesh({ chunk, atlasTexture }: ChunkMeshProps) {
  const meshRef = useRef<THREE.Mesh>(null)

  const geometry = useMemo(() => {
    const meshData = buildChunkMesh(chunk)
    if (!meshData) return null

    const geo = new THREE.BufferGeometry()
    geo.setAttribute('position', new THREE.BufferAttribute(meshData.vertices, 3))
    geo.setAttribute('normal', new THREE.BufferAttribute(meshData.normals, 3))
    geo.setAttribute('uv', new THREE.BufferAttribute(meshData.uvs, 2))
    geo.setAttribute('color', new THREE.BufferAttribute(meshData.colors, 3))
    geo.setIndex(new THREE.BufferAttribute(meshData.indices, 1))
    geo.computeBoundingSphere()

    return geo
  }, [chunk.position.x, chunk.position.z, chunk.meshVersion])

  if (!geometry) return null

  const material = atlasTexture
    ? new THREE.MeshLambertMaterial({
        map: atlasTexture,
        vertexColors: true,
        alphaTest: 0.1,
        transparent: false,
        side: THREE.FrontSide,
      })
    : new THREE.MeshLambertMaterial({ vertexColors: true })

  return (
    <mesh
      ref={meshRef}
      geometry={geometry}
      material={material}
      position={[chunk.position.x * 16, 0, chunk.position.z * 16]}
    />
  )
}
