import React, { useEffect, useRef, useState, useCallback } from 'react'; import { useTranslation } from 'react-i18next'; import maplibregl from 'maplibre-gl'; import 'maplibre-gl/dist/maplibre-gl.css'; import { fetchIslands } from '../../api/client'; import { useAuth } from '../../auth/AuthContext'; import './IslandsWorld.css'; /** * IslandsWorld: Full-screen metaverse for personal islands * Each user has their own floating island in this virtual ocean */ export default function IslandsWorld({ theme, onIslandClick, onOpenMap, onOpenPlanets }) { const { t } = useTranslation(); const { authenticated, username } = useAuth(); const containerRef = useRef(null); const mapRef = useRef(null); const markersRef = useRef([]); const animationRef = useRef(null); const [islands, setIslands] = useState([]); const [loading, setLoading] = useState(true); const [searchQuery, setSearchQuery] = useState(''); const [hoveredIsland, setHoveredIsland] = useState(null); // Fetch islands useEffect(() => { let mounted = true; setLoading(true); fetchIslands({ limit: 200 }) .then(data => { if (mounted) { setIslands(data || []); setLoading(false); } }) .catch(err => { console.warn('[IslandsWorld] Failed to fetch islands:', err); if (mounted) setLoading(false); }); return () => { mounted = false; }; }, []); // Filter islands by search const filteredIslands = searchQuery ? islands.filter(i => (i.username || '').toLowerCase().includes(searchQuery.toLowerCase()) || (i.display_name || '').toLowerCase().includes(searchQuery.toLowerCase()) ) : islands; // Initialize MapLibre useEffect(() => { if (!containerRef.current || loading) return; const centerLng = 0; const centerLat = 0; const map = new maplibregl.Map({ container: containerRef.current, style: { version: 8, sources: {}, layers: [ { id: 'background', type: 'background', paint: { 'background-color': '#0a1628' // Deep ocean } } ] }, center: [centerLng, centerLat], zoom: 1, pitch: 50, bearing: 0, antialias: true, attributionControl: false }); mapRef.current = map; map.on('load', () => { // Add ocean gradient layer const oceanGradientData = createOceanGradient(centerLng, centerLat); map.addSource('ocean-gradient', { type: 'geojson', data: oceanGradientData }); map.addLayer({ id: 'ocean-glow', type: 'fill', source: 'ocean-gradient', paint: { 'fill-color': [ 'interpolate', ['linear'], ['get', 'intensity'], 0, '#0a1628', 0.5, '#0d2847', 1, '#1e3a5f' ], 'fill-opacity': 0.8 } }); // Add starfield const starsData = createStarfield(500); map.addSource('stars', { type: 'geojson', data: starsData }); map.addLayer({ id: 'stars', type: 'circle', source: 'stars', paint: { 'circle-radius': ['interpolate', ['linear'], ['zoom'], 0, 1, 5, 3], 'circle-color': ['get', 'color'], 'circle-opacity': ['get', 'opacity'], 'circle-blur': 0.3 } }); // Create island markers const markers = []; const gridSize = Math.ceil(Math.sqrt(filteredIslands.length || 1)); const spacing = 20; filteredIslands.forEach((island, idx) => { const gridX = idx % gridSize; const gridY = Math.floor(idx / gridSize); const baseX = (gridX - gridSize / 2) * spacing; const baseY = (gridY - gridSize / 2) * spacing; const jitterX = (Math.random() - 0.5) * spacing * 0.4; const jitterY = (Math.random() - 0.5) * spacing * 0.4; const lng = centerLng + baseX + jitterX; const lat = centerLat + baseY + jitterY; const el = createIslandMarker(island, idx, t, username); el.addEventListener('mouseenter', () => setHoveredIsland(island)); el.addEventListener('mouseleave', () => setHoveredIsland(null)); el.addEventListener('click', (e) => { e.stopPropagation(); const action = e.target.closest('[data-action]')?.dataset?.action; if (action === 'profile') { // Navigate to user profile window.location.href = `/profile/${island.username}`; return; } if (action === 'edit') { // Navigate to island edit window.location.href = `/island/${island.username}/edit`; return; } // Default: open island viewer onIslandClick?.(island); }); const marker = new maplibregl.Marker({ element: el, anchor: 'center' }) .setLngLat([lng, lat]) .addTo(map); markers.push({ marker, island, el }); }); markersRef.current = markers; // Gentle rotation let bearing = 0; function animate() { bearing += 0.05; if (bearing >= 360) bearing = 0; map.rotateTo(bearing, { duration: 100 }); animationRef.current = requestAnimationFrame(animate); } animate(); }); return () => { if (animationRef.current) cancelAnimationFrame(animationRef.current); markersRef.current.forEach(({ marker }) => marker.remove()); markersRef.current = []; map.remove(); }; }, [filteredIslands, loading, onIslandClick, t]); return (
{/* Search bar with icon and world nav */}
setSearchQuery(e.target.value)} /> {searchQuery && ( )} {islands.length}
{/* Main canvas */}
{/* Hovered island tooltip */} {hoveredIsland && (
{hoveredIsland.avatar_url ? ( {hoveredIsland.username} ) : ( {(hoveredIsland.username || 'U')[0].toUpperCase()} )}
@{hoveredIsland.username}
{hoveredIsland.display_name || hoveredIsland.bio || t('worlds.clickToVisit')}
{hoveredIsland.content_count || 0} {t('worlds.posts')} • {hoveredIsland.terrain_type || 'tropical'}
)} {/* Create Island CTA (for authenticated users without island) */} {authenticated && ( )} {/* Loading overlay */} {loading && (

{t('worlds.loadingIslands')}

)}
); } /** * Create a stylized island marker element */ function createIslandMarker(island, idx, t, currentUsername) { const el = document.createElement('div'); el.className = 'island-marker'; const terrainColors = { 'tropical': '#2ecc71', 'desert': '#f39c12', 'arctic': '#3498db', 'volcanic': '#e74c3c', 'meadow': '#27ae60', }; const color = terrainColors[island.terrain_type] || terrainColors['tropical']; const seed = island.seed || idx; // Generate unique island shape const islandSVG = generateIslandSVG(seed, color); const postCount = island.content_count || 0; const isOwner = currentUsername && island.username && currentUsername.toLowerCase() === island.username.toLowerCase(); el.innerHTML = `
${islandSVG}
@${island.username} ${postCount} posts
${isOwner ? ` ` : ''}
`; return el; } /** * Generate island SVG with organic shape */ function generateIslandSVG(seed, color) { const rng = seededRandom(seed); const size = 140; const cx = size / 2; const cy = size / 2; const numPoints = 10; // Generate organic shape const points = []; for (let i = 0; i < numPoints; i++) { const angle = (i / numPoints) * Math.PI * 2; const radiusVar = 0.55 + rng() * 0.45; const r = (size / 2.5) * radiusVar; points.push({ x: cx + Math.cos(angle) * r, y: cy + Math.sin(angle) * r }); } // Create smooth path let path = `M ${points[0].x} ${points[0].y}`; for (let i = 0; i < numPoints; i++) { const curr = points[i]; const next = points[(i + 1) % numPoints]; const cpx = (curr.x + next.x) / 2 + (rng() - 0.5) * 10; const cpy = (curr.y + next.y) / 2 + (rng() - 0.5) * 10; path += ` Q ${cpx} ${cpy} ${next.x} ${next.y}`; } path += ' Z'; // Add decorations const numTrees = 3 + Math.floor(rng() * 4); let trees = ''; for (let i = 0; i < numTrees; i++) { const angle = rng() * Math.PI * 2; const dist = 10 + rng() * 20; const tx = cx + Math.cos(angle) * dist; const ty = cy + Math.sin(angle) * dist; const treeSize = 6 + rng() * 6; trees += ` `; } return ` ${trees} `; } /** * Create starfield GeoJSON */ function createStarfield(count) { const features = []; for (let i = 0; i < count; i++) { const lng = (Math.random() - 0.5) * 400; const lat = (Math.random() - 0.5) * 400; const brightness = Math.random(); features.push({ type: 'Feature', geometry: { type: 'Point', coordinates: [lng, lat] }, properties: { color: brightness > 0.8 ? '#ffeedd' : brightness > 0.5 ? '#aaccff' : '#ffffff', opacity: 0.3 + brightness * 0.5 } }); } return { type: 'FeatureCollection', features }; } /** * Create ocean gradient GeoJSON */ function createOceanGradient(centerLng, centerLat) { const features = []; const rings = 10; for (let i = 0; i < rings; i++) { const radius = (i + 1) * 30; const coords = []; for (let j = 0; j <= 64; j++) { const angle = (j / 64) * Math.PI * 2; coords.push([ centerLng + Math.cos(angle) * radius, centerLat + Math.sin(angle) * radius ]); } features.push({ type: 'Feature', geometry: { type: 'Polygon', coordinates: [coords] }, properties: { intensity: 1 - (i / rings) } }); } return { type: 'FeatureCollection', features }; } /** * Seeded random number generator */ function seededRandom(seed) { let s = seed; return function() { s = (s * 9301 + 49297) % 233280; return s / 233280; }; }