import React, { useEffect, useRef, useState } from 'react';
import maplibregl from 'maplibre-gl';
import 'maplibre-gl/dist/maplibre-gl.css';
import '../../styles/island.css';
import { fetchPosts, updateProfileUsername, uploadProfileAvatar, updateTimezone, getBrowserTimezone, changePassword, toSmallImageUrl } from '../../api/client';
import { setUserTimezone as saveTimezoneLocal, getUserTimezone as getStoredTimezone } from '../../utils/timezone';
import { useAuth } from '../../auth/AuthContext';
import { trackEvent } from "../../utils/analytics";

/**
 * IslandViewer: 2.5D immersive island visualization using MapLibre
 * Lightweight alternative to Three.js using existing MapLibre dependency
 */
export default function IslandViewer({ island, onClose }) {
  const containerRef = useRef(null);
  const mapRef = useRef(null);
  const animationRef = useRef(null);
  const fileRef = useRef(null);
  const { authenticated, username, refreshProfile, setAvatarUrl, setNeedsUsername } = useAuth();
  const [uploading, setUploading] = useState(false);
  const [uploadError, setUploadError] = useState("");
  const [uploadInfo, setUploadInfo] = useState("");
  const [avatarVisibility, setAvatarVisibility] = useState("public");
  const [avatarGroupId, setAvatarGroupId] = useState("");
  const [avatarUsers, setAvatarUsers] = useState("");
  const [avatarSrc, setAvatarSrc] = useState("");
  const [activeTab, setActiveTab] = useState("profile");
  const [userPosts, setUserPosts] = useState([]);
  const [postsLoading, setPostsLoading] = useState(false);
  const [localUsername, setLocalUsername] = useState("");
  const [usernameDraft, setUsernameDraft] = useState("");
  const [usernameSaving, setUsernameSaving] = useState(false);
  const [usernameError, setUsernameError] = useState("");
  const [usernameInfo, setUsernameInfo] = useState("");
  const [timezone, setTimezone] = useState(getStoredTimezone());
  const [timezoneSaving, setTimezoneSaving] = useState(false);
  const [timezoneInfo, setTimezoneInfo] = useState("");
  // Password change
  const [showPasswordForm, setShowPasswordForm] = useState(false);
  const [oldPassword, setOldPassword] = useState('');
  const [newPassword, setNewPassword] = useState('');
  const [confirmPassword, setConfirmPassword] = useState('');
  const [passwordError, setPasswordError] = useState('');
  const [passwordSuccess, setPasswordSuccess] = useState('');
  const [passwordLoading, setPasswordLoading] = useState(false);
  const islandUsername = localUsername || island?.username || "";

  useEffect(() => {
    if (!island || !containerRef.current) return;

    console.log('[IslandViewer] Rendering island with MapLibre:', islandUsername, island.seed);
    trackEvent("island_open", { username: islandUsername || "" });

    // Center of island in virtual coordinates
    const centerLng = 0;
    const centerLat = 0;

    // Create MapLibre map with sky theme
    const map = new maplibregl.Map({
      container: containerRef.current,
      style: {
        version: 8,
        sources: {},
        layers: [
          {
            id: 'background',
            type: 'background',
            paint: {
              'background-color': '#87ceeb' // Sky blue
            }
          }
        ]
      },
      center: [centerLng, centerLat],
      zoom: 16,
      pitch: 60, // 2.5D angle
      bearing: 0,
      antialias: true,
      attributionControl: false
    });

    mapRef.current = map;

    map.on('load', () => {
      // Add ocean layer (large circle)
      map.addLayer({
        id: 'ocean',
        type: 'fill',
        source: {
          type: 'geojson',
          data: {
            type: 'Feature',
            geometry: {
              type: 'Polygon',
              coordinates: [createCircleCoordinates(centerLng, centerLat, 0.005, 64)]
            }
          }
        },
        paint: {
          'fill-color': '#1e90ff',
          'fill-opacity': 0.6
        }
      });

      // Generate island terrain as custom marker
      const islandEl = createIslandElement(island.seed, island.terrain_type);
      const islandMarker = new maplibregl.Marker({
        element: islandEl,
        anchor: 'center'
      })
        .setLngLat([centerLng, centerLat])
        .addTo(map);

      // Generate vegetation markers
      const vegetationData = generateVegetationData(island.seed, island.terrain_type);
      const vegMarkers = [];

      vegetationData.forEach(veg => {
        const vegEl = createTreeElement(veg.terrainType);
        const vegMarker = new maplibregl.Marker({
          element: vegEl,
          anchor: 'bottom'
        })
          .setLngLat([centerLng + veg.offsetX, centerLat + veg.offsetY])
          .addTo(map);

        vegMarkers.push(vegMarker);
      });

      // Add content items as markers
      if (island.content && island.content.length > 0) {
        console.log('[IslandViewer] Adding', island.content.length, 'content items');
        const usedSlots = new Map();
        island.content.forEach((item, idx) => {
          const contentEl = createContentElement(item);
          const pos = resolveContentPosition(item, idx, island.seed, usedSlots);
          new maplibregl.Marker({
            element: contentEl,
            anchor: 'bottom'
          })
            .setLngLat([
              centerLng + (pos.x - 0.5) * 0.0012,
              centerLat + (pos.y - 0.5) * 0.0012
            ])
            .addTo(map);
        });
      }

      // Animation: gentle rotation
      let bearing = 0;
      function animate() {
        bearing += 0.1;
        if (bearing >= 360) bearing = 0;
        map.rotateTo(bearing, { duration: 100, easing: t => t });
        animationRef.current = requestAnimationFrame(animate);
      }
      animate();
    });

    // Cleanup
    return () => {
      if (animationRef.current) {
        cancelAnimationFrame(animationRef.current);
      }
      map.remove();
    };
  }, [island]);

  useEffect(() => {
    setAvatarSrc(island?.avatar_url || "");
  }, [island?.avatar_url]);

  useEffect(() => {
    setLocalUsername(island?.username || "");
  }, [island?.username]);

  useEffect(() => {
    setUsernameDraft(islandUsername);
  }, [islandUsername]);

  useEffect(() => {
    if (!islandUsername) return;
    let cancelled = false;
    setPostsLoading(true);
    fetchPosts({ username: islandUsername, limit: 40 })
      .then((items) => {
        if (cancelled) return;
        setUserPosts(Array.isArray(items) ? items : []);
      })
      .catch(() => {
        if (cancelled) return;
        setUserPosts([]);
      })
      .finally(() => {
        if (cancelled) return;
        setPostsLoading(false);
      });
    return () => {
      cancelled = true;
    };
  }, [island?.username]);

  if (!island) return null;
  const isSelf =
    authenticated && username && islandUsername &&
    username.toLowerCase() === islandUsername.toLowerCase();

  return (
    <div className="island-viewer-modal" onClick={onClose}>
      <div className="island-viewer-container" onClick={(e) => e.stopPropagation()}>
        <button className="island-viewer-close" onClick={onClose}>×</button>

        <div className="island-viewer-header">
            <div className="island-header-row">
              <div className="island-header-avatar">
                {avatarSrc ? (
                  <img src={toSmallImageUrl(avatarSrc)} alt={islandUsername} />
                ) : (
                  <span>{(islandUsername || "U")[0].toUpperCase()}</span>
                )}
              </div>
              <div className="island-header-text">
                <h2>{island.display_name || `${islandUsername}'s Island`}</h2>
                <p>{island.bio || 'Welcome to my island'}</p>
              </div>
            </div>
        </div>

        {activeTab === "profile" ? (
          <div className="island-profile-panel">
            <div className="island-profile-avatar">
              {avatarSrc ? (
                <img src={toSmallImageUrl(avatarSrc)} alt={islandUsername} />
              ) : (
                <div className="island-profile-letter">
                  {(islandUsername || "U")[0].toUpperCase()}
                </div>
              )}
            </div>
            <div className="island-profile-meta">
              <div className="island-profile-name">@{islandUsername}</div>
              {isSelf ? (
                <div className="island-profile-actions">
                  <div className="island-profile-row">
                    <label>Username</label>
                    <div className="island-profile-inline">
                      <input
                        className="island-profile-input"
                        value={usernameDraft}
                        onChange={(e) => setUsernameDraft(e.target.value)}
                        placeholder="Choose a username"
                        disabled={usernameSaving}
                      />
                      <button
                        type="button"
                        className="island-profile-btn"
                        disabled={usernameSaving || !usernameDraft.trim()}
                        onClick={async () => {
                          const next = usernameDraft.trim();
                          if (!next) return;
                          setUsernameSaving(true);
                          setUsernameError("");
                          setUsernameInfo("");
                          const res = await updateProfileUsername(next);
                          if (res && res.ok && res.username) {
                            setLocalUsername(res.username);
                            if (setNeedsUsername) setNeedsUsername(false);
                            if (refreshProfile) await refreshProfile();
                            setUsernameInfo("Username updated.");
                          } else {
                            setUsernameError(res?.text || "Update failed.");
                          }
                          setUsernameSaving(false);
                        }}
                      >
                        {usernameSaving ? "Saving..." : "Change"}
                      </button>
                    </div>
                  </div>
                  <div className="island-profile-row">
                    <label>Photo visibility</label>
                    <select
                      value={avatarVisibility}
                      onChange={(e) => {
                        const next = e.target.value;
                        setAvatarVisibility(next);
                        if (next !== "group") setAvatarGroupId("");
                        if (next !== "custom") setAvatarUsers("");
                      }}
                    >
                      <option value="public">Public</option>
                      <option value="private">Private</option>
                      <option value="group">Group</option>
                      <option value="custom">Custom</option>
                    </select>
                  </div>
                  {avatarVisibility === "group" ? (
                    <input
                      className="island-profile-input"
                      placeholder="Group ID"
                      value={avatarGroupId}
                      onChange={(e) => setAvatarGroupId(e.target.value)}
                    />
                  ) : null}
                  {avatarVisibility === "custom" ? (
                    <input
                      className="island-profile-input"
                      placeholder="Usernames (comma separated)"
                      value={avatarUsers}
                      onChange={(e) => setAvatarUsers(e.target.value)}
                    />
                  ) : null}
                  <button
                    type="button"
                    className="island-profile-btn"
                    disabled={uploading}
                    onClick={() => fileRef.current && fileRef.current.click()}
                  >
                    {uploading ? "Uploading..." : "Change photo"}
                  </button>
                  <input
                    ref={fileRef}
                    type="file"
                    accept="image/*"
                    style={{ display: "none" }}
                    onChange={async (e) => {
                      const file = e.target.files && e.target.files[0];
                      if (!file) return;
                      setUploading(true);
                      setUploadError("");
                      setUploadInfo("");
                      const users = avatarUsers
                        .split(",")
                        .map((u) => u.trim())
                        .filter(Boolean);
                      const res = await uploadProfileAvatar(file, {
                        visibility: avatarVisibility,
                        group_id: avatarGroupId.trim(),
                        users,
                      });
                      if (res && res.ok && res.avatar_url) {
                        setAvatarSrc(res.avatar_url);
                        if (setAvatarUrl) setAvatarUrl(res.avatar_url);
                        setUploadInfo("Photo updated.");
                      } else {
                        setUploadError(res?.text || "Upload failed.");
                      }
                      setUploading(false);
                    }}
                  />
                  {uploadError ? <div className="island-profile-error">{uploadError}</div> : null}
                  {uploadInfo ? <div className="island-profile-info">{uploadInfo}</div> : null}
                  {usernameError ? <div className="island-profile-error">{usernameError}</div> : null}
                  {usernameInfo ? <div className="island-profile-info">{usernameInfo}</div> : null}

                  <div className="island-profile-row" style={{ marginTop: '16px' }}>
                    <label>Timezone</label>
                    <select
                      value={timezone}
                      onChange={async (e) => {
                        const tz = e.target.value;
                        setTimezone(tz);
                        saveTimezoneLocal(tz); // Save locally for immediate use
                        setTimezoneSaving(true);
                        setTimezoneInfo("");
                        const res = await updateTimezone(tz);
                        if (res?.ok) {
                          setTimezoneInfo("Timezone saved");
                          setTimeout(() => setTimezoneInfo(""), 2000);
                        }
                        setTimezoneSaving(false);
                      }}
                      disabled={timezoneSaving}
                    >
                      <option value="">Auto-detect</option>
                      <optgroup label="Americas">
                        <option value="America/New_York">New York (EST)</option>
                        <option value="America/Chicago">Chicago (CST)</option>
                        <option value="America/Denver">Denver (MST)</option>
                        <option value="America/Los_Angeles">Los Angeles (PST)</option>
                        <option value="America/Toronto">Toronto (EST)</option>
                        <option value="America/Montreal">Montreal (EST)</option>
                        <option value="America/Vancouver">Vancouver (PST)</option>
                        <option value="America/Mexico_City">Mexico City</option>
                        <option value="America/Sao_Paulo">São Paulo</option>
                      </optgroup>
                      <optgroup label="Europe">
                        <option value="Europe/London">London (GMT)</option>
                        <option value="Europe/Paris">Paris (CET)</option>
                        <option value="Europe/Berlin">Berlin (CET)</option>
                        <option value="Europe/Madrid">Madrid (CET)</option>
                        <option value="Europe/Rome">Rome (CET)</option>
                        <option value="Europe/Amsterdam">Amsterdam (CET)</option>
                        <option value="Europe/Brussels">Brussels (CET)</option>
                        <option value="Europe/Zurich">Zurich (CET)</option>
                      </optgroup>
                      <optgroup label="Asia/Pacific">
                        <option value="Asia/Tokyo">Tokyo (JST)</option>
                        <option value="Asia/Shanghai">Shanghai (CST)</option>
                        <option value="Asia/Hong_Kong">Hong Kong (HKT)</option>
                        <option value="Asia/Singapore">Singapore (SGT)</option>
                        <option value="Asia/Dubai">Dubai (GST)</option>
                        <option value="Australia/Sydney">Sydney (AEST)</option>
                        <option value="Australia/Melbourne">Melbourne (AEST)</option>
                        <option value="Pacific/Auckland">Auckland (NZST)</option>
                      </optgroup>
                    </select>
                  </div>
                  {timezoneInfo ? <div className="island-profile-info">{timezoneInfo}</div> : null}

                  <div className="island-profile-row" style={{ marginTop: '16px' }}>
                    <button
                      type="button"
                      className="island-profile-btn"
                      onClick={() => {
                        setShowPasswordForm(true);
                        setPasswordError('');
                        setPasswordSuccess('');
                        setOldPassword('');
                        setNewPassword('');
                        setConfirmPassword('');
                      }}
                    >
                      <i className="fa-solid fa-key" /> Change Password
                    </button>
                  </div>
                </div>
              ) : null}
            </div>
          </div>
        ) : (
          <div className="island-posts-panel">
            {postsLoading ? (
              <div className="island-posts-empty">Loading posts...</div>
            ) : userPosts.length ? (
              userPosts.map((post) => (
                <div key={post.id} className="island-post-row">
                  <div className="island-post-title">{post.title || "Untitled"}</div>
                  {post.snippet ? (
                    <div className="island-post-snippet">{post.snippet}</div>
                  ) : null}
                  <div className="island-post-meta">
                    {post.created_at ? post.created_at.slice(0, 10) : ""}
                  </div>
                </div>
              ))
            ) : (
              <div className="island-posts-empty">No posts yet.</div>
            )}
          </div>
        )}

        <div className="island-viewer-canvas-wrap">
          <div
            ref={containerRef}
            className="island-viewer-canvas"
            style={{ width: '100%', height: '600px' }}
          />
          <div className="island-tabbar island-tabbar-overlay">
            <button
              type="button"
              className={"island-tab" + (activeTab === "posts" ? " is-active" : "")}
              onClick={() => setActiveTab("posts")}
              title="Posts"
            >
              <i className="fa-solid fa-newspaper"></i>
            </button>
            <button
              type="button"
              className={"island-tab" + (activeTab === "profile" ? " is-active" : "")}
              onClick={() => setActiveTab("profile")}
              title="Profile"
            >
              <i className="fa-solid fa-user-gear"></i>
            </button>
          </div>
        </div>

        <div className="island-viewer-stats">
          <div className="stat">
            <span className="stat-value">{island.content_count || 0}</span>
            <span className="stat-label">Posts</span>
          </div>
          <div className="stat">
            <span className="stat-value">{island.visitors || 0}</span>
            <span className="stat-label">Visitors</span>
          </div>
          <div className="stat">
            <span className="stat-value">{island.terrain_type || 'tropical'}</span>
            <span className="stat-label">Terrain</span>
          </div>
        </div>

        <div className="island-viewer-footer">
          <p className="island-info">
            🌱 Seed: {island.seed} • 🎨 {island.color_palette || 'vibrant'} palette
          </p>
        </div>
      </div>

      {/* Password Change Modal */}
      {showPasswordForm && (
        <div className="password-modal-backdrop" onClick={() => setShowPasswordForm(false)}>
          <div className="password-modal" onClick={(e) => e.stopPropagation()}>
            <button className="password-modal-close" onClick={() => setShowPasswordForm(false)}>×</button>
            <h3 className="password-modal-title">Change Password</h3>
            <div className="password-modal-form">
              <div className="password-modal-field">
                <label>Current Password</label>
                <input
                  type="password"
                  value={oldPassword}
                  onChange={(e) => setOldPassword(e.target.value)}
                  placeholder="Enter current password"
                />
              </div>
              <div className="password-modal-field">
                <label>New Password</label>
                <input
                  type="password"
                  value={newPassword}
                  onChange={(e) => setNewPassword(e.target.value)}
                  placeholder="Min 8 characters"
                />
              </div>
              <div className="password-modal-field">
                <label>Confirm Password</label>
                <input
                  type="password"
                  value={confirmPassword}
                  onChange={(e) => setConfirmPassword(e.target.value)}
                  placeholder="Confirm new password"
                />
              </div>
              {passwordError && <div className="password-modal-error">{passwordError}</div>}
              {passwordSuccess && <div className="password-modal-success">{passwordSuccess}</div>}
              <button
                type="button"
                className="password-modal-submit"
                disabled={passwordLoading}
                onClick={async () => {
                  setPasswordError('');
                  setPasswordSuccess('');
                  if (newPassword.length < 8) {
                    setPasswordError('Password must be at least 8 characters');
                    return;
                  }
                  if (newPassword !== confirmPassword) {
                    setPasswordError('Passwords do not match');
                    return;
                  }
                  setPasswordLoading(true);
                  const res = await changePassword(oldPassword, newPassword);
                  setPasswordLoading(false);
                  if (res.ok) {
                    setPasswordSuccess('Password changed!');
                    setOldPassword('');
                    setNewPassword('');
                    setConfirmPassword('');
                    setTimeout(() => {
                      setShowPasswordForm(false);
                      setPasswordSuccess('');
                    }, 1500);
                  } else {
                    if (res.error === 'invalid_old_password') {
                      setPasswordError('Current password is incorrect');
                    } else {
                      setPasswordError(res.error || 'Failed to change password');
                    }
                  }
                }}
              >
                {passwordLoading ? 'Changing...' : 'Change Password'}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

/**
 * Create circle coordinates for polygon (ocean)
 */
function createCircleCoordinates(lng, lat, radius, points = 64) {
  const coords = [];
  for (let i = 0; i <= points; i++) {
    const angle = (i / points) * Math.PI * 2;
    coords.push([
      lng + Math.cos(angle) * radius,
      lat + Math.sin(angle) * radius
    ]);
  }
  return coords;
}

/**
 * Create island DOM element with seed-based styling
 */
function createIslandElement(seed, terrainType = 'tropical') {
  const rng = seededRandom(seed);

  const el = document.createElement('div');
  el.className = 'island-terrain-marker';

  const terrainColor = getTerrainColorCSS(terrainType);
  const size = 220 + rng() * 50; // 220-270px

  el.innerHTML = `
    <div style="
      width: ${size}px;
      height: ${size}px;
      border-radius: 50%;
      background: radial-gradient(circle at 30% 30%, ${terrainColor}ee, ${terrainColor}aa, ${terrainColor}77);
      box-shadow:
        0 0 40px ${terrainColor}88,
        0 20px 40px rgba(0,0,0,0.4),
        inset -10px -10px 30px rgba(0,0,0,0.3),
        inset 10px 10px 30px rgba(255,255,255,0.2);
      position: relative;
      animation: islandFloat 4s ease-in-out infinite;
    ">
      <div style="
        position: absolute;
        inset: 8px;
        border-radius: 50%;
        border: 6px solid rgba(255, 243, 199, 0.55);
        box-shadow: inset 0 0 12px rgba(255, 243, 199, 0.45);
      "></div>
      <div style="
        position: absolute;
        top: 12%;
        right: 18%;
        font-size: 22px;
        filter: drop-shadow(0 4px 6px rgba(0,0,0,0.4));
        animation: contentFloat 3s ease-in-out infinite;
      ">✨</div>
      ${createIslandTexture(seed, terrainType)}
    </div>
  `;

  return el;
}

function createIslandTexture(seed, terrainType) {
  // Add some visual detail with random spots/patches
  const rng = seededRandom(seed + 100);
  let spots = '';

  for (let i = 0; i < 8; i++) {
    const x = rng() * 80 + 10; // 10-90%
    const y = rng() * 80 + 10;
    const size = rng() * 20 + 10; // 10-30px
    spots += `
      <div style="
        position: absolute;
        left: ${x}%;
        top: ${y}%;
        width: ${size}px;
        height: ${size}px;
        border-radius: 50%;
        background: rgba(0,0,0,0.1);
        transform: translate(-50%, -50%);
      "></div>
    `;
  }

  return spots;
}

/**
 * Get terrain color as CSS string
 */
function getTerrainColorCSS(terrainType) {
  const palettes = {
    'tropical': '#2ecc71',
    'desert': '#f39c12',
    'arctic': '#ecf0f1',
    'volcanic': '#e74c3c',
    'meadow': '#27ae60',
  };
  return palettes[terrainType] || palettes['tropical'];
}

/**
 * Generate vegetation data based on seed
 */
function generateVegetationData(seed, terrainType = 'tropical') {
  const vegetation = [];
  const rng = seededRandom(seed);

  const count = terrainType === 'desert' ? 3 : terrainType === 'arctic' ? 1 : 8;

  for (let i = 0; i < count; i++) {
    const angle = rng() * Math.PI * 2;
    const radius = (0.2 + rng() * 0.3) * 0.0001; // Small offset in lng/lat

    vegetation.push({
      offsetX: Math.cos(angle) * radius,
      offsetY: Math.sin(angle) * radius,
      terrainType: terrainType,
      scale: 0.8 + rng() * 0.4
    });
  }

  return vegetation;
}

/**
 * Create tree DOM element
 */
function createTreeElement(terrainType) {
  const el = document.createElement('div');
  el.className = 'island-tree-marker';

  let treeHTML = '';

  if (terrainType === 'arctic') {
    treeHTML = `
      <div style="
        width: 0;
        height: 0;
        border-left: 15px solid transparent;
        border-right: 15px solid transparent;
        border-bottom: 40px solid #1a4d2e;
        position: relative;
        animation: treeSwaythe: 3s ease-in-out infinite;
      "></div>
    `;
  } else if (terrainType === 'desert') {
    treeHTML = `
      <div style="
        width: 12px;
        height: 50px;
        background: linear-gradient(to bottom, #3a5f0b, #2a4f0b);
        border-radius: 6px;
        position: relative;
        animation: treeSway 3s ease-in-out infinite;
      "></div>
    `;
  } else {
    // Tropical/meadow: stylized tree
    treeHTML = `
      <div style="position: relative; animation: treeSway 3s ease-in-out infinite;">
        <div style="
          width: 8px;
          height: 30px;
          background: #4a2511;
          margin: 0 auto;
        "></div>
        <div style="
          width: 0;
          height: 0;
          border-left: 20px solid transparent;
          border-right: 20px solid transparent;
          border-bottom: 30px solid #228b22;
          position: relative;
          top: -30px;
          left: 50%;
          transform: translateX(-50%);
        "></div>
        <div style="
          width: 0;
          height: 0;
          border-left: 16px solid transparent;
          border-right: 16px solid transparent;
          border-bottom: 25px solid #228b22;
          position: relative;
          top: -45px;
          left: 50%;
          transform: translateX(-50%);
        "></div>
      </div>
    `;
  }

  el.innerHTML = treeHTML;
  return el;
}

/**
 * Create content DOM element
 */
function createContentElement(content) {
  const el = document.createElement('div');
  el.className = 'island-content-marker';

  const color = content.content_type === 'post' ? '#3498db' :
                content.content_type === 'app' ? '#e74c3c' : '#f39c12';

  el.innerHTML = `
    <div style="
      width: 46px;
      height: 64px;
      background: linear-gradient(135deg, ${color}ee, ${color}aa);
      border-radius: 12px;
      box-shadow:
        0 4px 12px rgba(0,0,0,0.4),
        0 0 20px ${color}66;
      display: flex;
      align-items: center;
      justify-content: center;
      color: white;
      font-size: 24px;
      cursor: pointer;
      transition: all 0.3s ease;
      animation: contentFloat 2s ease-in-out infinite;
    " onmouseenter="this.style.transform='scale(1.2)'" onmouseleave="this.style.transform='scale(1)'">
      ${content.content_type === 'post' ? '📄' : content.content_type === 'app' ? '📱' : '📁'}
    </div>
  `;

  return el;
}

function resolveContentPosition(item, index, seed, used) {
  const rng = seededRandom(seed + index * 7 + 13);
  let x = Number.isFinite(item.position_x) ? item.position_x : 0.5;
  let y = Number.isFinite(item.position_y) ? item.position_y : 0.5;
  if (!Number.isFinite(x)) x = 0.5;
  if (!Number.isFinite(y)) y = 0.5;

  // If missing or stacked, scatter in a ring.
  const rawKey = `${Math.round(x * 1000)}:${Math.round(y * 1000)}`;
  const seen = used.get(rawKey) || 0;
  used.set(rawKey, seen + 1);
  if (seen > 0 || (x === 0.5 && y === 0.5)) {
    const angle = rng() * Math.PI * 2;
    const radius = 0.06 + rng() * 0.16 + seen * 0.03;
    x = 0.5 + Math.cos(angle) * radius;
    y = 0.5 + Math.sin(angle) * radius;
  }
  x = Math.max(0.1, Math.min(0.9, x));
  y = Math.max(0.1, Math.min(0.9, y));
  return { x, y };
}

/**
 * Seeded random number generator (deterministic)
 */
function seededRandom(seed) {
  let s = seed;
  return function() {
    s = (s * 9301 + 49297) % 233280;
    return s / 233280;
  };
}
