import { jsxs as m, jsx as n } from "react/jsx-runtime";
import { useReducer as U, useRef as w, useEffect as H } from "react";
import J from "react-use/lib/useSpring";
import * as N from "d3-geo";
import * as V from "topojson-client";
import D from "versor";
import R from "./countries.json.js";
import X from "./util.js";
import { withDeprecated as Y } from "../Util/deprecate.js";
import { styled as B } from "../Theme/index.js";
const F = V.feature(R, R.objects.ne_110m_admin_0_countries), K = {
  light: {
    ocean: "#EDF4F4",
    graticule: "#EDF4F4",
    land: "#CCEAEA",
    activeLand: "#AFD3D3",
    border: "#AFD3D3",
    marker: "#4E6AF6",
    activeMarker: "#4E6AF6"
  },
  dark: {
    ocean: "#09233B",
    graticule: "#09233B",
    land: "#0D2344",
    activeLand: "#173159",
    border: "#89DDD9",
    marker: "#ffffff",
    activeMarker: "#FFD159"
  }
};
function Q(e, s) {
  switch (s.type) {
    case "dragEnd":
      return { ...e, isDragging: !1 };
    case "dragStart":
      return {
        ...e,
        isDragging: !0,
        animationDuration: 1,
        mousePosition: s.payload.mousePosition
      };
    case "tooltip":
    case "rotate":
      return Object.assign({}, e, s.payload);
    default:
      return e;
  }
}
function W({
  theme: e = "dark",
  width: s = 1200,
  height: g = 600,
  enableRotation: I = !1,
  rotationSpeed: M = 5,
  activeMarkerId: i = void 0,
  markers: y = [],
  colors: L = {}
}) {
  const $ = Object.assign(L, K[e]), [r, d] = U(Q, {
    rotation: [0, 0, 0],
    isDragging: !1,
    animateDuration: 1,
    mousePosition: null,
    tooltipIndex: -1
  }), E = w(null), x = w({}), k = w({
    p1: null,
    p2: [0, 0],
    r1: null,
    r2: [0, 0, 0],
    step: 0,
    markerId: null,
    iv: null
  }), C = J(r.animateDuration, 170, 26), S = i && k.current.markerId !== i && y.some((t) => t.id === i), p = N.geoOrthographic().fitExtent(
    [
      [30, 30],
      [s - 30, g - 30]
    ],
    F
  ).rotate(
    C <= 1 || r.isDragging || !i ? r.rotation : k.current.iv(C / r.animateDuration)
  ), P = N.geoPath().projection(p).pointRadius(2);
  H(() => {
    if (S) {
      let { p1: t, p2: o, r1: a, r2: u, markerId: c } = k.current;
      if (c !== i && !r.isDragging) {
        const l = y.find((v) => v.id === i);
        t = o, o = [l.longitude, l.latitude], a = u, u = [-o[0], 20 - o[1], p.rotate()[2]];
        const h = X.interpolateAngles(a, u);
        Object.assign(k.current, {
          p1: t,
          p2: o,
          r1: a,
          r2: u,
          iv: h,
          markerId: i
        });
        const f = r.animateDuration * 2;
        d({
          type: "rotate",
          payload: {
            animateDuration: f > 1e3 ? 2 : f
          }
        });
      }
    } else if (I) {
      const t = window.requestAnimationFrame(() => {
        const o = [r.rotation[0] + 2 / M, r.rotation[1], r.rotation[2]];
        d({ type: "rotate", payload: { rotation: o } });
      });
      return function() {
        window.cancelAnimationFrame(t);
      };
    }
  });
  const b = (t) => {
    const o = E.current, a = o?.getBoundingClientRect();
    return [t.clientX - a.left - o.clientLeft, t.clientY - a.top - o.clientTop];
  }, T = (t) => {
    const o = b(t);
    o[0] && (x.current.v0 = D.cartesian(p.invert(o)), x.current.r0 = p.rotate(), x.current.q0 = D(x.current.r0), d({ type: "dragStart", payload: { mousePosition: o } }));
  }, z = (t) => {
    if (r.isDragging === !1)
      return;
    const o = b(t), { r0: a, v0: u, q0: c } = x.current, l = D.cartesian(p.rotate(a).invert(o)), h = D.multiply(c, D.delta(u, l)), f = D.rotation(h);
    d({ type: "rotate", payload: { rotation: f, mousePosition: o } });
  }, j = () => {
    setTimeout(() => {
      d({ type: "dragEnd", payload: {} });
    }, 200);
  }, A = (t, o) => d({
    type: "tooltip",
    payload: { tooltipIndex: o, mousePosition: b(t) }
  }), O = () => d({ type: "tooltip", payload: { tooltipIndex: -1, mousePosition: null } }), G = () => y.map((t, o) => {
    const a = [t.longitude, t.latitude], u = N.geoDistance(a, p.invert([s / 2, g / 2])), c = p(a), l = i === t.id, h = u > 1.57 ? "none" : l ? $.activeMarker : $.marker, f = l ? 9 : 6;
    return /* @__PURE__ */ m(
      "g",
      {
        className: `marker ${l ? "marker--active" : ""}`,
        onFocus: (v) => A(v, o),
        onBlur: O,
        onMouseOver: (v) => A(v, o),
        onMouseOut: O,
        children: [
          /* @__PURE__ */ n(
            "circle",
            {
              className: "marker__inner",
              r: f,
              cx: c[0],
              cy: c[1],
              fill: h,
              style: { fillOpacity: l ? 1 : 0.5 }
            },
            "marker-inner"
          ),
          /* @__PURE__ */ n(
            "circle",
            {
              className: "marker__outer",
              r: f * 2,
              cx: c[0],
              cy: c[1],
              fill: h,
              style: {
                animationDuration: l ? "800ms" : "1600ms",
                animationDelay: `${o * 0.2}s`,
                transformOrigin: `${c[0]}px ${c[1]}px`
              }
            },
            "marker-outer"
          )
        ]
      },
      t.id
    );
  }), q = () => {
    if (r.tooltipIndex >= 0) {
      const t = y[r.tooltipIndex];
      return /* @__PURE__ */ m(oo, { style: { left: r.mousePosition?.[0] ?? 0, top: r.mousePosition?.[1] ?? 0 }, children: [
        /* @__PURE__ */ n("p", { className: "title", children: t.title }),
        /* @__PURE__ */ n("p", { className: "description", children: t.description }),
        /* @__PURE__ */ m("p", { className: "description", children: [
          "ID: ",
          t.id
        ] })
      ] });
    }
  };
  let _ = null;
  if (i && y.some((t) => t.id === i)) {
    const t = y.find((o) => o.id === i);
    _ = F.features.findIndex(
      (o) => o.properties && o.properties.name && o.properties.name === t.country
    );
  }
  return /* @__PURE__ */ m(Z, { width: s, height: g, $theme: e, colors: $, onMouseLeave: j, children: [
    q(),
    /* @__PURE__ */ m(
      "svg",
      {
        className: "earth",
        width: s,
        height: g,
        onMouseDown: T,
        onMouseMove: z,
        onMouseUp: j,
        ref: E,
        children: [
          /* @__PURE__ */ n("rect", { className: "frame", width: s, height: g }),
          /* @__PURE__ */ n("circle", { cx: s / 2, cy: g / 2, r: p.scale(), className: "globe", filter: "url(#glow)" }),
          /* @__PURE__ */ n("path", { className: "graticule", d: P(N.geoGraticule().step([10, 10])()) }),
          /* @__PURE__ */ n("g", { className: "features", children: F.features.map((t, o) => /* @__PURE__ */ n(
            "path",
            {
              className: `country ${_ === o ? "country--active" : ""}`,
              d: P(t)
            },
            t.properties.name
          )) }),
          /* @__PURE__ */ n("g", { className: "markers", children: G() }),
          r.isDragging && r.mousePosition && /* @__PURE__ */ n(
            "path",
            {
              className: "point point-mouse",
              d: P({
                type: "Point",
                coordinates: p.invert(r.mousePosition)
              })
            }
          )
        ]
      }
    ),
    /* @__PURE__ */ n("svg", { className: "defs", children: /* @__PURE__ */ m("defs", { children: [
      /* @__PURE__ */ m("linearGradient", { id: "gradBlue", x1: "0%", y1: "0%", x2: "100%", y2: "0%", children: [
        /* @__PURE__ */ n("stop", { offset: "0%", style: { stopColor: "#005C99", stopOpacity: 1 } }),
        /* @__PURE__ */ n("stop", { offset: "100%", style: { stopColor: "#0099FF", stopOpacity: 1 } })
      ] }),
      /* @__PURE__ */ m("filter", { id: "glow", children: [
        /* @__PURE__ */ n(
          "feColorMatrix",
          {
            type: "matrix",
            values: `0 0 0 0   0
                     0 0 0 0.9 0
                     0 0 0 0.9 0
                     0 0 0 1   0`
          }
        ),
        /* @__PURE__ */ n("feGaussianBlur", { stdDeviation: "5.5", result: "coloredBlur" }),
        /* @__PURE__ */ m("feMerge", { children: [
          /* @__PURE__ */ n("feMergeNode", { in: "coloredBlur" }),
          /* @__PURE__ */ n("feMergeNode", { in: "SourceGraphic" })
        ] })
      ] })
    ] }) })
  ] });
}
const lo = Y(W, { name: "Earth" }), Z = B("div")`
  background-color: ${(e) => e.$theme === "light" ? "#f7f7f7" : "#222"};
  width: ${(e) => e.width}px;
  height: ${(e) => e.height}px;
  position: relative;
  animation-name: zoomIn;
  animation-duration: 1s;
  animation-iteration-count: 1;
  animation-timing-function: ease;
  user-select: none;

  .defs {
    height: 0;
    width: 0;
  }

  .frame {
    fill: none;
    pointer-events: all;
  }

  .country {
    fill: ${(e) => e.colors.land};
    stroke: ${(e) => e.colors.border};
    stroke-width: 0.5px;
    transition: fill 300ms ease;

    &:hover {
      fill: ${(e) => e.colors.activeLand};
    }
  }

  .country--active {
    fill: ${(e) => e.colors.activeLand};
  }

  .globe {
    fill: ${(e) => e.colors.ocean};
    stroke: rgba(255, 255, 255, 0.5);
    stroke-width: 0.25px;
  }

  .graticule {
    fill: none;
    stroke: ${(e) => e.colors.graticule};
  }

  .star {
    fill: #fff;
    stroke: rgba(255, 255, 255, 0.5);
    stroke-width: 0.25px;
  }

  .marker {
    .marker__outer {
      fill-opacity: 0;
      animation: scaleIn 2s infinite ease-in-out;
    }
  }

  @keyframes zoomIn {
    from {
      opacity: 0;
      transform: scale3d(0.1, 0.1, 0.1);
    }

    50% {
      opacity: 1;
    }
  }

  @keyframes scaleIn {
    from {
      fill-opacity: 0.3;
      transform: scale3d(0.5, 0.5, 0.5);
    }
    to {
      fill-opacity: 0;
      transform: scale3d(1.5, 1.5, 1.5);
    }
  }
`, oo = B("div")`
  position: absolute;
  width: auto;
  min-width: 90px;
  max-width: 320px;
  padding: 8px 12px;
  font-size: 14px;
  background-color: #4a4a4a;
  border-radius: 2px;
  animation-name: fadeIn;
  animation-duration: 250ms;
  animation-iteration-count: 1;
  animation-timing-function: ease;

  .title,
  .description {
    margin: 0;
    font-size: 16px;
    color: #fff;
  }

  .description {
    margin-top: ${(e) => e.theme.spacing(1)}px;
    color: #fff;
    font-size: 12px;
  }

  @keyframes fadeIn {
    from {
      opacity: 0;
    }

    to {
      opacity: 1;
    }
  }
`;
export {
  lo as default
};
