// PonteREI — Globe (3D via globe.gl) + 2D map fallback

function Globe3D({ properties, ghostPins, onPinClick }) {
  const wrapRef = useRef(null);
  const globeRef = useRef(null);
  const [tooltip, setTooltip] = useState(null);
  const { locale } = useLocale();

  useEffect(() => {
    if (!window.Globe || !wrapRef.current) return;

    const activePoints = properties.map((p) => ({
      lat: p.address.lat,
      lng: p.address.lng,
      label: localized(p.title, locale),
      city: `${p.address.city}, ${localized(p.address.country, locale)}`,
      yield: p.financials.projectedAnnualYield,
      img: p.images[0],
      slug: p.slug,
      ghost: false,
      color: "#E85D3A",
    }));
    const ghostPoints = ghostPins.map((g) => ({
      lat: g.lat,
      lng: g.lng,
      label: g.city,
      city: g.city,
      ghost: true,
      color: "#5A665E",
    }));
    const allPoints = [...ghostPoints, ...activePoints];

    const g = window.Globe()(wrapRef.current)
      .globeImageUrl("https://unpkg.com/three-globe@2.31.1/example/img/earth-night.jpg")
      .bumpImageUrl("https://unpkg.com/three-globe@2.31.1/example/img/earth-topology.png")
      .backgroundColor("rgba(20, 32, 26, 1)")
      .atmosphereColor("#E85D3A")
      .atmosphereAltitude(0.18)
      .pointsData(allPoints)
      .pointLat("lat")
      .pointLng("lng")
      .pointColor("color")
      .pointAltitude(0.015)
      .pointRadius((d) => (d.ghost ? 0.35 : 0.55))
      .pointsMerge(false)
      .ringsData(activePoints)
      .ringLat("lat")
      .ringLng("lng")
      .ringColor(() => () => "rgba(232, 93, 58, 0.7)")
      .ringMaxRadius(2.5)
      .ringPropagationSpeed(1.2)
      .ringRepeatPeriod(1400)
      .onPointClick((d) => { if (!d.ghost && onPinClick) onPinClick(d.slug); })
      .onPointHover((d) => {
        if (!d) { setTooltip(null); return; }
        setTooltip(d);
      });

    globeRef.current = g;

    // sizing
    const fit = () => {
      if (!wrapRef.current) return;
      const r = wrapRef.current.getBoundingClientRect();
      g.width(r.width).height(r.height);
    };
    fit();
    const ro = new ResizeObserver(fit);
    ro.observe(wrapRef.current);

    // auto-rotate
    const controls = g.controls();
    controls.autoRotate = true;
    controls.autoRotateSpeed = 0.5;
    controls.enableZoom = false;

    // initial pov on Brazil
    g.pointOfView({ lat: -10, lng: -50, altitude: 2.5 }, 0);

    return () => { ro.disconnect(); if (wrapRef.current) wrapRef.current.innerHTML = ""; };
  }, [properties, ghostPins, locale, onPinClick]);

  return (
    <div ref={wrapRef} className="globe-canvas">
      {tooltip && (
        <div className={`globe-tooltip ${tooltip.ghost ? "ghost" : ""} ${!tooltip.ghost && tooltip.img ? "has-img" : ""}`}
             style={{ top: 16, right: 16 }}>
          {!tooltip.ghost && tooltip.img && <div className="tip-img" style={{ backgroundImage: `url(${tooltip.img})` }} />}
          <div className="tip-body" style={{ padding: tooltip.ghost ? "10px 12px" : "10px 12px" }}>
            <div className="tip-city">{tooltip.city}</div>
            {!tooltip.ghost && (
              <>
                <div className="tip-title">{tooltip.label}</div>
                <div className="tip-meta">
                  <span className="muted">{t("globe.tooltipYield", locale)}</span>
                  <strong>{formatPctLocalized(tooltip.yield, locale)}</strong>
                </div>
              </>
            )}
            {tooltip.ghost && <div style={{ fontSize: 11, opacity: 0.7, marginTop: 4 }}>{t("globe.legendSoon", locale)}</div>}
          </div>
        </div>
      )}
    </div>
  );
}

function Globe2D({ properties, ghostPins, onPinClick }) {
  const { locale } = useLocale();
  const project = (lat, lng) => {
    // simple equirectangular -> %
    const x = ((lng + 180) / 360) * 100;
    const y = ((90 - lat) / 180) * 100;
    return { x, y };
  };
  const [hover, setHover] = useState(null);

  return (
    <div className="map2d">
      <svg viewBox="0 0 1000 500" className="map2d-svg" preserveAspectRatio="xMidYMid meet">
        {/* Stylized world graticule */}
        <defs>
          <pattern id="dots" x="0" y="0" width="14" height="14" patternUnits="userSpaceOnUse">
            <circle cx="3" cy="3" r="1.4" fill="rgba(232, 93, 58, 0.18)" />
          </pattern>
        </defs>
        <rect width="1000" height="500" fill="url(#dots)" />
        {/* Major continent outlines (approximated polygons) */}
        <g fill="none" stroke="rgba(242, 237, 229, 0.28)" strokeWidth="1.2">
          <path d="M 150 90 Q 240 70 320 110 Q 400 130 380 200 Q 320 250 240 230 Q 170 200 150 130 Z" />
          <path d="M 480 100 Q 580 80 680 110 Q 780 100 850 150 Q 870 220 800 250 Q 700 240 600 220 Q 510 180 480 130 Z" />
          <path d="M 280 250 Q 320 270 360 320 Q 380 380 340 430 Q 290 460 270 410 Q 250 350 280 280 Z" />
          <path d="M 540 250 Q 600 280 620 340 Q 600 400 560 410 Q 520 380 530 320 Z" />
          <path d="M 770 270 Q 830 290 850 330 Q 830 360 790 360 Q 750 330 770 290 Z" />
        </g>
      </svg>
      {ghostPins.map((g, i) => {
        const { x, y } = project(g.lat, g.lng);
        return (
          <div key={"g" + i} className="pin-2d ghost" style={{ left: x + "%", top: y + "%" }}
               onMouseEnter={() => setHover({ ...g, ghost: true })}
               onMouseLeave={() => setHover(null)}
               title={g.city} />
        );
      })}
      {properties.map((p) => {
        const { x, y } = project(p.address.lat, p.address.lng);
        return (
          <div key={p.id} className="pin-2d" style={{ left: x + "%", top: y + "%" }}
               onMouseEnter={() => setHover({ city: `${p.address.city}, ${localized(p.address.country, locale)}`, label: localized(p.title, locale), yield: p.financials.projectedAnnualYield, img: p.images[0], ghost: false })}
               onMouseLeave={() => setHover(null)}
               onClick={() => onPinClick && onPinClick(p.slug)} />
        );
      })}
      {hover && (
        <div className={`globe-tooltip ${hover.ghost ? "ghost" : ""} ${!hover.ghost && hover.img ? "has-img" : ""}`}
             style={{ top: 16, right: 16 }}>
          {!hover.ghost && hover.img && <div className="tip-img" style={{ backgroundImage: `url(${hover.img})` }} />}
          <div className="tip-body">
            <div className="tip-city">{hover.city}</div>
            {!hover.ghost && (
              <>
                <div className="tip-title">{hover.label}</div>
                <div className="tip-meta">
                  <span className="muted">{t("globe.tooltipYield", locale)}</span>
                  <strong>{formatPctLocalized(hover.yield, locale)}</strong>
                </div>
              </>
            )}
            {hover.ghost && <div style={{ fontSize: 11, opacity: 0.7, marginTop: 4 }}>{t("globe.legendSoon", locale)}</div>}
          </div>
        </div>
      )}
    </div>
  );
}

function GlobeSection({ globeMode, setGlobeMode }) {
  const { locale } = useLocale();
  const { navigate } = useRouter();
  const properties = window.PROPERTIES;
  const ghostPins = window.GHOST_PINS;

  const handlePinClick = (slug) => navigate(`/property/${slug}`);

  return (
    <section className="section section-bg-deep">
      <div className="container">
        <div className="section-head" style={{ textAlign: "center", marginInline: "auto" }}>
          <div className="eyebrow">{t("globe.eyebrow", locale)}</div>
          <h2 style={{ color: "#F2EDE5" }}>{t("globe.title", locale)}</h2>
          <p>{t("globe.sub", locale)}</p>
        </div>

        <div className="globe-wrap">
          {globeMode === "3d" ? (
            <Globe3D properties={properties} ghostPins={ghostPins} onPinClick={handlePinClick} />
          ) : (
            <Globe2D properties={properties} ghostPins={ghostPins} onPinClick={handlePinClick} />
          )}

          <div className="globe-overlay">
            <div className="globe-legend">
              <span className="globe-legend-item">
                <span className="globe-legend-dot" style={{ background: "#E85D3A" }} />
                {t("globe.legendActive", locale)}
              </span>
              <span className="globe-legend-item">
                <span className="globe-legend-dot" style={{ background: "#9CA29C" }} />
                {t("globe.legendSoon", locale)}
              </span>
            </div>
            <div className="globe-toggle">
              <button className={globeMode === "3d" ? "active" : ""} onClick={() => setGlobeMode("3d")}>{t("globe.toggle3D", locale)}</button>
              <button className={globeMode === "2d" ? "active" : ""} onClick={() => setGlobeMode("2d")}>{t("globe.toggle2D", locale)}</button>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}

Object.assign(window, { Globe3D, Globe2D, GlobeSection });
