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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
"use client"

import React, { useEffect, useRef, useState } from "react"
import { renderToString } from "react-dom/server"

interface Icon {
  x: number
  y: number
  z: number
  scale: number
  opacity: number
  id: number
}

export interface CloudItem {
  id: string
  title: string
  url: string
  image: string
}

interface IconCloudProps {
  icons?: React.ReactNode[]
  images?: string[]
  items?: CloudItem[]
}

function easeOutCubic(t: number): number {
  return 1 - Math.pow(1 - t, 3)
}

export function IconCloud({ icons, images, items }: IconCloudProps) {
  const canvasRef = useRef<HTMLCanvasElement>(null)
  const [iconPositions, setIconPositions] = useState<Icon[]>([])
  const [isDragging, setIsDragging] = useState(false)
  const [lastMousePos, setLastMousePos] = useState({ x: 0, y: 0 })
  const [mousePos, setMousePos] = useState({ x: 0, y: 0 })
  const [dragMoved, setDragMoved] = useState(false)
  const [targetRotation, setTargetRotation] = useState<{
    x: number
    y: number
    startX: number
    startY: number
    distance: number
    startTime: number
    duration: number
  } | null>(null)
  const animationFrameRef = useRef<number>(0)
  const rotationRef = useRef({ x: 0, y: 0 })
  const velocityRef = useRef({ x: 0.002, y: -0.002 })
  const iconCanvasesRef = useRef<HTMLCanvasElement[]>([])
  const imagesLoadedRef = useRef<boolean[]>([])

  // Create icon canvases once when icons/images change
  useEffect(() => {
    if (!icons && !images && !items) return

    const targetItems = items ?? icons ?? images ?? []
    imagesLoadedRef.current = new Array(targetItems.length).fill(false)

    const newIconCanvases = targetItems.map((item, index) => {
      const size = 100; // High-res offscreen canvas for crisp SVG rendering
      const offscreen = document.createElement("canvas")
      offscreen.width = size
      offscreen.height = size
      const offCtx = offscreen.getContext("2d")

      if (offCtx) {
        if (images || items) {
          // Handle image URLs directly
          const src = items ? items[index].image : images![index]
          const img = new Image()
          img.crossOrigin = "anonymous"
          img.src = src
          img.onload = () => {
            // Create a temporary canvas to measure the actual pixel bounds
            const tempCanvas = document.createElement("canvas")
            tempCanvas.width = size
            tempCanvas.height = size
            const tempCtx = tempCanvas.getContext("2d")
            if (!tempCtx) return

            tempCtx.drawImage(img, 0, 0, size, size)

            try {
              // Find bounding box of non-transparent pixels
              const imageData = tempCtx.getImageData(0, 0, size, size)
              const data = imageData.data
              let minX = size, minY = size, maxX = 0, maxY = 0

              for (let y = 0; y < size; y++) {
                for (let x = 0; x < size; x++) {
                  const alpha = data[(y * size + x) * 4 + 3]
                  if (alpha > 10) { // Ignore faint shadows/anti-aliasing
                    if (x < minX) minX = x
                    if (y < minY) minY = y
                    if (x > maxX) maxX = x
                    if (y > maxY) maxY = y
                  }
                }
              }

              // Fallback if image is completely empty
              if (minX > maxX || minY > maxY) {
                minX = 0; minY = 0; maxX = size; maxY = size;
              }

              const cropWidth = maxX - minX + 1
              const cropHeight = maxY - minY + 1

              // Calculate scaling to fit the maximum dimension, preserving aspect ratio
              const scale = size / Math.max(cropWidth, cropHeight)
              // Make them slightly smaller than the absolute edge (e.g. 90% of max size)
              const paddingScale = 0.9
              const finalWidth = cropWidth * scale * paddingScale
              const finalHeight = cropHeight * scale * paddingScale
              const dx = (size - finalWidth) / 2
              const dy = (size - finalHeight) / 2

              offCtx.clearRect(0, 0, size, size)
              // Draw the tightly cropped image scaled up
              offCtx.drawImage(
                tempCanvas,
                minX, minY, cropWidth, cropHeight,
                dx, dy, finalWidth, finalHeight
              )
            } catch {
              // Fallback if CORS prevents getImageData
              offCtx.clearRect(0, 0, size, size)
              offCtx.drawImage(img, 0, 0, size, size)
            }

            imagesLoadedRef.current[index] = true
          }
        } else {
          // Handle SVG icons
          offCtx.scale(size / 24, size / 24) // scale up assuming 24x24 standard SVG
          const svgString = renderToString(item as React.ReactElement)
          const img = new Image()
          img.src = "data:image/svg+xml;base64," + btoa(svgString)
          img.onload = () => {
            offCtx.clearRect(0, 0, size, size)
            offCtx.drawImage(img, 0, 0, size, size)
            imagesLoadedRef.current[index] = true
          }
        }
      }
      return offscreen
    })

    iconCanvasesRef.current = newIconCanvases
  }, [icons, images, items])

  // Generate initial icon positions on a sphere
  useEffect(() => {
    const targetItems = items ?? icons ?? images ?? []
    const newIcons: Icon[] = []
    const numIcons = targetItems.length || 20

    // Fibonacci sphere parameters
    const offset = 2 / numIcons
    const increment = Math.PI * (3 - Math.sqrt(5))

    for (let i = 0; i < numIcons; i++) {
      const y = i * offset - 1 + offset / 2
      const r = Math.sqrt(1 - y * y)
      const phi = i * increment

      const x = Math.cos(phi) * r
      const z = Math.sin(phi) * r

      newIcons.push({
        x: x * 100,
        y: y * 100,
        z: z * 100,
        scale: 1,
        opacity: 1,
        id: i,
      })
    }
    const timer = setTimeout(() => {
      setIconPositions(newIcons)
    }, 0)
    return () => clearTimeout(timer)
  }, [icons, images, items])

  // Handle mouse events
  const handleMouseDown = (e: React.MouseEvent<HTMLCanvasElement>) => {
    const rect = canvasRef.current?.getBoundingClientRect()
    if (!rect || !canvasRef.current) return

    const scaleX = canvasRef.current.width / rect.width
    const scaleY = canvasRef.current.height / rect.height
    const x = (e.clientX - rect.left) * scaleX
    const y = (e.clientY - rect.top) * scaleY

    const ctx = canvasRef.current.getContext("2d")
    if (!ctx) return

    iconPositions.forEach((icon) => {
      const cosX = Math.cos(rotationRef.current.x)
      const sinX = Math.sin(rotationRef.current.x)
      const cosY = Math.cos(rotationRef.current.y)
      const sinY = Math.sin(rotationRef.current.y)

      const rotatedX = icon.x * cosY - icon.z * sinY
      const rotatedZ = icon.x * sinY + icon.z * cosY
      const rotatedY = icon.y * cosX + rotatedZ * sinX

      const screenX = canvasRef.current!.width / 2 + rotatedX
      const screenY = canvasRef.current!.height / 2 + rotatedY

      const scale = (rotatedZ + 200) / 300
      const radius = 20 * scale
      const dx = x - screenX
      const dy = y - screenY

      if (dx * dx + dy * dy < radius * radius) {
        const targetX = -Math.atan2(
          icon.y,
          Math.sqrt(icon.x * icon.x + icon.z * icon.z)
        )
        const targetY = Math.atan2(icon.x, icon.z)

        const currentX = rotationRef.current.x
        const currentY = rotationRef.current.y
        const distance = Math.sqrt(
          Math.pow(targetX - currentX, 2) + Math.pow(targetY - currentY, 2)
        )

        const duration = Math.min(2000, Math.max(800, distance * 1000))

        setTargetRotation({
          x: targetX,
          y: targetY,
          startX: currentX,
          startY: currentY,
          distance,
          startTime: performance.now(),
          duration,
        })
        return
      }
    })

    setIsDragging(true)
    setDragMoved(false)
    setLastMousePos({ x: e.clientX, y: e.clientY })
  }

  const handleMouseMove = (e: React.MouseEvent<HTMLCanvasElement>) => {
    const rect = canvasRef.current?.getBoundingClientRect()
    if (rect && canvasRef.current) {
      const scaleX = canvasRef.current.width / rect.width
      const scaleY = canvasRef.current.height / rect.height
      const x = (e.clientX - rect.left) * scaleX
      const y = (e.clientY - rect.top) * scaleY
      setMousePos({ x, y })
    }

    if (isDragging) {
      const deltaX = e.clientX - lastMousePos.x
      const deltaY = e.clientY - lastMousePos.y

      if (Math.abs(deltaX) > 2 || Math.abs(deltaY) > 2) {
        setDragMoved(true)
      }

      rotationRef.current = {
        x: rotationRef.current.x + deltaY * 0.002,
        y: rotationRef.current.y + deltaX * 0.002,
      }
      
      // Update velocity immediately based on drag to maintain inertia after release
      velocityRef.current = {
        x: deltaY * 0.002,
        y: deltaX * 0.002,
      }

      setLastMousePos({ x: e.clientX, y: e.clientY })
    }
  }

  const handleMouseUp = () => {
    if (!dragMoved && !isDragging && items) {
      // Click handled separately
    }
    setIsDragging(false)
  }

  const handleMouseLeave = () => {
    setIsDragging(false)
    // When mouse leaves, reset the target mouse pos to center smoothly
    setMousePos({ x: 0, y: 0 }) 
  }

  const handleClick = (e: React.MouseEvent<HTMLCanvasElement>) => {
    if (dragMoved) return // Was dragging
    const rect = canvasRef.current?.getBoundingClientRect()
    if (!rect || !canvasRef.current || !items) return

    const scaleX = canvasRef.current.width / rect.width
    const scaleY = canvasRef.current.height / rect.height
    const x = (e.clientX - rect.left) * scaleX
    const y = (e.clientY - rect.top) * scaleY

    let clickedItem: CloudItem | null = null
    let maxZ = -Infinity

    iconPositions.forEach((icon, index) => {
      const cosX = Math.cos(rotationRef.current.x)
      const sinX = Math.sin(rotationRef.current.x)
      const cosY = Math.cos(rotationRef.current.y)
      const sinY = Math.sin(rotationRef.current.y)

      const rotatedX = icon.x * cosY - icon.z * sinY
      const rotatedZ = icon.x * sinY + icon.z * cosY
      const rotatedY = icon.y * cosX + rotatedZ * sinX

      const screenX = canvasRef.current!.width / 2 + rotatedX
      const screenY = canvasRef.current!.height / 2 + rotatedY

      const scale = (rotatedZ + 200) / 300
      const radius = 20 * scale
      const dx = x - screenX
      const dy = y - screenY

      if (dx * dx + dy * dy < radius * radius) {
        if (rotatedZ > maxZ && rotatedZ > -50) {
          maxZ = rotatedZ
          clickedItem = items[index]
        }
      }
    })

    if (clickedItem) {
      window.open((clickedItem as CloudItem).url, "_blank")
    }
  }

  // Animation and rendering
  useEffect(() => {
    const canvas = canvasRef.current
    const ctx = canvas?.getContext("2d")
    if (canvas && ctx) {
      const animate = () => {
        ctx.clearRect(0, 0, canvas.width, canvas.height)

        const centerX = canvas.width / 2
        const centerY = canvas.height / 2
        
        // Calculate normalized mouse coordinates [-1, 1] relative to center
        // If mousePos is 0,0 (mouse left canvas), it will naturally go to a constant drift
        const nx = mousePos.x === 0 && mousePos.y === 0 ? 0.2 : (mousePos.x - centerX) / centerX
        const ny = mousePos.x === 0 && mousePos.y === 0 ? 0.2 : (mousePos.y - centerY) / centerY

        let targetVelocityX = 0.002 // default idle speed X
        let targetVelocityY = -0.002 // default idle speed Y

        // If mouse is interacting over canvas bounds, adjust velocity based on pointer
        if (mousePos.x > 0 && mousePos.x < canvas.width && mousePos.y > 0 && mousePos.y < canvas.height) {
          targetVelocityX = ny * 0.008
          targetVelocityY = nx * 0.008
        } else if (mousePos.x === 0 && mousePos.y === 0) {
          // When mouse hasn't interacted or left, fallback to gentle diagonal spin
          targetVelocityX = 0.002
          targetVelocityY = -0.002
        }

        let hoveredItemIndex: number | null = null
        let maxZ = -Infinity

        if (targetRotation) {
          const elapsed = performance.now() - targetRotation.startTime
          const progress = Math.min(1, elapsed / targetRotation.duration)
          const easedProgress = easeOutCubic(progress)

          rotationRef.current = {
            x:
              targetRotation.startX +
              (targetRotation.x - targetRotation.startX) * easedProgress,
            y:
              targetRotation.startY +
              (targetRotation.y - targetRotation.startY) * easedProgress,
          }

          if (progress >= 1) {
            setTargetRotation(null)
          }
        } else if (!isDragging) {
          // Apply inertia (smoothly transition to the target velocity)
          velocityRef.current.x += (targetVelocityX - velocityRef.current.x) * 0.05
          velocityRef.current.y += (targetVelocityY - velocityRef.current.y) * 0.05

          rotationRef.current = {
            x: rotationRef.current.x + velocityRef.current.x,
            y: rotationRef.current.y + velocityRef.current.y,
          }
        } else {
          // While dragging, we let handleMouseMove control rotation directly
          // but we still smoothly decay the targetVelocity to zero to avoid snapping
          velocityRef.current.x *= 0.95
          velocityRef.current.y *= 0.95
        }

        iconPositions.forEach((icon, index) => {
          const cosX = Math.cos(rotationRef.current.x)
          const sinX = Math.sin(rotationRef.current.x)
          const cosY = Math.cos(rotationRef.current.y)
          const sinY = Math.sin(rotationRef.current.y)

          const rotatedX = icon.x * cosY - icon.z * sinY
          const rotatedZ = icon.x * sinY + icon.z * cosY
          const rotatedY = icon.y * cosX + rotatedZ * sinX

          const scale = (rotatedZ + 200) / 300
          const opacity = Math.max(0.2, Math.min(1, (rotatedZ + 150) / 200))

          // Check hover state
          const screenX = canvas.width / 2 + rotatedX
          const screenY = canvas.height / 2 + rotatedY
          const radius = 20 * scale
          const hdx = mousePos.x - screenX
          const hdy = mousePos.y - screenY

          if (hdx * hdx + hdy * hdy < radius * radius && rotatedZ > maxZ && rotatedZ > -50) {
            maxZ = rotatedZ
            hoveredItemIndex = index
          }

          ctx.save()
          ctx.translate(
            canvas.width / 2 + rotatedX,
            canvas.height / 2 + rotatedY
          )
          ctx.scale(scale, scale)
          ctx.globalAlpha = opacity

          if (icons || images || items) {
            // Only try to render icons/images if they exist
            if (
              iconCanvasesRef.current[index] &&
              imagesLoadedRef.current[index]
            ) {
              ctx.drawImage(iconCanvasesRef.current[index], -20, -20, 40, 40)
            }
          } else {
            // Show numbered circles if no icons/images are provided
            ctx.beginPath()
            ctx.arc(0, 0, 20, 0, Math.PI * 2)
            ctx.fillStyle = "#4444ff"
            ctx.fill()
            ctx.fillStyle = "white"
            ctx.textAlign = "center"
            ctx.textBaseline = "middle"
            ctx.font = "16px Arial"
            ctx.fillText(`${icon.id + 1}`, 0, 0)
          }

          ctx.restore()
        })

        if (hoveredItemIndex !== null && items) {
          canvas.style.cursor = "pointer"
          const hoveredItem = items[hoveredItemIndex]
          
          // Draw tooltip
          const hoveredIcon = iconPositions[hoveredItemIndex]
          const cosX = Math.cos(rotationRef.current.x)
          const sinX = Math.sin(rotationRef.current.x)
          const cosY = Math.cos(rotationRef.current.y)
          const sinY = Math.sin(rotationRef.current.y)
          const rotatedX = hoveredIcon.x * cosY - hoveredIcon.z * sinY
          const rotatedZ = hoveredIcon.x * sinY + hoveredIcon.z * cosY
          const rotatedY = hoveredIcon.y * cosX + rotatedZ * sinX
          
          const screenX = canvas.width / 2 + rotatedX
          const screenY = canvas.height / 2 + rotatedY
          
          ctx.font = "14px Inter, sans-serif"
          const textWidth = ctx.measureText(hoveredItem.title).width
          
          // Tooltip background
          ctx.fillStyle = "rgba(0, 0, 0, 0.75)"
          // Use a simple rect instead of roundRect for better compatibility, or emulate it
          // Since it's modern web, roundRect is fine in most places, but let's use standard arcs
          const rw = textWidth + 24
          const rh = 28
          const rx = screenX - rw / 2
          const ry = screenY - 50
          const r = 6
          
          ctx.beginPath()
          ctx.moveTo(rx + r, ry)
          ctx.lineTo(rx + rw - r, ry)
          ctx.quadraticCurveTo(rx + rw, ry, rx + rw, ry + r)
          ctx.lineTo(rx + rw, ry + rh - r)
          ctx.quadraticCurveTo(rx + rw, ry + rh, rx + rw - r, ry + rh)
          ctx.lineTo(rx + r, ry + rh)
          ctx.quadraticCurveTo(rx, ry + rh, rx, ry + rh - r)
          ctx.lineTo(rx, ry + r)
          ctx.quadraticCurveTo(rx, ry, rx + r, ry)
          ctx.closePath()
          ctx.fill()
          
          // Tooltip text
          ctx.fillStyle = "#ffffff"
          ctx.textAlign = "center"
          ctx.textBaseline = "middle"
          ctx.fillText(hoveredItem.title, screenX, ry + rh / 2)

        } else {
          canvas.style.cursor = isDragging ? "grabbing" : "grab"
        }

        animationFrameRef.current = requestAnimationFrame(animate)
      }

      animate()
    }

    return () => {
      if (animationFrameRef.current) {
        cancelAnimationFrame(animationFrameRef.current)
      }
    }
  }, [icons, images, items, iconPositions, isDragging, mousePos, targetRotation])

  return (
    <canvas
      ref={canvasRef}
      width={400}
      height={400}
      onMouseDown={handleMouseDown}
      onMouseMove={handleMouseMove}
      onMouseUp={handleMouseUp}
      onMouseLeave={handleMouseLeave}
      onClick={handleClick}
      className="rounded-lg"
      aria-label="Interactive 3D Icon Cloud"
      role="img"
    />
  )
}