/**
 * GlobalDataCenters
 * -----------------
 * Light premium "Data Centers Worldwide" section.
 *
 * Design goals (matching reference image):
 *   - Very light mint/white background with soft radial wash.
 *   - Rounded card hosting a dotted mint-green world map silhouette.
 *   - Pulsing green data-center nodes with animated halos.
 *   - Thin dashed curved backbone lines connecting regions.
 *   - Floating glass labels around the map for each region.
 *   - One hero popup over US East with a rich details list.
 *   - Legend row + bottom "Need a custom solution?" CTA card.
 *
 * The world silhouette is rendered with a viewBox of 1000x500 and uses
 * equirectangular-style x/y coordinates. Nodes coordinates are expressed
 * as percentages of that viewBox so the floating labels stay in sync with
 * the SVG markers when the card is resized.
 */

import { useMemo } from "react";
import { Link } from "react-router-dom";
import {
  ArrowRight,
  Building2,
  CheckCircle2,
  Clock,
  Globe2,
  Server,
  ShieldCheck,
} from "lucide-react";

// ---------------------------------------------------------------------------
// Data models
// ---------------------------------------------------------------------------

interface DataCenter {
  /** Unique id for React keys and aria references. */
  id: string;
  /** Short region label shown in the floating pill, e.g. "US East". */
  region: string;
  /** Human readable location, e.g. "Ashburn, Virginia, USA". */
  location: string;
  /** Dot position in percent across the 1000x500 map viewBox. */
  x: number;
  y: number;
  /** Operational status — used to colour the dot and legend. */
  status: "live" | "planned";
  /** Preferred direction to offset the floating label relative to the dot. */
  labelPosition: "top" | "right" | "bottom" | "left" | "top-right" | "bottom-right" | "bottom-left" | "top-left";
  /** Flag emoji, decorative only. */
  flag?: string;
}

/** All data centers rendered on the map — original coordinates restored. */
const DATA_CENTERS: DataCenter[] = [
  // North America
  { id: "us-west", region: "US West", location: "Oregon, USA", x: 16, y: 34, status: "live", labelPosition: "left", flag: "🇺🇸" },
  { id: "us-east", region: "US East", location: "Ashburn, Virginia, USA", x: 25, y: 36, status: "live", labelPosition: "top-right", flag: "🇺🇸" },
  { id: "canada", region: "Canada", location: "Toronto, Canada", x: 22, y: 26, status: "live", labelPosition: "top", flag: "🇨🇦" },

  // South America
  { id: "sa-east", region: "South America", location: "São Paulo, Brazil", x: 30, y: 76, status: "live", labelPosition: "bottom-left", flag: "🇧🇷" },

  // Europe
  { id: "eu-frankfurt", region: "Europe", location: "Frankfurt, Germany", x: 52, y: 28, status: "live", labelPosition: "top", flag: "🇩🇪" },
  { id: "uk-london", region: "United Kingdom", location: "London, UK", x: 48, y: 26, status: "live", labelPosition: "left", flag: "🇬🇧" },
  { id: "fr-paris", region: "France", location: "Paris, France", x: 50, y: 30, status: "live", labelPosition: "bottom-left", flag: "🇫🇷" },
  { id: "nl-ams", region: "Netherlands", location: "Amsterdam, NL", x: 51, y: 27, status: "planned", labelPosition: "top-left", flag: "🇳🇱" },
  { id: "it-milan", region: "Italy", location: "Milan, Italy", x: 52.5, y: 33, status: "planned", labelPosition: "bottom-right", flag: "🇮🇹" },
  { id: "fi-helsinki", region: "Finland", location: "Helsinki, Finland", x: 55, y: 22, status: "planned", labelPosition: "top", flag: "🇫🇮" },
  { id: "pl-warsaw", region: "Poland", location: "Warsaw, Poland", x: 55.5, y: 28, status: "planned", labelPosition: "top-right", flag: "🇵🇱" },

  // Middle East + Africa
  { id: "me-dubai", region: "Middle East", location: "Dubai, UAE", x: 65, y: 44, status: "live", labelPosition: "bottom-right", flag: "🇦🇪" },
  { id: "me-riyadh", region: "Saudi Arabia", location: "Riyadh, STC", x: 62, y: 44, status: "live", labelPosition: "bottom-left", flag: "🇸🇦" },
  { id: "me-cairo", region: "Egypt", location: "Cairo, WE", x: 58, y: 42, status: "live", labelPosition: "left", flag: "🇪🇬" },

  // Asia Pacific
  { id: "ap-singapore", region: "Asia Pacific", location: "Singapore", x: 81, y: 58, status: "live", labelPosition: "right", flag: "🇸🇬" },
  { id: "ap-mumbai", region: "India", location: "Mumbai, India", x: 72, y: 48, status: "live", labelPosition: "bottom", flag: "🇮🇳" },
  { id: "ap-bangkok", region: "Thailand", location: "Bangkok, Thailand", x: 79, y: 50, status: "planned", labelPosition: "top-right", flag: "🇹🇭" },

  // Oceania
  { id: "au-sydney", region: "Australia", location: "Sydney, Australia", x: 88, y: 76, status: "live", labelPosition: "right", flag: "🇦🇺" },
];

/** Backbone connections expressed as pairs of data center ids. */
const CONNECTIONS: Array<[string, string]> = [
  ["us-west", "us-east"],
  ["us-east", "eu-frankfurt"],
  ["us-east", "sa-east"],
  ["eu-frankfurt", "me-dubai"],
  ["me-dubai", "ap-mumbai"],
  ["ap-mumbai", "ap-singapore"],
  ["ap-singapore", "au-sydney"],
  ["eu-frankfurt", "uk-london"],
  ["me-riyadh", "me-dubai"],
  ["us-west", "ap-singapore"],
];

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

/** Convert percentage coordinates to absolute SVG viewBox (1000x500) coords. */
const pxX = (pct: number): number => (pct / 100) * 1000;
const pxY = (pct: number): number => (pct / 100) * 500;

/** Build a smooth quadratic-ish arc between two map points. */
function buildArcPath(from: DataCenter, to: DataCenter): string {
  const x1 = pxX(from.x);
  const y1 = pxY(from.y);
  const x2 = pxX(to.x);
  const y2 = pxY(to.y);
  const mx = (x1 + x2) / 2;
  const my = (y1 + y2) / 2;
  // Lift the control point upwards proportionally to the horizontal distance
  // so long transoceanic links bow gracefully.
  const dx = x2 - x1;
  const lift = Math.min(80, Math.abs(dx) * 0.25 + 20);
  const cy = my - lift;
  return `M ${x1.toFixed(1)} ${y1.toFixed(1)} Q ${mx.toFixed(1)} ${cy.toFixed(1)} ${x2.toFixed(1)} ${y2.toFixed(1)}`;
}

/** Offset classes for the floating label pills based on desired direction. */
function labelOffsetClasses(position: DataCenter["labelPosition"]): string {
  switch (position) {
    case "top":
      return "-translate-x-1/2 -translate-y-[calc(100%+14px)]";
    case "bottom":
      return "-translate-x-1/2 translate-y-[14px]";
    case "left":
      return "-translate-x-[calc(100%+14px)] -translate-y-1/2";
    case "right":
      return "translate-x-[14px] -translate-y-1/2";
    case "top-right":
      return "translate-x-[12px] -translate-y-[calc(100%+6px)]";
    case "top-left":
      return "-translate-x-[calc(100%+12px)] -translate-y-[calc(100%+6px)]";
    case "bottom-right":
      return "translate-x-[12px] translate-y-[6px]";
    case "bottom-left":
      return "-translate-x-[calc(100%+12px)] translate-y-[6px]";
    default:
      return "";
  }
}

// ---------------------------------------------------------------------------
// Component
// ---------------------------------------------------------------------------

const GlobalDataCenters: React.FC = () => {
  /** Resolve connection segments once per render. */
  const segments = useMemo(() => {
    const lookup = new Map(DATA_CENTERS.map((dc) => [dc.id, dc]));
    return CONNECTIONS.map(([aId, bId], idx) => {
      const a = lookup.get(aId);
      const b = lookup.get(bId);
      if (!a || !b) return null;
      return { key: `${aId}-${bId}-${idx}`, d: buildArcPath(a, b), delay: idx * 0.4 };
    }).filter((v): v is { key: string; d: string; delay: number } => Boolean(v));
  }, []);

  const heroDc = DATA_CENTERS.find((dc) => dc.id === "us-east")!;

  return (
    <section
      className="relative py-20 overflow-hidden onepage-section"
      style={{
        scrollSnapAlign: "start",
        background:
          "radial-gradient(1200px 600px at 50% -10%, rgba(22, 199, 132, 0.10) 0%, rgba(255,255,255,0) 60%), linear-gradient(180deg, #f7fcf9 0%, #ffffff 40%, #f4faf7 100%)",
      }}
    >
      {/* Inline keyframes — scoped via unique animation names so they don't
          collide with other Tailwind / framer transitions on the page. */}
      <style>{`
        @keyframes gdcPulse {
          0%   { transform: scale(1);   opacity: 0.9; }
          50%  { transform: scale(2.2); opacity: 0;   }
          100% { transform: scale(1);   opacity: 0;   }
        }
        @keyframes gdcCore {
          0%, 100% { box-shadow: 0 0 0 0 rgba(22, 199, 132, 0.55), 0 0 10px rgba(22,199,132,0.55); }
          50%      { box-shadow: 0 0 0 6px rgba(22, 199, 132, 0), 0 0 14px rgba(22,199,132,0.7); }
        }
        @keyframes gdcDash {
          to { stroke-dashoffset: -120; }
        }
        .gdc-pulse-ring {
          animation: gdcPulse 2.4s ease-out infinite;
        }
        .gdc-core {
          animation: gdcCore 1.8s ease-in-out infinite;
        }
        .gdc-line {
          stroke-dasharray: 6 6;
          animation: gdcDash 6s linear infinite;
        }
      `}</style>

      <div className="relative w-full max-w-[1600px] 3xl:max-w-[1800px] 4xl:max-w-[2100px] 5xl:max-w-[2400px] mx-auto px-4 sm:px-6 lg:px-8 3xl:px-12 5xl:px-16">
        {/* ---------- Heading ---------- */}
        <div className="text-center mb-10">
          <span className="text-[#16c784] font-bold uppercase tracking-widest text-xs sm:text-sm">
            Our Global Infrastructure
          </span>
          <h2 className="text-3xl md:text-5xl font-extrabold text-slate-900 mt-3 tracking-tight">
            Data Centers Worldwide
          </h2>
          <p className="text-slate-600 mt-4 max-w-3xl mx-auto leading-relaxed">
            Deploy closer to your customers with our{" "}
            <span className="font-bold text-[#0b6e3e]">Tier-III+</span>{" "}
            certified data centers across the Americas, Europe, Middle East and
            Asia Pacific — every node engineered for 99.99% uptime, redundant
            power & network, and low-latency connectivity.
          </p>

          {/* Status badges */}
          <div className="mt-7 flex flex-wrap justify-center gap-3">
            <span className="inline-flex items-center gap-2 bg-white border border-emerald-100 rounded-full px-4 py-1.5 text-xs font-semibold text-slate-700 shadow-sm">
              <span className="relative flex h-2 w-2">
                <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-[#16c784] opacity-75" />
                <span className="relative inline-flex rounded-full h-2 w-2 bg-[#16c784]" />
              </span>
              17 Regions Online
            </span>
            <span className="inline-flex items-center gap-2 bg-white border border-emerald-100 rounded-full px-4 py-1.5 text-xs font-semibold text-slate-700 shadow-sm">
              <ShieldCheck className="w-3.5 h-3.5 text-[#16c784]" />
              Tier-III+ Certified
            </span>
            <span className="inline-flex items-center gap-2 bg-white border border-emerald-100 rounded-full px-4 py-1.5 text-xs font-semibold text-slate-700 shadow-sm">
              <Clock className="w-3.5 h-3.5 text-[#16c784]" />
              99.99% SLA
            </span>
          </div>
        </div>

        {/* ---------- Map card ---------- */}
        <div
          className="relative rounded-[24px] bg-white border border-emerald-100 shadow-[0_20px_60px_-30px_rgba(15,118,79,0.25)] overflow-hidden"
        >
          {/* Soft inner wash to keep the card premium and airy */}
          <div
            aria-hidden="true"
            className="pointer-events-none absolute inset-0"
            style={{
              background:
                "radial-gradient(800px 400px at 50% 40%, rgba(22,199,132,0.07) 0%, rgba(255,255,255,0) 70%)",
            }}
          />

          {/* Aspect ratio — taller & wider so all floating labels, pulsing
              halos and the US East popup have breathing room without
              clipping into neighbours. */}
          <div className="relative w-full" style={{ paddingBottom: "56%", minHeight: "520px" }}>
            {/* --- World map SVG (dotted mint silhouette + backbone) --- */}
            <svg
              viewBox="0 0 1000 500"
              className="absolute inset-0 w-full h-full"
              preserveAspectRatio="xMidYMid meet"
              aria-hidden="true"
            >
              <defs>
                <pattern
                  id="gdcDotGrid"
                  width="9"
                  height="9"
                  patternUnits="userSpaceOnUse"
                >
                  <circle cx="1" cy="1" r="1" fill="rgba(22, 199, 132, 0.35)" />
                </pattern>
                <linearGradient id="gdcLineGrad" x1="0" x2="1" y1="0" y2="0">
                  <stop offset="0%" stopColor="#16c784" stopOpacity="0.2" />
                  <stop offset="50%" stopColor="#16c784" stopOpacity="0.75" />
                  <stop offset="100%" stopColor="#16c784" stopOpacity="0.2" />
                </linearGradient>
                <radialGradient id="gdcNodeGlow" cx="50%" cy="50%" r="50%">
                  <stop offset="0%" stopColor="#16c784" stopOpacity="0.45" />
                  <stop offset="100%" stopColor="#16c784" stopOpacity="0" />
                </radialGradient>
              </defs>

              {/* Background wash */}
              <rect width="1000" height="500" fill="#ffffff" />
              <rect
                width="1000"
                height="500"
                fill="url(#gdcDotGrid)"
                opacity="0.25"
              />

              {/* Stylised continent silhouettes (equirectangular approx.) */}
              <g>
                {[
                  // North America
                  "M120,110 L260,100 L290,150 L270,200 L240,250 L200,270 L160,255 L140,210 L110,170 Z",
                  // Central America
                  "M200,270 L230,290 L240,310 L210,320 L185,300 Z",
                  // South America
                  "M240,310 L290,320 L310,360 L300,420 L270,450 L245,430 L225,380 Z",
                  // Europe
                  "M470,120 L560,110 L590,140 L580,175 L540,195 L490,190 L460,160 Z",
                  // Africa
                  "M480,200 L580,200 L600,260 L590,330 L550,390 L510,400 L470,340 L465,270 Z",
                  // Middle East
                  "M580,200 L640,200 L660,240 L630,260 L590,250 Z",
                  // Asia mainland
                  "M590,130 L820,115 L870,160 L860,215 L820,250 L760,260 L700,240 L660,220 L620,190 Z",
                  // SE Asia
                  "M800,250 L860,260 L870,290 L840,305 L810,290 Z",
                  // Australia
                  "M830,360 L910,355 L925,395 L890,420 L845,410 Z",
                ].map((d, idx) => (
                  <path
                    key={idx}
                    d={d}
                    fill="url(#gdcDotGrid)"
                    stroke="rgba(22,199,132,0.35)"
                    strokeWidth="0.6"
                  />
                ))}
              </g>

              {/* Backbone connections */}
              <g fill="none" stroke="url(#gdcLineGrad)" strokeWidth="1.5">
                {segments.map((s) => (
                  <path
                    key={s.key}
                    className="gdc-line"
                    d={s.d}
                    style={{ animationDelay: `${s.delay}s` }}
                  />
                ))}
              </g>

              {/* Node halos (SVG-rendered so they scale with the map) */}
              <g>
                {DATA_CENTERS.filter((d) => d.status === "live").map((dc) => (
                  <circle
                    key={`halo-${dc.id}`}
                    cx={pxX(dc.x)}
                    cy={pxY(dc.y)}
                    r="16"
                    fill="url(#gdcNodeGlow)"
                  />
                ))}
              </g>
            </svg>

            {/* --- HTML overlay: pulsing nodes + floating labels --- */}
            <div className="absolute inset-0">
              {DATA_CENTERS.map((dc) => {
                const isLive = dc.status === "live";
                return (
                  <div
                    key={dc.id}
                    className="absolute"
                    style={{ left: `${dc.x}%`, top: `${dc.y}%` }}
                  >
                    {/* Pulsing node */}
                    <div className="relative -translate-x-1/2 -translate-y-1/2">
                      {isLive && (
                        <>
                          <span
                            className="gdc-pulse-ring absolute inset-0 rounded-full"
                            style={{
                              width: 14,
                              height: 14,
                              backgroundColor: "rgba(22, 199, 132, 0.45)",
                              boxShadow: "0 0 18px rgba(22, 199, 132, 0.7)",
                            }}
                          />
                          <span
                            className="gdc-pulse-ring absolute inset-0 rounded-full"
                            style={{
                              width: 14,
                              height: 14,
                              backgroundColor: "rgba(22, 199, 132, 0.35)",
                              animationDelay: "1.2s",
                              boxShadow: "0 0 18px rgba(22, 199, 132, 0.6)",
                            }}
                          />
                          <span
                            className="gdc-core relative block rounded-full"
                            style={{
                              width: 14,
                              height: 14,
                              background:
                                "radial-gradient(circle, #00ff9c 0%, #16c784 55%, #0b6e3e 100%)",
                              border: "2px solid #ffffff",
                            }}
                          />
                        </>
                      )}
                      {!isLive && (
                        <span
                          className="relative block rounded-full"
                          style={{
                            width: 12,
                            height: 12,
                            background: "#ffffff",
                            border: "2px dashed #94a3b8",
                          }}
                        />
                      )}
                    </div>

                    {/* Floating label pill — hidden for the hero DC because
                        we render a richer popup over it below. */}
                    {dc.id !== "us-east" && (
                      <div
                        className={`pointer-events-auto group absolute transition-all duration-300 ${labelOffsetClasses(
                          dc.labelPosition,
                        )}`}
                      >
                        <div
                          className={`flex items-center gap-2 rounded-xl border bg-white/95 backdrop-blur px-3 py-1.5 shadow-[0_6px_18px_-8px_rgba(15,118,79,0.35)] hover:-translate-y-0.5 hover:shadow-[0_12px_26px_-10px_rgba(22,199,132,0.55)] transition-transform ${
                            isLive
                              ? "border-emerald-200"
                              : "border-slate-200"
                          }`}
                        >
                          <span
                            className={`flex items-center justify-center w-6 h-6 rounded-md shrink-0 ${
                              isLive
                                ? "bg-emerald-50 text-[#16c784]"
                                : "bg-slate-100 text-slate-400"
                            }`}
                          >
                            <Building2 className="w-3.5 h-3.5" />
                          </span>
                          <div className="min-w-0">
                            <div className="text-[12px] font-bold text-slate-900 leading-tight whitespace-nowrap">
                              {dc.region}
                            </div>
                            <div className="text-[10px] text-slate-500 leading-tight whitespace-nowrap">
                              {dc.location}
                            </div>
                          </div>
                        </div>
                      </div>
                    )}
                  </div>
                );
              })}

              {/* Hero popup — US East (Ashburn) */}
              <div
                className="absolute z-10"
                style={{ left: `${heroDc.x}%`, top: `${heroDc.y}%` }}
              >
                <div className="relative -translate-x-[15%] -translate-y-[calc(100%+18px)]">
                  <div className="w-[260px] sm:w-[280px] rounded-2xl bg-white/95 backdrop-blur border border-emerald-100 shadow-[0_20px_50px_-20px_rgba(15,118,79,0.35)] p-4 transition-transform duration-300 hover:-translate-y-1">
                    <div className="flex items-start justify-between gap-2 mb-2">
                      <div className="min-w-0">
                        <div className="text-sm font-extrabold text-slate-900 leading-tight truncate">
                          US East (Ashburn)
                        </div>
                        <div className="text-[11px] text-slate-500 leading-tight truncate">
                          Ashburn, Virginia, USA
                        </div>
                      </div>
                      <span className="inline-flex items-center gap-1 shrink-0 rounded-full bg-emerald-50 border border-emerald-200 text-[10px] font-bold text-[#0b6e3e] px-2 py-0.5">
                        <span className="relative flex h-1.5 w-1.5">
                          <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-[#16c784] opacity-75" />
                          <span className="relative inline-flex rounded-full h-1.5 w-1.5 bg-[#16c784]" />
                        </span>
                        Live
                      </span>
                    </div>

                    <ul className="space-y-1.5 text-[11.5px] text-slate-700">
                      {[
                        "Tier-III+ Certified",
                        "24/7 Monitoring",
                        "99.99% Uptime SLA",
                        "Redundant Power & Network",
                      ].map((line) => (
                        <li key={line} className="flex items-center gap-2">
                          <CheckCircle2 className="w-3.5 h-3.5 text-[#16c784] shrink-0" />
                          <span>{line}</span>
                        </li>
                      ))}
                    </ul>

                    <Link
                      to="/pricing"
                      className="mt-3 inline-flex items-center gap-1 text-xs font-bold text-[#0b6e3e] hover:text-[#16c784] transition"
                    >
                      View Details
                      <ArrowRight className="w-3.5 h-3.5" />
                    </Link>

                    {/* Speech-bubble tail pointing to the node */}
                    <div
                      aria-hidden="true"
                      className="absolute -bottom-2 left-10 w-4 h-4 bg-white border-r border-b border-emerald-100 rotate-45"
                    />
                  </div>
                </div>
              </div>
            </div>
          </div>

          {/* ---------- Legend strip ---------- */}
          <div className="relative flex flex-wrap items-center justify-center gap-x-8 gap-y-3 px-6 py-4 border-t border-emerald-100 bg-gradient-to-b from-white to-[#f4faf7] text-xs">
            <span className="inline-flex items-center gap-2 text-slate-700 font-semibold">
              <span className="relative flex h-2.5 w-2.5">
                <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-[#16c784] opacity-75" />
                <span className="relative inline-flex rounded-full h-2.5 w-2.5 bg-[#16c784] shadow-[0_0_10px_#16c784]" />
              </span>
              Live Data Center
            </span>
            <span className="inline-flex items-center gap-2 text-slate-600 font-semibold">
              <span className="w-2.5 h-2.5 rounded-full border-2 border-dashed border-slate-400 bg-white" />
              Planned Location
            </span>
            <span className="inline-flex items-center gap-2 text-slate-600 font-semibold">
              <span
                className="inline-block w-8 border-t-2 border-dashed"
                style={{ borderColor: "#16c784" }}
              />
              Network Backbone
            </span>
          </div>
        </div>

        {/* ---------- Bottom CTA card ---------- */}
        <div className="mt-10 flex justify-center">
          <div className="relative w-full max-w-3xl rounded-2xl bg-white border border-emerald-100 shadow-[0_14px_40px_-18px_rgba(15,118,79,0.25)] px-5 py-4 sm:px-6 sm:py-5 flex flex-col sm:flex-row items-center gap-4 sm:gap-6">
            <div className="flex items-center justify-center w-12 h-12 rounded-xl bg-emerald-50 border border-emerald-100 shrink-0">
              <Server className="w-6 h-6 text-[#16c784]" />
            </div>
            <div className="text-center sm:text-left flex-1">
              <div className="text-base font-extrabold text-slate-900">
                Need a custom solution?
              </div>
              <div className="text-sm text-slate-600 mt-0.5">
                Deploy in a specific region or build a private infrastructure.
              </div>
            </div>
            <Link
              to="/contact"
              className="inline-flex items-center gap-2 rounded-xl bg-[#16c784] hover:bg-[#0b6e3e] text-white font-bold text-sm px-5 py-2.5 shadow-[0_10px_24px_-10px_rgba(22,199,132,0.8)] transition-colors"
            >
              <Globe2 className="w-4 h-4" />
              Contact Sales
              <ArrowRight className="w-4 h-4" />
            </Link>
          </div>
        </div>
      </div>
    </section>
  );
};

export default GlobalDataCenters;