"use client";

import { useEffect, useRef, useState } from "react";
import * as THREE from "three";
import { LocateFixed, Minus, Pause, Play, Plus } from "lucide-react";
import { INDONESIA_POINTS, WORLD_POINTS } from "@/content/globe-points";
import { ensureGsap, prefersReducedMotion } from "@/lib/motion";
import type { Dictionary } from "@/lib/i18n";

/**
 * Interactive Archipelago Globe (Three.js).
 * - Dotted land from Natural Earth; Indonesia denser, in pulsing gold. Lit body shader with a
 *   gold rim, atmosphere glow and a slow orbit ring for depth.
 * - Interaction: drag (mouse / touch) to rotate, auto-rotation toggle, reset, zoom via buttons,
 *   +/- keys, pinch (touch), ctrl/⌘ + wheel or trackpad pinch, and plain wheel only once the
 *   globe is "engaged" (clicked) — released on pointer leave or Esc, so page scrolling is never
 *   hijacked by accident.
 * - Scroll: a scrubbed (reversible) reveal; the camera swings round to face Indonesia.
 * - Illustrative "connection" arcs to generic directions — not offices, projects or partners.
 * - Renders only while visible; on-demand rendering for reduced motion; 2D fallback without WebGL.
 */
const INDO = { lon: 118, lat: -2.5 };
const DEG = Math.PI / 180;
const GOLD = new THREE.Color("#d8c28c");
const ZOOM_MIN = 0.85;
const ZOOM_MAX = 2.6;
const TAU = Math.PI * 2;

function toVec(lon: number, lat: number, r = 1) {
  const phi = (90 - lat) * DEG;
  const theta = (lon + 180) * DEG;
  return new THREE.Vector3(-r * Math.sin(phi) * Math.cos(theta), r * Math.cos(phi), r * Math.sin(phi) * Math.sin(theta));
}

const pointVert = /* glsl */ `
  uniform float uSize; uniform float uPixelRatio; uniform float uTime; uniform float uPulse;
  attribute float aPhase;
  varying float vAlpha;
  void main() {
    vec4 mv = modelViewMatrix * vec4(position, 1.0);
    vec3 n = normalize(normalMatrix * normalize(position));
    float facing = dot(n, normalize(-mv.xyz));
    vAlpha = smoothstep(-0.05, 0.35, facing) * (1.0 - uPulse * 0.45 + uPulse * 0.45 * sin(uTime * 1.6 + aPhase * 6.2831));
    gl_PointSize = uSize * uPixelRatio * (2.6 / -mv.z);
    gl_Position = projectionMatrix * mv;
  }`;
const pointFrag = /* glsl */ `
  uniform vec3 uColor; uniform float uOpacity; varying float vAlpha;
  void main() {
    float d = length(gl_PointCoord - 0.5);
    if (d > 0.5) discard;
    float a = smoothstep(0.5, 0.2, d) * uOpacity * vAlpha;
    gl_FragColor = vec4(uColor, a);
  }`;
const arcVert = /* glsl */ `
  attribute float aU; varying float vU;
  void main() { vU = aU; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }`;
const arcFrag = /* glsl */ `
  uniform float uTime; uniform float uPhase; uniform vec3 uColor; uniform float uStatic; uniform float uReveal; varying float vU;
  void main() {
    float head = fract(uTime * 0.16 + uPhase) * 1.4;
    float d = head - vU;
    float trail = (d > 0.0 && d < 0.35) ? (1.0 - d / 0.35) : 0.0;
    float a = mix(0.10 + trail * 0.9, 0.35, uStatic) * uReveal;
    gl_FragColor = vec4(uColor, a);
  }`;
const bodyVert = /* glsl */ `
  varying vec3 vN; varying vec3 vView;
  void main() {
    vec4 mv = modelViewMatrix * vec4(position, 1.0);
    vN = normalize(normalMatrix * normal); vView = normalize(-mv.xyz);
    gl_Position = projectionMatrix * mv;
  }`;
const bodyFrag = /* glsl */ `
  varying vec3 vN; varying vec3 vView;
  void main() {
    vec3 L = normalize(vec3(-0.55, 0.45, 0.7));
    float diff = clamp(dot(vN, L), 0.0, 1.0);
    float rim = pow(1.0 - clamp(dot(vN, vView), 0.0, 1.0), 2.6);
    vec3 deep = vec3(0.016, 0.07, 0.16);
    vec3 navy = vec3(0.05, 0.19, 0.4);
    vec3 col = mix(deep, navy, diff) + vec3(0.85, 0.74, 0.5) * rim * 0.32;
    gl_FragColor = vec4(col, 0.96);
  }`;
const atmoVert = /* glsl */ `
  varying vec3 vNormal;
  void main() { vNormal = normalize(normalMatrix * normal); gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0); }`;
const atmoFrag = /* glsl */ `
  uniform float uIntensity; varying vec3 vNormal;
  void main() {
    float i = pow(0.62 - dot(vNormal, vec3(0.0, 0.0, 1.0)), 3.0) * uIntensity;
    gl_FragColor = vec4(mix(vec3(0.16, 0.36, 0.7), vec3(0.85, 0.76, 0.55), 0.4), 1.0) * i;
  }`;

function hasWebGL() {
  try {
    const c = document.createElement("canvas");
    return !!(c.getContext("webgl2") || c.getContext("webgl"));
  } catch {
    return false;
  }
}

/** Static orthographic fallback drawn on a 2D canvas. */
function drawFallback(canvas: HTMLCanvasElement) {
  const ctx = canvas.getContext("2d");
  if (!ctx) return;
  const dpr = Math.min(window.devicePixelRatio || 1, 2);
  const size = canvas.clientWidth;
  canvas.width = canvas.height = size * dpr;
  ctx.scale(dpr, dpr);
  const r = size * 0.42;
  const cx = size / 2;
  const cy = size / 2;
  const lon0 = INDO.lon * DEG;
  const lat0 = INDO.lat * DEG;
  const project = (lon: number, lat: number) => {
    const l = lon * DEG;
    const p = lat * DEG;
    const cosc = Math.sin(lat0) * Math.sin(p) + Math.cos(lat0) * Math.cos(p) * Math.cos(l - lon0);
    if (cosc < 0) return null;
    return [cx + r * Math.cos(p) * Math.sin(l - lon0), cy - r * (Math.cos(lat0) * Math.sin(p) - Math.sin(lat0) * Math.cos(p) * Math.cos(l - lon0))];
  };
  ctx.fillStyle = "#082d61";
  ctx.beginPath();
  ctx.arc(cx, cy, r, 0, Math.PI * 2);
  ctx.fill();
  const plot = (pts: Float32Array, color: string, s: number) => {
    ctx.fillStyle = color;
    for (let i = 0; i < pts.length; i += 2) {
      const p = project(pts[i], pts[i + 1]);
      if (p) ctx.fillRect(p[0], p[1], s, s);
    }
  };
  plot(WORLD_POINTS, "rgba(255,255,255,0.45)", 1.4);
  plot(INDONESIA_POINTS, "#d8c28c", 1.6);
}

type Api = { zoomBy: (f: number) => void; setAuto: (on: boolean) => void; reset: () => void };
type Labels = Pick<
  Dictionary["vision"],
  "globeLabel" | "globeControls" | "zoomIn" | "zoomOut" | "resetView" | "rotateStop" | "rotateStart" | "zoomActive"
>;

export default function ArchipelagoGlobe({ t }: { t: Labels }) {
  const wrap = useRef<HTMLDivElement>(null);
  const stage = useRef<HTMLDivElement>(null);
  const canvasRef = useRef<HTMLCanvasElement>(null);
  const api = useRef<Api | null>(null);
  const [auto, setAuto] = useState(() => !prefersReducedMotion());
  const [engaged, setEngaged] = useState(false);
  // Client-only component (loaded with ssr: false), so these can be read during render.
  const [webgl] = useState(hasWebGL);

  useEffect(() => {
    const container = stage.current;
    const outer = wrap.current;
    const canvas = canvasRef.current;
    if (!container || !outer || !canvas) return;
    if (!webgl) {
      drawFallback(canvas);
      return;
    }
    const reduced = prefersReducedMotion();
    const isSmall = window.matchMedia("(max-width: 767px)").matches;

    const renderer = new THREE.WebGLRenderer({ canvas, antialias: !isSmall, alpha: true, powerPreference: "low-power" });
    const pixelRatio = Math.min(window.devicePixelRatio || 1, isSmall ? 1.5 : 2);
    renderer.setPixelRatio(pixelRatio);
    const scene = new THREE.Scene();
    const camera = new THREE.PerspectiveCamera(35, 1, 0.1, 100);
    camera.position.set(0, 0, 5.4);

    const tilt = new THREE.Group();
    const spin = new THREE.Group();
    tilt.add(spin);
    scene.add(tilt);

    // Body — lit navy sphere with a warm rim
    spin.add(
      new THREE.Mesh(
        new THREE.SphereGeometry(0.995, isSmall ? 48 : 64, isSmall ? 48 : 64),
        new THREE.ShaderMaterial({ vertexShader: bodyVert, fragmentShader: bodyFrag, transparent: true }),
      ),
    );
    // Atmosphere
    const uIntensity = { value: reduced ? 1 : 0 };
    const atmo = new THREE.Mesh(
      new THREE.SphereGeometry(1.18, 64, 64),
      new THREE.ShaderMaterial({
        vertexShader: atmoVert,
        fragmentShader: atmoFrag,
        uniforms: { uIntensity },
        side: THREE.BackSide,
        blending: THREE.AdditiveBlending,
        transparent: true,
        depthWrite: false,
      }),
    );
    scene.add(atmo);

    // Orbit ring (depth cue)
    const ringPts: THREE.Vector3[] = [];
    for (let i = 0; i <= 160; i++) {
      const a = (i / 160) * TAU;
      ringPts.push(new THREE.Vector3(Math.cos(a) * 1.42, 0, Math.sin(a) * 1.42));
    }
    const ringMat = new THREE.LineDashedMaterial({ color: GOLD, transparent: true, opacity: 0, dashSize: 0.03, gapSize: 0.05 });
    const ring = new THREE.Line(new THREE.BufferGeometry().setFromPoints(ringPts), ringMat);
    ring.computeLineDistances();
    ring.rotation.set(1.2, 0, 0.35);
    scene.add(ring);

    const uTime = { value: 0 };
    const uReveal = { value: reduced ? 1 : 0 };
    const makePoints = (data: Float32Array, color: THREE.Color, size: number, opacity: number, pulse: number, step = 1) => {
      const n = Math.floor(data.length / 2 / step);
      const pos = new Float32Array(n * 3);
      const phase = new Float32Array(n);
      for (let i = 0; i < n; i++) {
        const j = i * step;
        const v = toVec(data[j * 2], data[j * 2 + 1], 1.004);
        pos.set([v.x, v.y, v.z], i * 3);
        phase[i] = Math.random();
      }
      const g = new THREE.BufferGeometry();
      g.setAttribute("position", new THREE.BufferAttribute(pos, 3));
      g.setAttribute("aPhase", new THREE.BufferAttribute(phase, 1));
      const m = new THREE.ShaderMaterial({
        vertexShader: pointVert,
        fragmentShader: pointFrag,
        transparent: true,
        depthWrite: false,
        uniforms: {
          uSize: { value: size },
          uPixelRatio: { value: pixelRatio },
          uColor: { value: color },
          uOpacity: { value: opacity },
          uTime,
          uPulse: { value: reduced ? 0 : pulse },
        },
      });
      return new THREE.Points(g, m);
    };
    // Lighter world layer on small screens.
    spin.add(makePoints(WORLD_POINTS, new THREE.Color("#cfd8e6"), isSmall ? 3.8 : 3.4, 0.55, 0, isSmall ? 2 : 1));
    spin.add(makePoints(INDONESIA_POINTS, GOLD, 4.4, 1, 1));

    // Illustrative arcs from the archipelago outward (generic directions, not locations).
    const start = toVec(INDO.lon, INDO.lat);
    const ends: [number, number][] = [
      [INDO.lon - 150, 38],
      [INDO.lon - 95, 52],
      [INDO.lon - 55, 22],
      [INDO.lon - 30, -32],
      [INDO.lon + 28, 36],
      [INDO.lon + 62, -24],
      [INDO.lon + 105, 30],
    ];
    ends.forEach(([lon, lat], k) => {
      const end = toVec(lon, lat);
      const seg = 80;
      const pos = new Float32Array((seg + 1) * 3);
      const us = new Float32Array(seg + 1);
      const angle = start.angleTo(end);
      for (let i = 0; i <= seg; i++) {
        const u = i / seg;
        const v = new THREE.Vector3().copy(start).lerp(end, u).normalize();
        v.multiplyScalar(1.004 + Math.sin(Math.PI * u) * angle * 0.22);
        pos.set([v.x, v.y, v.z], i * 3);
        us[i] = u;
      }
      const g = new THREE.BufferGeometry();
      g.setAttribute("position", new THREE.BufferAttribute(pos, 3));
      g.setAttribute("aU", new THREE.BufferAttribute(us, 1));
      const m = new THREE.ShaderMaterial({
        vertexShader: arcVert,
        fragmentShader: arcFrag,
        transparent: true,
        depthWrite: false,
        blending: THREE.AdditiveBlending,
        uniforms: { uTime, uReveal, uPhase: { value: k / ends.length }, uColor: { value: GOLD }, uStatic: { value: reduced ? 1 : 0 } },
      });
      spin.add(new THREE.Line(g, m));
    });

    // ── State ────────────────────────────────────────────────────────────
    const indoY = -(INDO.lon + 90) * DEG;
    const state = {
      focus: reduced ? 1 : 0, // scroll-driven: 0 = arriving, 1 = facing Indonesia
      userY: 0,
      userX: 0,
      phase: 0,
      velY: 0,
      zoom: 1,
      zoomTarget: 1,
      auto: !reduced,
      dragging: false,
      engaged: false,
    };

    let visible = false;
    let raf = 0;
    const timer = new THREE.Timer();
    const requestRender = () => {
      if (!raf && visible) raf = requestAnimationFrame(loop);
    };
    function loop() {
      raf = 0;
      timer.update();
      const dt = Math.min(timer.getDelta(), 0.05);
      if (!reduced) uTime.value = timer.getElapsed();
      // Auto-rotation: a slow, continuous sweep either side of the archipelago (±32°), so
      // Indonesia always stays in view. Starts once the camera has settled on Indonesia.
      if (state.auto && !state.dragging && state.focus > 0.98) state.phase += dt * 0.22;
      // Drag inertia
      if (!state.dragging && Math.abs(state.velY) > 0.0001) {
        state.userY += state.velY;
        state.velY *= Math.pow(0.04, dt);
      }
      state.zoom += (state.zoomTarget - state.zoom) * Math.min(1, dt * 7);
      spin.rotation.y = indoY - (1 - state.focus) * 2.4 + state.userY + Math.sin(state.phase) * 0.56;
      tilt.rotation.x = INDO.lat * DEG * state.focus + 0.32 * (1 - state.focus) + state.userX;
      const base = 5.4 - state.focus * 1.05;
      camera.position.z = base / state.zoom;
      camera.position.y = (1 - state.focus) * 0.35;
      camera.lookAt(0, 0, 0);
      ring.rotation.y += reduced ? 0 : dt * 0.05;
      ringMat.opacity = 0.22 * uReveal.value;
      renderer.render(scene, camera);
      const settling = Math.abs(state.zoomTarget - state.zoom) > 0.001 || Math.abs(state.velY) > 0.0001;
      if (visible && (!reduced || state.dragging || settling)) raf = requestAnimationFrame(loop);
    }

    const resize = () => {
      const s = container.clientWidth;
      renderer.setSize(s, s, false);
      camera.aspect = 1;
      camera.updateProjectionMatrix();
      requestRender();
    };

    // Visibility gating
    const io = new IntersectionObserver(
      ([e]) => {
        visible = e.isIntersecting && !document.hidden;
        if (visible) {
          timer.update();
          requestRender();
        } else if (raf) {
          cancelAnimationFrame(raf);
          raf = 0;
        }
      },
      { rootMargin: "100px" },
    );
    io.observe(container);
    const onVis = () => {
      const r = container.getBoundingClientRect();
      visible = !document.hidden && r.bottom > 0 && r.top < window.innerHeight;
      if (visible) requestRender();
    };
    document.addEventListener("visibilitychange", onVis);

    // ── Zoom ─────────────────────────────────────────────────────────────
    const setZoom = (z: number) => {
      state.zoomTarget = Math.max(ZOOM_MIN, Math.min(ZOOM_MAX, z));
      container.dataset.zoom = state.zoomTarget.toFixed(2); // exposed state (styling hooks / QA)
      requestRender();
    };
    const engage = (on: boolean) => {
      if (state.engaged === on) return;
      state.engaged = on;
      // Lenis must ignore wheel events over the globe only while it is engaged.
      if (on) container.setAttribute("data-lenis-prevent-wheel", "");
      else container.removeAttribute("data-lenis-prevent-wheel");
      setEngaged(on);
    };
    const onWheel = (e: WheelEvent) => {
      // ctrl/⌘ + wheel (and desktop trackpad pinch, which reports ctrlKey) always zooms here;
      // a plain wheel zooms only when the visitor has engaged the globe.
      if (!e.ctrlKey && !e.metaKey && !state.engaged) return;
      e.preventDefault();
      const dy = e.deltaMode === 1 ? e.deltaY * 16 : e.deltaY;
      setZoom(state.zoomTarget * Math.exp(-dy * (e.ctrlKey ? 0.01 : 0.0018)));
    };
    container.addEventListener("wheel", onWheel, { passive: false });

    // ── Pointer: drag rotate, pinch zoom ─────────────────────────────────
    const pointers = new Map<number, { x: number; y: number }>();
    let pinchDist = 0;
    let pinchZoom = 1;
    const dist = () => {
      const [a, b] = [...pointers.values()];
      return Math.hypot(a.x - b.x, a.y - b.y);
    };
    const down = (e: PointerEvent) => {
      pointers.set(e.pointerId, { x: e.clientX, y: e.clientY });
      if (e.pointerType === "mouse") engage(true);
      try {
        canvas.setPointerCapture(e.pointerId);
      } catch {
        /* pointer already released */
      }
      if (pointers.size === 2) {
        pinchDist = dist();
        pinchZoom = state.zoomTarget;
        state.dragging = false;
      } else {
        state.dragging = true;
        state.velY = 0;
        container.dataset.dragging = "true";
      }
      requestRender();
    };
    const move = (e: PointerEvent) => {
      const p = pointers.get(e.pointerId);
      if (!p) return;
      const dx = e.clientX - p.x;
      const dy = e.clientY - p.y;
      p.x = e.clientX;
      p.y = e.clientY;
      if (pointers.size >= 2) {
        if (pinchDist > 0) setZoom(pinchZoom * (dist() / pinchDist));
        return;
      }
      if (!state.dragging) return;
      const k = 0.006 / state.zoom;
      state.userY += dx * k;
      state.velY = dx * k;
      // Touch keeps vertical swipes for page scrolling (touch-action: pan-y).
      if (e.pointerType !== "touch") state.userX = Math.max(-0.6, Math.min(0.6, state.userX + dy * 0.004));
      requestRender();
    };
    const up = (e: PointerEvent) => {
      pointers.delete(e.pointerId);
      if (pointers.size < 2) pinchDist = 0;
      if (pointers.size === 0) {
        state.dragging = false;
        container.dataset.dragging = "false";
        container.dataset.rotation = state.userY.toFixed(2);
      }
      requestRender();
    };
    const leave = () => engage(false);
    canvas.addEventListener("pointerdown", down);
    canvas.addEventListener("pointermove", move);
    canvas.addEventListener("pointerup", up);
    canvas.addEventListener("pointercancel", up);
    outer.addEventListener("pointerleave", leave);

    // ── Public API (buttons) + keyboard ──────────────────────────────────
    const { gsap, ScrollTrigger } = ensureGsap();
    const reset = () => {
      state.velY = 0;
      const targetY = Math.round(state.userY / TAU) * TAU; // nearest full turn: no long unwind
      gsap.to(state, {
        userY: targetY,
        userX: 0,
        phase: Math.round(state.phase / Math.PI) * Math.PI, // sweep back to centre
        overwrite: true,
        zoomTarget: 1,
        duration: reduced ? 0 : 1.4,
        ease: "expo.inOut",
        onUpdate: requestRender,
        onComplete: () => {
          state.userY = 0;
          state.phase = 0;
          container.dataset.zoom = "1.00";
          container.dataset.rotation = "0.00";
          requestRender();
        },
      });
    };
    api.current = {
      zoomBy: (f) => setZoom(state.zoomTarget * f),
      setAuto: (on) => {
        state.auto = on;
        requestRender();
      },
      reset,
    };
    const key = (e: KeyboardEvent) => {
      if (e.key === "ArrowLeft" || e.key === "ArrowRight") {
        e.preventDefault();
        state.userY += e.key === "ArrowLeft" ? -0.25 : 0.25;
      } else if (e.key === "ArrowUp" || e.key === "ArrowDown") {
        e.preventDefault();
        state.userX = Math.max(-0.6, Math.min(0.6, state.userX + (e.key === "ArrowUp" ? -0.12 : 0.12)));
      } else if (e.key === "+" || e.key === "=") {
        e.preventDefault();
        setZoom(state.zoomTarget * 1.25);
      } else if (e.key === "-" || e.key === "_") {
        e.preventDefault();
        setZoom(state.zoomTarget / 1.25);
      } else if (e.key === "0" || e.key === "Home") {
        e.preventDefault();
        reset();
      } else if (e.key === "Escape") {
        engage(false);
        return;
      } else return;
      requestRender();
    };
    container.addEventListener("keydown", key);

    // ── Scroll: reversible reveal + camera swing to Indonesia ────────────
    let st: { kill: () => void } | undefined;
    if (!reduced) {
      st = ScrollTrigger.create({
        trigger: container,
        start: "top 92%",
        end: "center 55%",
        scrub: 0.8,
        onUpdate: (self) => {
          const p = self.progress;
          state.focus = p;
          uIntensity.value = 0.25 + p * 0.75;
          uReveal.value = Math.max(0, (p - 0.35) / 0.65);
          gsap.set(container, { scale: 0.82 + p * 0.18, opacity: Math.min(1, 0.15 + p * 1.2) });
          requestRender();
        },
        onLeaveBack: () => engage(false),
      });
    }

    const ro = new ResizeObserver(resize);
    ro.observe(container);
    resize();

    return () => {
      st?.kill();
      gsap.killTweensOf(state);
      ro.disconnect();
      io.disconnect();
      api.current = null;
      document.removeEventListener("visibilitychange", onVis);
      container.removeEventListener("keydown", key);
      container.removeEventListener("wheel", onWheel);
      canvas.removeEventListener("pointerdown", down);
      canvas.removeEventListener("pointermove", move);
      canvas.removeEventListener("pointerup", up);
      canvas.removeEventListener("pointercancel", up);
      outer.removeEventListener("pointerleave", leave);
      cancelAnimationFrame(raf);
      scene.traverse((o) => {
        const m = o as THREE.Mesh;
        m.geometry?.dispose();
        const mat = m.material as THREE.Material | THREE.Material[] | undefined;
        if (Array.isArray(mat)) mat.forEach((x) => x.dispose());
        else mat?.dispose();
      });
      renderer.dispose();
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const btn =
    "inline-flex h-10 w-10 items-center justify-center rounded-full border border-white/20 bg-navy-ink/40 text-white/80 backdrop-blur-md transition hover:border-gold hover:text-gold focus-visible:border-gold disabled:opacity-40";

  return (
    <div ref={wrap} className="relative">
      {/* soft halo behind the globe */}
      <div
        aria-hidden="true"
        className="pointer-events-none absolute inset-[8%] rounded-full bg-[radial-gradient(circle,rgb(216_194_140/0.16),transparent_65%)] blur-2xl"
      />
      <div
        ref={stage}
        role="img"
        aria-label={t.globeLabel}
        tabIndex={0}
        className="globe-stage relative aspect-square w-full cursor-grab touch-pan-y select-none outline-none data-[dragging=true]:cursor-grabbing focus-visible:ring-1 focus-visible:ring-gold/60 rounded-full"
      >
        {/* soft circular lens: when zoomed in, the globe never shows the square canvas edge */}
        <canvas
          ref={canvasRef}
          className="absolute inset-0 h-full w-full [mask-image:radial-gradient(circle,#000_62%,transparent_71%)]"
        />
        <span
          aria-hidden="true"
          className={`pointer-events-none absolute left-1/2 top-3 -translate-x-1/2 whitespace-nowrap rounded-full border border-gold/40 bg-navy-ink/60 px-3 py-1 text-[0.62rem] uppercase tracking-[0.2em] text-gold-light backdrop-blur transition-all duration-500 ${engaged ? "translate-y-0 opacity-100" : "-translate-y-2 opacity-0"}`}
        >
          {t.zoomActive}
        </span>
      </div>

      {webgl && (
        <div role="group" aria-label={t.globeControls} className="globe-controls absolute bottom-2 right-0 flex flex-col gap-2 sm:bottom-6">
          <button type="button" className={btn} aria-label={t.zoomIn} onClick={() => api.current?.zoomBy(1.3)}>
            <Plus size={16} aria-hidden="true" />
          </button>
          <button type="button" className={btn} aria-label={t.zoomOut} onClick={() => api.current?.zoomBy(1 / 1.3)}>
            <Minus size={16} aria-hidden="true" />
          </button>
          <button
            type="button"
            className={btn}
            aria-label={auto ? t.rotateStop : t.rotateStart}
            aria-pressed={auto}
            onClick={() => {
              const next = !auto;
              setAuto(next);
              api.current?.setAuto(next);
            }}
          >
            {auto ? <Pause size={15} aria-hidden="true" /> : <Play size={15} className="translate-x-px" aria-hidden="true" />}
          </button>
          <button type="button" className={btn} aria-label={t.resetView} onClick={() => api.current?.reset()}>
            <LocateFixed size={16} aria-hidden="true" />
          </button>
        </div>
      )}
    </div>
  );
}
