1"use client"
2
3import React, { useEffect, useRef, useState } from "react"
4import { renderToString } from "react-dom/server"
5
6interface Icon {
7 x: number
8 y: number
9 z: number
10 scale: number
11 opacity: number
12 id: number
13}
14
15interface IconCloudProps {
16 icons?: React.ReactNode[]
17 images?: string[]
18}
19
20function easeOutCubic(t: number): number {
21 return 1 - Math.pow(1 - t, 3)
22}
23
24export function IconCloud({ icons, images }: IconCloudProps) {
25 const canvasRef = useRef<HTMLCanvasElement>(null)
26 const [iconPositions, setIconPositions] = useState<Icon[]>([])
27 const [isDragging, setIsDragging] = useState(false)
28 const [lastMousePos, setLastMousePos] = useState({ x: 0, y: 0 })
29 const [mousePos, setMousePos] = useState({ x: 0, y: 0 })
30 const [targetRotation, setTargetRotation] = useState<{
31 x: number
32 y: number
33 startX: number
34 startY: number
35 distance: number
36 startTime: number
37 duration: number
38 } | null>(null)
39 const animationFrameRef = useRef<number>(0)
40 const rotationRef = useRef({ x: 0, y: 0 })
41 const iconCanvasesRef = useRef<HTMLCanvasElement[]>([])
42 const imagesLoadedRef = useRef<boolean[]>([])
43
44 // Create icon canvases once when icons/images change
45 useEffect(() => {
46 if (!icons && !images) return
47
48 const items = icons ?? images ?? []
49 imagesLoadedRef.current = new Array(items.length).fill(false)
50
51 const newIconCanvases = items.map((item, index) => {
52 const offscreen = document.createElement("canvas")
53 offscreen.width = 40
54 offscreen.height = 40
55 const offCtx = offscreen.getContext("2d")
56
57 if (offCtx) {
58 if (images) {
59 // Handle image URLs directly
60 const img = new Image()
61 img.crossOrigin = "anonymous"
62 img.src = items[index] as string
63 img.onload = () => {
64 offCtx.clearRect(0, 0, offscreen.width, offscreen.height)
65
66 // Create circular clipping path
67 offCtx.beginPath()
68 offCtx.arc(20, 20, 20, 0, Math.PI * 2)
69 offCtx.closePath()
70 offCtx.clip()
71
72 // Draw the image
73 offCtx.drawImage(img, 0, 0, 40, 40)
74
75 imagesLoadedRef.current[index] = true
76 }
77 } else {
78 // Handle SVG icons
79 offCtx.scale(0.4, 0.4)
80 const svgString = renderToString(item as React.ReactElement)
81 const img = new Image()
82 img.src = "data:image/svg+xml;base64," + btoa(svgString)
83 img.onload = () => {
84 offCtx.clearRect(0, 0, offscreen.width, offscreen.height)
85 offCtx.drawImage(img, 0, 0)
86 imagesLoadedRef.current[index] = true
87 }
88 }
89 }
90 return offscreen
91 })
92
93 iconCanvasesRef.current = newIconCanvases
94 }, [icons, images])
95
96 // Generate initial icon positions on a sphere
97 useEffect(() => {
98 const items = icons ?? images ?? []
99 const newIcons: Icon[] = []
100 const numIcons = items.length || 20
101
102 // Fibonacci sphere parameters
103 const offset = 2 / numIcons
104 const increment = Math.PI * (3 - Math.sqrt(5))
105
106 for (let i = 0; i < numIcons; i++) {
107 const y = i * offset - 1 + offset / 2
108 const r = Math.sqrt(1 - y * y)
109 const phi = i * increment
110
111 const x = Math.cos(phi) * r
112 const z = Math.sin(phi) * r
113
114 newIcons.push({
115 x: x * 100,
116 y: y * 100,
117 z: z * 100,
118 scale: 1,
119 opacity: 1,
120 id: i,
121 })
122 }
123 setIconPositions(newIcons)
124 }, [icons, images])
125
126 // Handle mouse events
127 const handleMouseDown = (e: React.MouseEvent<HTMLCanvasElement>) => {
128 const rect = canvasRef.current?.getBoundingClientRect()
129 if (!rect || !canvasRef.current) return
130
131 const x = e.clientX - rect.left
132 const y = e.clientY - rect.top
133
134 const ctx = canvasRef.current.getContext("2d")
135 if (!ctx) return
136
137 iconPositions.forEach((icon) => {
138 const cosX = Math.cos(rotationRef.current.x)
139 const sinX = Math.sin(rotationRef.current.x)
140 const cosY = Math.cos(rotationRef.current.y)
141 const sinY = Math.sin(rotationRef.current.y)
142
143 const rotatedX = icon.x * cosY - icon.z * sinY
144 const rotatedZ = icon.x * sinY + icon.z * cosY
145 const rotatedY = icon.y * cosX + rotatedZ * sinX
146
147 const screenX = canvasRef.current!.width / 2 + rotatedX
148 const screenY = canvasRef.current!.height / 2 + rotatedY
149
150 const scale = (rotatedZ + 200) / 300
151 const radius = 20 * scale
152 const dx = x - screenX
153 const dy = y - screenY
154
155 if (dx * dx + dy * dy < radius * radius) {
156 const targetX = -Math.atan2(
157 icon.y,
158 Math.sqrt(icon.x * icon.x + icon.z * icon.z)
159 )
160 const targetY = Math.atan2(icon.x, icon.z)
161
162 const currentX = rotationRef.current.x
163 const currentY = rotationRef.current.y
164 const distance = Math.sqrt(
165 Math.pow(targetX - currentX, 2) + Math.pow(targetY - currentY, 2)
166 )
167
168 const duration = Math.min(2000, Math.max(800, distance * 1000))
169
170 setTargetRotation({
171 x: targetX,
172 y: targetY,
173 startX: currentX,
174 startY: currentY,
175 distance,
176 startTime: performance.now(),
177 duration,
178 })
179 return
180 }
181 })
182
183 setIsDragging(true)
184 setLastMousePos({ x: e.clientX, y: e.clientY })
185 }
186
187 const handleMouseMove = (e: React.MouseEvent<HTMLCanvasElement>) => {
188 const rect = canvasRef.current?.getBoundingClientRect()
189 if (rect) {
190 const x = e.clientX - rect.left
191 const y = e.clientY - rect.top
192 setMousePos({ x, y })
193 }
194
195 if (isDragging) {
196 const deltaX = e.clientX - lastMousePos.x
197 const deltaY = e.clientY - lastMousePos.y
198
199 rotationRef.current = {
200 x: rotationRef.current.x + deltaY * 0.002,
201 y: rotationRef.current.y + deltaX * 0.002,
202 }
203
204 setLastMousePos({ x: e.clientX, y: e.clientY })
205 }
206 }
207
208 const handleMouseUp = () => {
209 setIsDragging(false)
210 }
211
212 // Animation and rendering
213 useEffect(() => {
214 const canvas = canvasRef.current
215 const ctx = canvas?.getContext("2d")
216 if (canvas && ctx) {
217 const animate = () => {
218 ctx.clearRect(0, 0, canvas.width, canvas.height)
219
220 const centerX = canvas.width / 2
221 const centerY = canvas.height / 2
222 const maxDistance = Math.sqrt(centerX * centerX + centerY * centerY)
223 const dx = mousePos.x - centerX
224 const dy = mousePos.y - centerY
225 const distance = Math.sqrt(dx * dx + dy * dy)
226 const speed = 0.003 + (distance / maxDistance) * 0.01
227
228 if (targetRotation) {
229 const elapsed = performance.now() - targetRotation.startTime
230 const progress = Math.min(1, elapsed / targetRotation.duration)
231 const easedProgress = easeOutCubic(progress)
232
233 rotationRef.current = {
234 x:
235 targetRotation.startX +
236 (targetRotation.x - targetRotation.startX) * easedProgress,
237 y:
238 targetRotation.startY +
239 (targetRotation.y - targetRotation.startY) * easedProgress,
240 }
241
242 if (progress >= 1) {
243 setTargetRotation(null)
244 }
245 } else if (!isDragging) {
246 rotationRef.current = {
247 x: rotationRef.current.x + (dy / canvas.height) * speed,
248 y: rotationRef.current.y + (dx / canvas.width) * speed,
249 }
250 }
251
252 iconPositions.forEach((icon, index) => {
253 const cosX = Math.cos(rotationRef.current.x)
254 const sinX = Math.sin(rotationRef.current.x)
255 const cosY = Math.cos(rotationRef.current.y)
256 const sinY = Math.sin(rotationRef.current.y)
257
258 const rotatedX = icon.x * cosY - icon.z * sinY
259 const rotatedZ = icon.x * sinY + icon.z * cosY
260 const rotatedY = icon.y * cosX + rotatedZ * sinX
261
262 const scale = (rotatedZ + 200) / 300
263 const opacity = Math.max(0.2, Math.min(1, (rotatedZ + 150) / 200))
264
265 ctx.save()
266 ctx.translate(
267 canvas.width / 2 + rotatedX,
268 canvas.height / 2 + rotatedY
269 )
270 ctx.scale(scale, scale)
271 ctx.globalAlpha = opacity
272
273 if (icons || images) {
274 // Only try to render icons/images if they exist
275 if (
276 iconCanvasesRef.current[index] &&
277 imagesLoadedRef.current[index]
278 ) {
279 ctx.drawImage(iconCanvasesRef.current[index], -20, -20, 40, 40)
280 }
281 } else {
282 // Show numbered circles if no icons/images are provided
283 ctx.beginPath()
284 ctx.arc(0, 0, 20, 0, Math.PI * 2)
285 ctx.fillStyle = "#4444ff"
286 ctx.fill()
287 ctx.fillStyle = "white"
288 ctx.textAlign = "center"
289 ctx.textBaseline = "middle"
290 ctx.font = "16px Arial"
291 ctx.fillText(`${icon.id + 1}`, 0, 0)
292 }
293
294 ctx.restore()
295 })
296 animationFrameRef.current = requestAnimationFrame(animate)
297 }
298
299 animate()
300 }
301
302 return () => {
303 if (animationFrameRef.current) {
304 cancelAnimationFrame(animationFrameRef.current)
305 }
306 }
307 }, [icons, images, iconPositions, isDragging, mousePos, targetRotation])
308
309 return (
310 <canvas
311 ref={canvasRef}
312 width={400}
313 height={400}
314 onMouseDown={handleMouseDown}
315 onMouseMove={handleMouseMove}
316 onMouseUp={handleMouseUp}
317 onMouseLeave={handleMouseUp}
318 className="rounded-lg"
319 aria-label="Interactive 3D Icon Cloud"
320 role="img"
321 />
322 )
323}
324