"use client";

import { useState } from "react";
import { m, useReducedMotion } from "framer-motion";
import { MapPin } from "lucide-react";
import { useLocale } from "next-intl";
import { buildFlightArc, EXPORT_GLOBE, getExportGlobeView, projectGeoPoint } from "@/lib/export-globe";
import { EXPORT_MARKETS, EXPORT_NETWORK_ORIGIN, type ExportMarket, type ExportMarketLocale } from "@/lib/export-markets";

type Copy = {
  eyebrow: string;
  title: string;
  body: string;
  origin: string;
  list: string;
  draft: string;
  note: string;
  globeLabel: string;
};

const copy = {
  tr: {
    eyebrow: "Uluslararası büyüme · hedef pazarlar",
    title: "İstanbul'dan dünyaya uzanan bağlantılar.",
    body: "Norden'in ankastre ocak portföyü için belirlenen ihracat hedefleri; Avrupa, Asya, Kafkasya, Rusya, Afrika ve Amerika pazarlarını bir araya getiriyor. İstanbul'daki üretim merkezimizden yeni iş birliklerine uzanan bir büyüme hedefi.",
    origin: "Norden fabrika · Arnavutköy",
    list: "Hedef ihracat pazarları",
    draft: "Üretimden uluslararası iş birliğine",
    note: "Natural Earth · Temsili başkent noktalarıdır; bayi veya sevkiyat adresi değildir",
    globeLabel: "Arnavutköy'deki Norden fabrika pininden ülke başkentlerine uzanan coğrafi bağlantı ağı",
  },
  en: {
    eyebrow: "International growth · target markets",
    title: "Connections extending from Istanbul to the world.",
    body: "The export markets identified for Norden's built-in hob portfolio span Europe, Asia, the Caucasus, Russia, Africa and the Americas. Our growth ambition connects production in Istanbul with new international business partnerships.",
    origin: "Norden factory · Arnavutköy",
    list: "Target export markets",
    draft: "From manufacturing to international partnerships",
    note: "Natural Earth · Representative capital points, not distributor or delivery addresses",
    globeLabel: "Geographic connection network from the Norden factory pin in Arnavutköy to country capitals",
  },
  ru: {
    eyebrow: "Международное развитие · целевые рынки",
    title: "Связи, ведущие из Стамбула в разные регионы мира.",
    body: "Целевые экспортные рынки для встраиваемых варочных панелей Norden охватывают Европу, Азию, Кавказ, Россию, Африку и Америку. Наши планы развития объединяют производство в Стамбуле и перспективы нового международного делового сотрудничества.",
    origin: "Фабрика Norden · Арнавуткёй",
    list: "Целевые экспортные рынки",
    draft: "От производства к международному сотрудничеству",
    note: "Natural Earth · Условные точки столиц, не адреса дилеров или поставок",
    globeLabel: "Географическая сеть от фабрики Norden в Арнавуткёе до столиц стран",
  },
} satisfies Record<ExportMarketLocale, Copy>;

export default function ExportNetwork({ markets = EXPORT_MARKETS }: { markets?: ExportMarket[] }) {
  const rawLocale = useLocale();
  const locale: ExportMarketLocale = rawLocale === "en" || rawLocale === "ru" ? rawLocale : "tr";
  const t = copy[locale];
  const reduceMotion = useReducedMotion();
  const [activeCode, setActiveCode] = useState(markets[0]?.code || "");

  return (
    <section id="export-network" className="relative isolate overflow-hidden border-t bg-[#06070c]" style={{ borderColor: "var(--border)" }}>
      <div aria-hidden className="pointer-events-none absolute inset-0 bg-[radial-gradient(circle_at_64%_48%,rgba(166,48,29,.18),transparent_34%),radial-gradient(circle_at_25%_20%,rgba(207,145,71,.07),transparent_28%)]" />
      <div aria-hidden className="pointer-events-none absolute inset-x-0 top-0 h-px bg-gradient-to-r from-transparent via-[#db6b39]/45 to-transparent" />

      <div className="relative mx-auto grid min-h-[94svh] max-w-[100rem] items-center gap-10 px-6 py-20 md:px-12 lg:grid-cols-[.72fr_1.35fr_.72fr] lg:gap-5 lg:py-16">
        <m.div
          initial={reduceMotion ? false : { opacity: 0, x: -72 }}
          whileInView={{ opacity: 1, x: 0 }}
          viewport={{ once: true, amount: .45 }}
          transition={{ duration: .9, ease: [0.16, 1, 0.3, 1] }}
          className="relative z-10 max-w-xl"
        >
          <span className="font-mono text-[9px] uppercase tracking-[.23em] text-[#e0a457]">{t.eyebrow}</span>
          <h2 className="mt-7 text-4xl font-medium leading-[1.02] tracking-[-.052em] text-white md:text-6xl lg:text-5xl xl:text-6xl">{t.title}</h2>
          <p className="mt-7 text-sm leading-7 text-white/55 md:text-base">{t.body}</p>
          <div className="mt-9 flex items-center gap-3 font-mono text-[8px] uppercase tracking-[.18em] text-white/36">
            <span className="h-px w-12 bg-[#df5e32]" />
            {t.draft}
          </div>
        </m.div>

        <m.div
          initial={reduceMotion ? false : { opacity: 0, scale: .84 }}
          whileInView={{ opacity: 1, scale: 1 }}
          viewport={{ once: true, amount: .28 }}
          transition={{ duration: 1.2, ease: [0.16, 1, 0.3, 1] }}
          className="relative mx-auto aspect-square w-full max-w-[48rem]"
        >
          <div aria-hidden className="absolute inset-[7%] rounded-full bg-[#9f3826]/20 blur-[68px]" />
          <m.div
            animate={reduceMotion ? undefined : { y: [0, -5, 0], rotate: [-.35, .35, -.35] }}
            transition={{ duration: 12, repeat: Infinity, ease: "easeInOut" }}
            className="absolute inset-[3%] overflow-hidden rounded-full border border-white/[.07] bg-[radial-gradient(circle_at_35%_24%,#25292c_0%,#0c0e11_34%,#020305_72%)] shadow-[inset_-70px_-38px_90px_rgba(0,0,0,.92),inset_34px_20px_55px_rgba(255,255,255,.025),0_0_80px_rgba(122,42,27,.22)]"
          >
            <NetworkGlobe markets={markets} activeCode={activeCode} reduceMotion={Boolean(reduceMotion)} ariaLabel={t.globeLabel} />
            <div aria-hidden className="pointer-events-none absolute inset-0 bg-[linear-gradient(112deg,rgba(255,255,255,.055),transparent_24%,transparent_70%,rgba(0,0,0,.72))]" />
          </m.div>
          <div className="absolute bottom-[8%] left-1/2 flex -translate-x-1/2 items-center gap-2 rounded-full border border-[#df5e32]/35 bg-black/55 px-4 py-2 font-mono text-[8px] uppercase tracking-[.16em] text-white/62 backdrop-blur-md">
            <MapPin size={12} className="text-[#f06b39]" /> {t.origin}
          </div>
          <p className="absolute inset-x-4 bottom-0 text-center font-mono text-[7px] uppercase tracking-[.14em] text-white/25">{t.note}</p>
        </m.div>

        <m.div
          initial={reduceMotion ? false : { opacity: 0, x: 72 }}
          whileInView={{ opacity: 1, x: 0 }}
          viewport={{ once: true, amount: .35 }}
          transition={{ duration: .9, delay: .12, ease: [0.16, 1, 0.3, 1] }}
          className="relative z-10"
        >
          <div className="mb-5 flex items-center justify-between gap-4">
            <span className="font-mono text-[8px] uppercase tracking-[.19em] text-white/38">{t.list}</span>
            <span className="font-mono text-[8px] tracking-[.18em] text-[#df6a38]">{String(markets.length).padStart(2, "0")}</span>
          </div>
          <div className="scrollbar-none grid max-h-[34rem] grid-cols-2 gap-2 overflow-y-auto pr-1 lg:grid-cols-1">
            {markets.map((market, index) => {
              const active = market.code === activeCode;
              return (
                <button
                  key={market.code}
                  type="button"
                  aria-pressed={active}
                  aria-label={`${market.names[locale]} · ${market.capitalNames[locale]}`}
                  title={`${market.names[locale]} · ${market.capitalNames[locale]}`}
                  onClick={() => setActiveCode(market.code)}
                  onMouseEnter={() => setActiveCode(market.code)}
                  onFocus={() => setActiveCode(market.code)}
                  className="group flex min-h-11 items-center gap-3 rounded-full border px-4 text-left transition-[border-color,background-color,transform] duration-300 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#df6a38] motion-reduce:transition-none lg:hover:translate-x-1"
                  style={{ borderColor: active ? "rgba(223,94,50,.68)" : "rgba(223,94,50,.25)", background: active ? "rgba(223,94,50,.08)" : "rgba(6,7,12,.62)" }}
                >
                  <span className="font-mono text-[9px] font-semibold tracking-[.08em] text-white/90">{market.code}</span>
                  <span className="min-w-0 text-xs leading-4 text-white/65 transition-colors group-hover:text-white">{market.names[locale]}</span>
                  <span className="ml-auto hidden font-mono text-[7px] text-[#df6a38]/60 sm:block">{String(index + 1).padStart(2, "0")}</span>
                </button>
              );
            })}
          </div>
        </m.div>
      </div>
    </section>
  );
}

function NetworkGlobe({ markets, activeCode, reduceMotion, ariaLabel }: { markets: ExportMarket[]; activeCode: string; reduceMotion: boolean; ariaLabel: string }) {
  const activeMarket = markets.find((market) => market.code === activeCode);
  const view = getExportGlobeView(activeMarket?.coordinates);
  const originPoint = projectGeoPoint(EXPORT_NETWORK_ORIGIN.coordinates, view.center);

  return (
    <svg viewBox={`0 0 ${EXPORT_GLOBE.width} ${EXPORT_GLOBE.height}`} className="h-full w-full" role="img" aria-label={ariaLabel}>
      <defs>
        <clipPath id="network-globe-clip"><circle cx={EXPORT_GLOBE.centerX} cy={EXPORT_GLOBE.centerY} r={EXPORT_GLOBE.radius} /></clipPath>
        <linearGradient id="network-route" x1="0" y1="0" x2="1" y2="1">
          <stop stopColor="#ff6033" />
          <stop offset=".55" stopColor="#d97a34" />
          <stop offset="1" stopColor="#d9b84b" />
        </linearGradient>
        <filter id="network-glow" x="-100%" y="-100%" width="300%" height="300%">
          <feGaussianBlur stdDeviation="5" result="blur" />
          <feMerge><feMergeNode in="blur" /><feMergeNode in="SourceGraphic" /></feMerge>
        </filter>
      </defs>

      <g clipPath="url(#network-globe-clip)">
        <circle cx={EXPORT_GLOBE.centerX} cy={EXPORT_GLOBE.centerY} r={EXPORT_GLOBE.radius} fill="transparent" />
        <image href={view.asset} x="0" y="0" width={EXPORT_GLOBE.width} height={EXPORT_GLOBE.height} aria-hidden="true" />

        {markets.map((market, index) => {
          const active = market.code === activeCode;
          const targetPoint = projectGeoPoint(market.coordinates, view.center);
          if (!targetPoint.visible) return null;
          const path = buildFlightArc(originPoint, targetPoint, index);
          return (
            <g key={`${view.asset}-${market.code}`}>
              <m.path
                d={path}
                fill="none"
                stroke="url(#network-route)"
                strokeLinecap="round"
                strokeWidth={active ? 4.4 : 2.3}
                initial={reduceMotion ? false : { pathLength: 0, opacity: 0 }}
                whileInView={{ pathLength: 1, opacity: active ? 1 : .48 }}
                viewport={{ once: true, amount: .2 }}
                transition={{ duration: reduceMotion ? 0 : 1.05, delay: reduceMotion ? 0 : index * .065, ease: [0.16, 1, 0.3, 1] }}
                style={{ filter: active ? "url(#network-glow)" : "none", transition: "stroke-width .3s ease, opacity .3s ease" }}
              />
              <circle cx={targetPoint.x} cy={targetPoint.y} r={active ? 6 : 4} fill={active ? "#ffd35c" : "#d4ad48"} opacity={active ? 1 : .76} />
              {active && <circle cx={targetPoint.x} cy={targetPoint.y} r="13" fill="none" stroke="#ffd35c" strokeWidth="1.5" opacity=".48" />}
              {active && <text x={targetPoint.x + 12} y={targetPoint.y - 12} fill="rgba(255,255,255,.8)" fontSize="13" fontWeight="600" letterSpacing="1.5">{market.code}</text>}
            </g>
          );
        })}

        <circle cx={originPoint.x} cy={originPoint.y} r="8" fill="#ff6033" filter="url(#network-glow)" />
        <circle cx={originPoint.x} cy={originPoint.y} r="18" fill="none" stroke="#ff6033" strokeWidth="2" opacity=".8" />
        <circle cx={originPoint.x} cy={originPoint.y} r="29" fill="none" stroke="#ff6033" strokeWidth="1" opacity=".26" />
      </g>
      <circle cx={EXPORT_GLOBE.centerX} cy={EXPORT_GLOBE.centerY} r={EXPORT_GLOBE.radius} fill="none" stroke="rgba(255,255,255,.08)" strokeWidth="2" />
    </svg>
  );
}
