1"use client"
2
3import { useCallback, useEffect, useRef, useState } from "react"
4import createGlobe from "cobe"
5import { useSpring } from "@react-spring/web"
6
7import { cn } from "@/lib/utils"
8import { Button } from "@/components/ui/button"
9
10type CobeVariant =
11 | "default"
12 | "draggable"
13 | "auto-draggable"
14 | "auto-rotation"
15 | "rotate-to-location"
16 | "scaled"
17
18interface Location {
19 name: string
20 lat?: number
21 long?: number
22 emoji?: string
23}
24
25interface GeocodeResult {
26 lat: number
27 lng: number
28 display_name: string
29}
30
31interface CobeProps {
32 variant?: CobeVariant
33 className?: string
34 style?: React.CSSProperties
35 locations?: Location[]
36 // Globe configuration settings
37 phi?: number
38 theta?: number
39 mapSamples?: number
40 mapBrightness?: number
41 mapBaseBrightness?: number
42 diffuse?: number
43 dark?: number
44 baseColor?: string
45 markerColor?: string
46 markerSize?: number
47 glowColor?: string
48 scale?: number
49 offsetX?: number
50 offsetY?: number
51 opacity?: number
52}
53
54type CobeState = Record<string, unknown>
55
56export function Cobe({
57 variant = "default",
58 className,
59 style,
60 locations = [
61 { name: "San Francisco", emoji: "๐" },
62 { name: "Berlin", emoji: "๐" },
63 { name: "Tokyo", emoji: "๐" },
64 { name: "Buenos Aires", emoji: "๐" },
65 ],
66 // Default values based on the original JSX version
67 phi = 0,
68 theta = 0.2,
69 mapSamples = 16000,
70 mapBrightness = 1.8,
71 mapBaseBrightness = 0.05,
72 diffuse = 3,
73 dark = 1.0,
74 baseColor = "#ffffff",
75 markerColor = "#fb6415",
76 markerSize = 0.05,
77 glowColor = "#ffffff",
78 scale = 1.0,
79 offsetX = 0.0,
80 offsetY = 0.0,
81 opacity = 0.7,
82}: CobeProps) {
83 const canvasRef = useRef<HTMLCanvasElement>(null)
84 const pointerInteracting = useRef<number | null>(null)
85 const pointerInteractionMovement = useRef<number>(0)
86 const focusRef = useRef<[number, number]>([0, 0])
87 const [customLocations, setCustomLocations] = useState<Location[]>([])
88 const [isInitializing, setIsInitializing] = useState(true)
89
90 const [{ r }, api] = useSpring<{ r: number }>(() => ({
91 r: 0,
92 config: {
93 mass: 1,
94 tension: 280,
95 friction: 40,
96 precision: 0.001,
97 },
98 }))
99
100 const locationToAngles = (lat: number, long: number): [number, number] => {
101 return [
102 Math.PI - ((long * Math.PI) / 180 - Math.PI / 2),
103 (lat * Math.PI) / 180,
104 ] as [number, number]
105 }
106
107 const hexToRgb = (hex: string): [number, number, number] => {
108 const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
109 return result
110 ? [
111 parseInt(result[1], 16) / 255,
112 parseInt(result[2], 16) / 255,
113 parseInt(result[3], 16) / 255,
114 ]
115 : [0, 0, 0]
116 }
117
118 const geocodeLocation = async (
119 query: string
120 ): Promise<GeocodeResult | null> => {
121 try {
122 const response = await fetch(
123 `https://nominatim.openstreetmap.org/search?format=json&q=${encodeURIComponent(query)}&limit=1`
124 )
125 const data = await response.json()
126
127 if (data && data.length > 0) {
128 return {
129 lat: parseFloat(data[0].lat),
130 lng: parseFloat(data[0].lon),
131 display_name: data[0].display_name,
132 }
133 }
134 return null
135 } catch (error) {
136 console.error("Geocoding error:", error)
137 return null
138 }
139 }
140
141 const geocodeLocationList = useCallback(async (locationList: Location[]) => {
142 const geocodedLocations: Location[] = []
143
144 for (const location of locationList) {
145 if (location.lat && location.long) {
146 // Already has coordinates
147 geocodedLocations.push(location)
148 } else {
149 // Need to geocode
150 const result = await geocodeLocation(location.name)
151 if (result) {
152 geocodedLocations.push({
153 ...location,
154 lat: result.lat,
155 long: result.lng,
156 })
157 }
158 }
159 }
160
161 return geocodedLocations
162 }, [])
163
164 // Initialize locations on component mount
165 useEffect(() => {
166 const initializeLocations = async () => {
167 if (variant === "rotate-to-location" && locations.length > 0) {
168 setIsInitializing(true)
169 const geocoded = await geocodeLocationList(locations)
170 setCustomLocations(geocoded)
171 setIsInitializing(false)
172 }
173 }
174
175 initializeLocations()
176 }, [variant, locations, geocodeLocationList])
177
178 useEffect(() => {
179 let phi = 0
180 let width = 0
181 let currentPhi = 0
182 let currentTheta = 0
183 const doublePi = Math.PI * 2
184
185 const onResize = () => {
186 if (canvasRef.current) {
187 width = canvasRef.current.offsetWidth
188 }
189 }
190
191 window.addEventListener("resize", onResize)
192 onResize()
193
194 if (!canvasRef.current) return
195
196 const globe = createGlobe(canvasRef.current, {
197 devicePixelRatio: 2,
198 width: width * 2,
199 height: variant === "scaled" ? width * 2 * 0.4 : width * 2,
200 phi: phi,
201 theta: theta,
202 dark: dark,
203 diffuse: diffuse,
204 mapSamples: mapSamples,
205 mapBrightness: mapBrightness,
206 mapBaseBrightness: mapBaseBrightness,
207 baseColor: hexToRgb(baseColor),
208 markerColor: hexToRgb(markerColor),
209 glowColor: hexToRgb(glowColor),
210 markers:
211 variant === "default" ||
212 variant === "draggable" ||
213 variant === "auto-draggable" ||
214 variant === "auto-rotation" ||
215 variant === "scaled"
216 ? [
217 // San Francisco, default color
218 { location: [37.7595, -122.4367], size: markerSize },
219 // New York, red color
220 {
221 location: [40.7128, -74.006],
222 size: markerSize,
223 color: [1, 0, 0],
224 },
225 // Tokyo, blue color
226 {
227 location: [35.6895, 139.6917],
228 size: markerSize,
229 color: [0, 0.5, 1],
230 },
231 // Sydney, green color
232 {
233 location: [-33.8688, 151.2093],
234 size: markerSize,
235 color: [0, 1, 0],
236 },
237 // Rio de Janeiro, purple color
238 {
239 location: [-22.9068, -43.1729],
240 size: markerSize,
241 color: [0.8, 0, 0.8],
242 },
243 // Paris, yellow color
244 {
245 location: [48.8566, 2.3522],
246 size: markerSize,
247 color: [1, 1, 0],
248 },
249 // Porto, orange color
250 {
251 location: [41.1579, -8.6291],
252 size: markerSize,
253 color: [1, 0.5, 0],
254 },
255 // Athens, pink color
256 {
257 location: [37.9838, 23.7275],
258 size: markerSize,
259 color: [1, 0.5, 1],
260 },
261 // Rome, brown color
262 {
263 location: [41.9028, 12.4964],
264 size: markerSize,
265 color: [0.5, 0.3, 0],
266 },
267 // Kathmandu, blue color
268 {
269 location: [27.7172, 85.324],
270 size: markerSize,
271 color: [0, 0.5, 1],
272 },
273 // Tarbes, green color
274 {
275 location: [43.4643, -0.5167],
276 size: markerSize,
277 color: [0, 1, 0],
278 },
279 // Bamako, yellow color
280 {
281 location: [12.6683, -8.0076],
282 size: markerSize,
283 color: [1, 1, 0],
284 },
285 // Djibouti, purple color
286 {
287 location: [11.55, 43.1667],
288 size: markerSize,
289 color: [0.8, 0, 0.8],
290 },
291 ]
292 : variant === "rotate-to-location"
293 ? customLocations
294 .filter((loc) => loc.lat && loc.long)
295 .map((loc) => ({
296 location: [loc.lat!, loc.long!],
297 size: markerSize,
298 }))
299 : [],
300 scale: variant === "scaled" ? 2.5 : undefined,
301 offset: variant === "scaled" ? [0, width * 2 * 0.4 * 0.6] : undefined,
302 opacity: opacity,
303 onRender: (state: CobeState) => {
304 switch (variant) {
305 case "default":
306 state.phi = phi + r.get()
307 phi += 0.005
308 break
309 case "draggable":
310 state.phi = r.get()
311 break
312 case "auto-draggable":
313 if (!pointerInteracting.current) {
314 phi += 0.005
315 }
316 state.phi = phi + r.get()
317 break
318 case "auto-rotation":
319 state.phi = phi
320 phi += 0.005
321 break
322 case "rotate-to-location":
323 state.phi = currentPhi
324 state.theta = currentTheta
325 const [focusPhi, focusTheta] = focusRef.current
326 const distPositive = (focusPhi - currentPhi + doublePi) % doublePi
327 const distNegative = (currentPhi - focusPhi + doublePi) % doublePi
328 if (distPositive < distNegative) {
329 currentPhi += distPositive * 0.08
330 } else {
331 currentPhi -= distNegative * 0.08
332 }
333 currentTheta = currentTheta * 0.92 + focusTheta * 0.08
334 break
335 case "scaled":
336 // No rotation for scaled variant
337 break
338 }
339
340 state.width = width * 2
341 state.height = variant === "scaled" ? width * 2 * 0.4 : width * 2
342 },
343 })
344
345 if (canvasRef.current) {
346 setTimeout(() => {
347 if (canvasRef.current) {
348 canvasRef.current.style.opacity = opacity.toString()
349 }
350 })
351 }
352
353 return () => {
354 globe.destroy()
355 window.removeEventListener("resize", onResize)
356 }
357 }, [
358 variant,
359 r,
360 customLocations,
361 phi,
362 theta,
363 mapSamples,
364 mapBrightness,
365 mapBaseBrightness,
366 diffuse,
367 dark,
368 baseColor,
369 markerColor,
370 markerSize,
371 glowColor,
372 scale,
373 offsetX,
374 offsetY,
375 opacity,
376 ])
377
378 const handlePointerDown = (e: React.PointerEvent) => {
379 if (
380 variant === "draggable" ||
381 variant === "auto-draggable" ||
382 variant === "default"
383 ) {
384 pointerInteracting.current =
385 e.clientX - pointerInteractionMovement.current
386 if (canvasRef.current) canvasRef.current.style.cursor = "grabbing"
387 }
388 }
389
390 const handlePointerUp = () => {
391 if (
392 variant === "draggable" ||
393 variant === "auto-draggable" ||
394 variant === "default"
395 ) {
396 pointerInteracting.current = null
397 if (canvasRef.current) canvasRef.current.style.cursor = "grab"
398 }
399 }
400
401 const handlePointerOut = () => {
402 if (
403 variant === "draggable" ||
404 variant === "auto-draggable" ||
405 variant === "default"
406 ) {
407 pointerInteracting.current = null
408 if (canvasRef.current) canvasRef.current.style.cursor = "grab"
409 }
410 }
411
412 const handleMouseMove = (e: React.MouseEvent) => {
413 if (
414 (variant === "draggable" ||
415 variant === "auto-draggable" ||
416 variant === "default") &&
417 pointerInteracting.current !== null
418 ) {
419 const delta = e.clientX - pointerInteracting.current
420 pointerInteractionMovement.current = delta
421 api.start({
422 r: delta / 200,
423 })
424 }
425 }
426
427 const handleTouchMove = (e: React.TouchEvent) => {
428 if (
429 (variant === "draggable" ||
430 variant === "auto-draggable" ||
431 variant === "default") &&
432 pointerInteracting.current !== null &&
433 e.touches[0]
434 ) {
435 const delta = e.touches[0].clientX - pointerInteracting.current
436 pointerInteractionMovement.current = delta
437 api.start({
438 r: delta / 100,
439 })
440 }
441 }
442
443 const handleLocationClick = (lat: number, long: number) => {
444 if (variant === "rotate-to-location") {
445 focusRef.current = locationToAngles(lat, long)
446 }
447 }
448
449 const containerStyle = {
450 width: "100%",
451 maxWidth: variant === "scaled" ? 800 : 600,
452 aspectRatio: variant === "scaled" ? 2.5 : 1,
453 margin: "auto",
454 position: "relative" as const,
455 ...style,
456 }
457
458 const canvasStyle = {
459 width: "100%",
460 height: "100%",
461 contain: "layout paint size" as const,
462 opacity: 0,
463 transition: "opacity 1s ease",
464 cursor:
465 variant === "draggable" ||
466 variant === "auto-draggable" ||
467 variant === "default"
468 ? "grab"
469 : undefined,
470 borderRadius:
471 variant === "default" ||
472 variant === "draggable" ||
473 variant === "auto-draggable" ||
474 variant === "auto-rotation"
475 ? "50%"
476 : variant === "scaled"
477 ? "8px"
478 : undefined,
479 }
480
481 return (
482 <div className={cn("", className)} style={containerStyle}>
483 <canvas
484 ref={canvasRef}
485 onPointerDown={handlePointerDown}
486 onPointerUp={handlePointerUp}
487 onPointerOut={handlePointerOut}
488 onMouseMove={handleMouseMove}
489 onTouchMove={handleTouchMove}
490 style={canvasStyle}
491 />
492 {variant === "rotate-to-location" && (
493 <>
494 <div
495 className="control-buttons flex flex-col items-center justify-center md:flex-row"
496 style={{ gap: ".5rem" }}
497 >
498 {isInitializing ? "Loading locations..." : ""}
499 {customLocations
500 .filter((loc) => loc.lat && loc.long)
501 .map((location, index) => (
502 <Button
503 key={index}
504 onClick={() =>
505 handleLocationClick(location.lat!, location.long!)
506 }
507 className="bg-background/80 text-foreground hover:bg-background/90 border-border transition-all duration-200 hover:scale-105"
508 >
509 {location.emoji || "๐"} {location.name}
510 </Button>
511 ))}
512 </div>
513 </>
514 )}
515 </div>
516 )
517}
518