"use client"

import { useRef } from "react"
import { useFrame } from "@react-three/fiber"
import type { Group } from "three"

const domains = [
  { name: "Core", color: "#EF4444", position: [0, 0, 0] },
  { name: "User", color: "#3B82F6", position: [-2, 1, 0] },
  { name: "Product", color: "#10B981", position: [2, 1, 0] },
  { name: "Order", color: "#F59E0B", position: [-1, -1.5, 0] },
  { name: "Payment", color: "#8B5CF6", position: [1, -1.5, 0] },
  { name: "Shared", color: "#6B7280", position: [0, 2.5, 0] },
]

function Hexagon({ position, color, name }: { position: [number, number, number]; color: string; name: string }) {
  const meshRef = useRef<Group>(null)

  useFrame((state) => {
    if (meshRef.current) {
      meshRef.current.rotation.z = Math.sin(state.clock.elapsedTime + position[0]) * 0.1
      meshRef.current.position.y = position[1] + Math.sin(state.clock.elapsedTime * 0.5 + position[0]) * 0.1
    }
  })

  return (
    <group ref={meshRef} position={position}>
      <mesh>
        <cylinderGeometry args={[0.8, 0.8, 0.2, 6]} />
        <meshStandardMaterial color={color} />
      </mesh>
      <mesh position={[0, 0.15, 0]}>
        <cylinderGeometry args={[0.7, 0.7, 0.05, 6]} />
        <meshStandardMaterial color="#FFFFFF" />
      </mesh>
    </group>
  )
}

export function HexagonGrid() {
  return (
    <group>
      {domains.map((domain, index) => (
        <Hexagon
          key={index}
          position={domain.position as [number, number, number]}
          color={domain.color}
          name={domain.name}
        />
      ))}

      {/* Connection lines */}
      {domains.slice(1).map((domain, index) => (
        <mesh key={`line-${index}`} position={[domain.position[0] / 2, domain.position[1] / 2, 0]}>
          <cylinderGeometry args={[0.02, 0.02, Math.sqrt(domain.position[0] ** 2 + domain.position[1] ** 2)]} />
          <meshStandardMaterial color="#D1D5DB" />
        </mesh>
      ))}
    </group>
  )
}
