import { useEffect, useRef, useState } from "react";
import { useNavigate } from "@tanstack/react-router";
import { Clock, Thermometer } from "lucide-react";
import { useReducedMotion } from "@/hooks/use-reduced-motion";

const NODES = [
  { label: "AI Systems", angle: -90, to: "/gatavase-ai" },
  { label: "Mobile Apps", angle: -30, to: "/app-development" },
  { label: "Web Platforms", angle: 30, to: "/website-development" },
  { label: "Cloud & Networks", angle: 90, to: "/networking" },
  { label: "Software", angle: 150, to: "/software-development" },
  { label: "Creative", angle: 210, to: "/graphics-design" },
] as const;

const R = 128;
const C = 180;

/** Animated radial command-center HUD: glowing hub, orbiting nodes, drawn links. */
export function HudOrbit() {
  const [active, setActive] = useState<string | null>(null);
  const navigate = useNavigate();

  const go = (to: string) => navigate({ to });

  return (
    <div className="hud-stage relative mx-auto aspect-square w-full max-w-[360px]">
      <svg viewBox="0 0 360 360" className="size-full overflow-visible" aria-hidden="true">
        <defs>
          <radialGradient id="hubGrad" cx="50%" cy="35%">
            <stop offset="0%" stopColor="var(--glow)" />
            <stop offset="60%" stopColor="var(--primary)" />
            <stop offset="100%" stopColor="color-mix(in oklab, var(--primary) 25%, transparent)" />
          </radialGradient>
        </defs>

        {/* orbit rings */}
        <circle cx={C} cy={C} r={R} className="hud-ring" />
        <circle cx={C} cy={C} r={R - 40} className="hud-ring hud-ring-slow" />
        <circle cx={C} cy={C} r={R + 26} className="hud-ring hud-ring-faint" />

        {/* connecting lines */}
        <g className="hud-links">
          {NODES.map((n) => {
            const rad = (n.angle * Math.PI) / 180;
            return (
              <line
                key={n.label}
                x1={C}
                y1={C}
                x2={C + R * Math.cos(rad)}
                y2={C + R * Math.sin(rad)}
                className="hud-link"
                style={{ animationDelay: `${Math.abs(n.angle) / 400}s` }}
              />
            );
          })}
        </g>

        {/* rotating node cluster */}
        <g className="hud-orbit">
          {NODES.map((n) => {
            const rad = (n.angle * Math.PI) / 180;
            return (
              <circle
                key={n.label}
                cx={C + R * Math.cos(rad)}
                cy={C + R * Math.sin(rad)}
                r={active === n.label ? 11 : 8}
                className="hud-node"
              />
            );
          })}
        </g>

        {/* central hub */}
        <circle cx={C} cy={C} r={52} fill="url(#hubGrad)" className="hud-hub" />
        <circle cx={C} cy={C} r={66} className="hud-hub-halo" />
      </svg>

      {/* labels sit above the SVG so they stay upright */}
      {NODES.map((n) => {
        const rad = (n.angle * Math.PI) / 180;
        return (
          <button
            key={n.label}
            type="button"
            onMouseEnter={() => setActive(n.label)}
            onMouseLeave={() => setActive(null)}
            onFocus={() => setActive(n.label)}
            onBlur={() => setActive(null)}
            onClick={() => go(n.to)}
            aria-label={`Open ${n.label} services`}
            className="hud-label cursor-pointer"
            style={{
              left: `${((C + (R + 34) * Math.cos(rad)) / 360) * 100}%`,
              top: `${((C + (R + 34) * Math.sin(rad)) / 360) * 100}%`,
            }}
          >
            {n.label}
          </button>
        );
      })}

      <div className="pointer-events-none absolute inset-0 grid place-items-center text-center">
        <div>
          <p className="font-display text-sm font-semibold tracking-tight text-primary-foreground">
            GATAVASE
          </p>
          <p className="font-mono text-[10px] tracking-[0.2em] text-primary-foreground/80 uppercase">
            core
          </p>
        </div>
      </div>
    </div>
  );
}

interface CityReading {
  city: string;
  timeZone: string;
  lat: number;
  lon: number;
}

const CITIES: CityReading[] = [
  { city: "Kampala", timeZone: "Africa/Kampala", lat: 0.3476, lon: 32.5825 },
  { city: "Doha", timeZone: "Asia/Qatar", lat: 25.2854, lon: 51.531 },
];

/** Floating HUD widgets: live local time/date and real temperature per office. */
export function HudWidgets({ className = "" }: { className?: string }) {
  const [now, setNow] = useState<Date | null>(null);
  const [temps, setTemps] = useState<Record<string, number | null>>({});

  useEffect(() => {
    setNow(new Date());
    const id = window.setInterval(() => setNow(new Date()), 1000);
    return () => window.clearInterval(id);
  }, []);

  useEffect(() => {
    let cancelled = false;
    const load = async () => {
      const results = await Promise.all(
        CITIES.map(async (c) => {
          try {
            const res = await fetch(
              `https://api.open-meteo.com/v1/forecast?latitude=${c.lat}&longitude=${c.lon}&current=temperature_2m`,
            );
            if (!res.ok) return [c.city, null] as const;
            const json = (await res.json()) as { current?: { temperature_2m?: number } };
            const t = json.current?.temperature_2m;
            return [c.city, typeof t === "number" ? t : null] as const;
          } catch {
            return [c.city, null] as const;
          }
        }),
      );
      if (!cancelled) setTemps(Object.fromEntries(results));
    };
    void load();
    const id = window.setInterval(load, 10 * 60 * 1000);
    return () => {
      cancelled = true;
      window.clearInterval(id);
    };
  }, []);

  return (
    <div className={`flex flex-wrap gap-3 ${className}`}>
      {CITIES.map((c) => {
        const time = now
          ? new Intl.DateTimeFormat("en-GB", {
              timeZone: c.timeZone,
              hour: "2-digit",
              minute: "2-digit",
              second: "2-digit",
            }).format(now)
          : "--:--:--";
        const date = now
          ? new Intl.DateTimeFormat("en-GB", {
              timeZone: c.timeZone,
              weekday: "short",
              day: "numeric",
              month: "short",
            }).format(now)
          : "";
        const temp = temps[c.city];
        return (
          <div key={c.city} className="hud-widget">
            <p className="font-mono text-[10px] tracking-[0.2em] text-primary uppercase">{c.city}</p>
            <p className="mt-1 flex items-center gap-1.5 font-display text-lg font-semibold tabular-nums">
              <Clock className="size-3.5 text-primary" />
              <span className="hud-value">{time}</span>
            </p>
            <p className="mt-0.5 text-[11px] text-muted-foreground">{date}</p>
            <p className="mt-2 flex items-center gap-1.5 text-xs text-muted-foreground">
              <Thermometer className="size-3.5 text-primary" />
              <span className="hud-value">
                {typeof temp === "number" ? `${Math.round(temp)}°C` : "—"}
              </span>
            </p>
          </div>
        );
      })}
    </div>
  );
}

/** Lightweight canvas star/particle field for the hero background. */
export function ParticleField({ className = "" }: { className?: string }) {
  const ref = useRef<HTMLCanvasElement | null>(null);
  const { reducedMotion } = useReducedMotion();

  useEffect(() => {
    const canvas = ref.current;
    if (!canvas) return;
    const ctx = canvas.getContext("2d");
    if (!ctx) return;

    const reduce =
      reducedMotion || window.matchMedia("(prefers-reduced-motion: reduce)").matches;
    let raf = 0;
    let w = 0;
    let h = 0;
    const dpr = Math.min(window.devicePixelRatio || 1, 2);

    const stars = Array.from({ length: reduce ? 40 : 90 }, () => ({
      x: Math.random(),
      y: Math.random(),
      r: Math.random() * 1.6 + 0.3,
      s: Math.random() * 0.00025 + 0.00005,
      o: Math.random() * 0.5 + 0.2,
    }));

    const resize = () => {
      w = canvas.clientWidth;
      h = canvas.clientHeight;
      canvas.width = w * dpr;
      canvas.height = h * dpr;
      ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    };
    resize();
    window.addEventListener("resize", resize);

    const paint = () => {
      ctx.clearRect(0, 0, w, h);
      for (const st of stars) {
        if (!reduce) {
          st.y -= st.s;
          if (st.y < 0) st.y = 1;
        }
        ctx.beginPath();
        ctx.arc(st.x * w, st.y * h, st.r, 0, Math.PI * 2);
        ctx.fillStyle = `rgba(160, 230, 255, ${st.o})`;
        ctx.fill();
      }
    };

    const draw = () => {
      paint();
      raf = requestAnimationFrame(draw);
    };

    if (reduce) {
      paint();
    } else {
      draw();
    }

    return () => {
      cancelAnimationFrame(raf);
      window.removeEventListener("resize", resize);
    };
  }, [reducedMotion]);

  return <canvas ref={ref} className={className} aria-hidden="true" />;
}
