"use client";

import { motion, useReducedMotion } from "motion/react";
import { cn } from "@/lib/utils";
import { easeOutExpo } from "@/lib/motion";
import { BrandLockup, BRAND_NAME } from "@/components/brand/brand-logo";

interface AppLoaderProps {
  label?: string;
  className?: string;
  /** full = viewport-centered; panel = fills parent area */
  variant?: "full" | "panel" | "inline";
}

const BRAND = BRAND_NAME;

/** Four KPI-style score arcs — performance platform metaphor */
const SCORE_ARCS = [
  { r: 46, dash: 180, duration: 2.8, delay: 0, opacity: 1 },
  { r: 38, dash: 140, duration: 3.4, delay: 0.15, opacity: 0.75 },
  { r: 30, dash: 110, duration: 2.2, delay: 0.28, opacity: 0.55 },
  { r: 22, dash: 90, duration: 3.8, delay: 0.4, opacity: 0.4 },
] as const;

/** Snap trig results so SSR and the browser emit identical SVG attributes. */
function roundCoord(n: number) {
  return Math.round(n * 1000) / 1000;
}

function polar(cx: number, cy: number, r: number, angleDeg: number) {
  const a = ((angleDeg - 90) * Math.PI) / 180;
  return {
    x: roundCoord(cx + r * Math.cos(a)),
    y: roundCoord(cy + r * Math.sin(a)),
  };
}

const DIAL_CX = 60;
const DIAL_CY = 60;
const DIAL_TICKS = Array.from({ length: 24 }, (_, i) => {
  const angle = i * 15;
  return {
    angle,
    outer: polar(DIAL_CX, DIAL_CY, 52, angle),
    inner: polar(DIAL_CX, DIAL_CY, angle % 45 === 0 ? 47 : 49.5, angle),
    major: angle % 45 === 0,
  };
});

function ScoreDial({
  size = 168,
  reduceMotion,
}: {
  size?: number;
  reduceMotion: boolean;
}) {
  const cx = DIAL_CX;
  const cy = DIAL_CY;

  return (
    <div className="relative" style={{ width: size, height: size }}>
      {/* Soft atmosphere — theme tokens only */}
      <motion.div
        aria-hidden
        className="pointer-events-none absolute inset-[12%] rounded-full bg-primary/10 dark:bg-primary/15"
        animate={
          reduceMotion
            ? undefined
            : { scale: [1, 1.08, 1], opacity: [0.45, 0.2, 0.45] }
        }
        transition={{ duration: 3.2, repeat: Infinity, ease: "easeInOut" }}
      />

      <svg
        viewBox="0 0 120 120"
        className="h-full w-full text-primary"
        aria-hidden
      >
        {/* Quiet track rings */}
        {[48, 40, 32, 24].map((r) => (
          <circle
            key={r}
            cx={cx}
            cy={cy}
            r={r}
            fill="none"
            className="stroke-border"
            strokeWidth={1}
            opacity={0.7}
          />
        ))}

        {/* Evaluation tick marks around the outer ring */}
        {DIAL_TICKS.map(({ angle, inner, outer, major }) => (
          <line
            key={angle}
            x1={inner.x}
            y1={inner.y}
            x2={outer.x}
            y2={outer.y}
            className="stroke-muted-foreground/40"
            strokeWidth={major ? 1.4 : 0.8}
            strokeLinecap="round"
          />
        ))}

        {/* Animated KPI score arcs */}
        {SCORE_ARCS.map((arc, i) => {
          const circumference = roundCoord(2 * Math.PI * arc.r);
          return (
            <motion.circle
              key={arc.r}
              cx={cx}
              cy={cy}
              r={arc.r}
              fill="none"
              stroke="currentColor"
              strokeWidth={i === 0 ? 2.5 : 2}
              strokeLinecap="round"
              strokeDasharray={`${arc.dash} ${circumference}`}
              opacity={arc.opacity}
              style={{ transformOrigin: "60px 60px", willChange: "transform" }}
              initial={
                reduceMotion
                  ? false
                  : { rotate: i % 2 === 0 ? -40 : 40, opacity: 0 }
              }
              animate={
                reduceMotion
                  ? { rotate: i * 28, opacity: arc.opacity }
                  : {
                      rotate: i % 2 === 0 ? [0, 360] : [0, -360],
                      opacity: [
                        arc.opacity * 0.55,
                        arc.opacity,
                        arc.opacity * 0.55,
                      ],
                    }
              }
              transition={
                reduceMotion
                  ? undefined
                  : {
                      rotate: {
                        duration: arc.duration,
                        repeat: Infinity,
                        ease: "linear",
                        delay: arc.delay,
                      },
                      opacity: {
                        duration: 2.4,
                        repeat: Infinity,
                        ease: "easeInOut",
                        delay: arc.delay,
                      },
                    }
              }
            />
          );
        })}

        {/* Leading evaluation markers ride the outer score arcs */}
        {!reduceMotion &&
          SCORE_ARCS.slice(0, 2).map((arc, i) => (
            <motion.g
              key={`dot-${arc.r}`}
              style={{
                transformOrigin: "60px 60px",
                willChange: "transform",
              }}
              animate={{ rotate: i === 0 ? 360 : -360 }}
              transition={{
                duration: arc.duration,
                repeat: Infinity,
                ease: "linear",
                delay: arc.delay,
              }}
            >
              <circle
                cx={cx}
                cy={cy - arc.r}
                r={2.2 - i * 0.3}
                fill="currentColor"
              />
            </motion.g>
          ))}

        {/* Core aperture */}
        <motion.g
          style={{ transformOrigin: "60px 60px", willChange: "transform" }}
          animate={reduceMotion ? undefined : { scale: [0.94, 1.06, 0.94] }}
          transition={{ duration: 2.6, repeat: Infinity, ease: "easeInOut" }}
        >
          <circle
            cx={cx}
            cy={cy}
            r={14}
            className="fill-background stroke-primary/30"
            strokeWidth={1}
          />
          <circle
            cx={cx}
            cy={cy}
            r={5}
            className="fill-primary/80"
            opacity={0.9}
          />
        </motion.g>
      </svg>
    </div>
  );
}

function BrandWordmark({
  reduceMotion,
  compact = false,
}: {
  reduceMotion: boolean;
  compact?: boolean;
}) {
  return (
    <div className="relative inline-block overflow-hidden px-1">
      <motion.div
        initial={reduceMotion ? false : { opacity: 0, y: 10 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.15, duration: 0.4, ease: easeOutExpo }}
      >
        <BrandLockup height={compact ? 20 : 28} className="items-center" />
      </motion.div>
    </div>
  );
}

function KpiMeter({
  reduceMotion,
  compact = false,
}: {
  reduceMotion: boolean;
  compact?: boolean;
}) {
  const segments = 5;

  return (
    <div
      className={cn(
        "flex items-center justify-center gap-1.5",
        compact ? "mt-0" : "mt-1",
      )}
      aria-hidden
    >
      {Array.from({ length: segments }, (_, i) => (
        <motion.span
          key={i}
          className={cn(
            "rounded-full bg-primary",
            compact ? "h-1 w-5" : "h-1.5 w-8",
          )}
          initial={reduceMotion ? false : { scaleX: 0.35, opacity: 0.25 }}
          animate={
            reduceMotion
              ? { opacity: 0.45 + i * 0.1 }
              : {
                  scaleX: [0.35, 1, 0.35],
                  opacity: [0.25, 1, 0.25],
                }
          }
          transition={
            reduceMotion
              ? undefined
              : {
                  duration: 1.6,
                  repeat: Infinity,
                  ease: "easeInOut",
                  delay: i * 0.14,
                }
          }
          style={{ transformOrigin: "left center", willChange: "transform" }}
        />
      ))}
    </div>
  );
}

export function AppLoader({
  label = "Preparing your workspace",
  className,
  variant = "full",
}: AppLoaderProps) {
  // null on the server vs boolean on the client would hydrate differently
  const reduceMotion = Boolean(useReducedMotion());

  const shell =
    variant === "full"
      ? "min-h-screen flex items-center justify-center bg-background"
      : variant === "panel"
        ? "flex items-center justify-center min-h-[50vh] w-full"
        : "inline-flex items-center gap-3";

  if (variant === "inline") {
    return (
      <div className={cn(shell, className)} role="status" aria-live="polite">
        <ScoreDial size={44} reduceMotion={reduceMotion} />
        <div className="min-w-0 text-left">
          <BrandWordmark reduceMotion={reduceMotion} compact />
          {label && (
            <p className="mt-0.5 text-xs text-muted-foreground tracking-tight truncate">
              {label}
            </p>
          )}
        </div>
        <span className="sr-only">{label || BRAND}</span>
      </div>
    );
  }

  return (
    <div className={cn(shell, className)} role="status" aria-live="polite">
      <motion.div
        className="relative flex max-w-md flex-col items-center px-6 text-center"
        initial={reduceMotion ? false : { opacity: 0, scale: 0.97 }}
        animate={{ opacity: 1, scale: 1 }}
        transition={{ duration: 0.45, ease: easeOutExpo }}
      >
        <ScoreDial reduceMotion={reduceMotion} />

        <motion.div
          className="mt-7 flex flex-col items-center gap-3"
          initial={reduceMotion ? false : { opacity: 0, y: 10 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ delay: 0.12, duration: 0.4, ease: easeOutExpo }}
        >
          <BrandWordmark reduceMotion={reduceMotion} />
          <KpiMeter reduceMotion={reduceMotion} />

          {label && (
            <motion.p
              className="text-sm text-muted-foreground tracking-tight"
              initial={reduceMotion ? false : { opacity: 0 }}
              animate={
                reduceMotion ? { opacity: 1 } : { opacity: [0.5, 1, 0.5] }
              }
              transition={
                reduceMotion
                  ? { delay: 0.2, duration: 0.3 }
                  : {
                      delay: 0.9,
                      duration: 2.4,
                      repeat: Infinity,
                      ease: "easeInOut",
                    }
              }
            >
              {label}
            </motion.p>
          )}
        </motion.div>

        <span className="sr-only">{label || BRAND}</span>
      </motion.div>
    </div>
  );
}

/** Compact spinner for buttons / tight UI */
export function AppSpinner({ className }: { className?: string }) {
  const reduceMotion = Boolean(useReducedMotion());
  return (
    <motion.span
      className={cn(
        "inline-block h-4 w-4 rounded-full border-2 border-current/30 border-t-current",
        className,
      )}
      animate={reduceMotion ? undefined : { rotate: 360 }}
      transition={{ duration: 0.75, repeat: Infinity, ease: "linear" }}
      aria-hidden
    />
  );
}
