'use client';

import { useRef } from 'react';
import {
  motion,
  useMotionValue,
  useSpring,
  useTransform,
  useReducedMotion,
  type MotionValue,
} from 'motion/react';
import { TrendingUp, Target, Award, BarChart3 } from 'lucide-react';
import { easeOutExpo } from '@/lib/motion';

function usePointerParallax(reduceMotion: boolean | null) {
  const x = useMotionValue(0);
  const y = useMotionValue(0);
  const springX = useSpring(x, { stiffness: 90, damping: 22, mass: 0.6 });
  const springY = useSpring(y, { stiffness: 90, damping: 22, mass: 0.6 });

  const onPointerMove = (e: React.PointerEvent<HTMLDivElement>) => {
    if (reduceMotion) return;
    const rect = e.currentTarget.getBoundingClientRect();
    const px = (e.clientX - rect.left) / rect.width - 0.5;
    const py = (e.clientY - rect.top) / rect.height - 0.5;
    x.set(px);
    y.set(py);
  };

  const onPointerLeave = () => {
    x.set(0);
    y.set(0);
  };

  return { springX, springY, onPointerMove, onPointerLeave };
}

type Axis = MotionValue<number>;

function ScoreRing({ rotateX, rotateY }: { rotateX: Axis; rotateY: Axis }) {
  return (
    <motion.div
      className="absolute left-1/2 top-[42%] w-[220px] h-[220px] -ml-[110px] -mt-[110px]"
      style={{ rotateX, rotateY, z: 28, transformStyle: 'preserve-3d' }}
      initial={{ opacity: 0, scale: 0.9 }}
      animate={{ opacity: 1, scale: 1 }}
      transition={{ duration: 0.7, ease: easeOutExpo }}
    >
      <div className="relative h-full w-full rounded-[28px] border border-white/12 bg-gradient-to-br from-white/[0.12] to-white/[0.03] backdrop-blur-xl shadow-[0_30px_80px_-20px_rgba(0,0,0,0.65)]">
        <div className="absolute inset-0 rounded-[28px] bg-[radial-gradient(circle_at_30%_20%,rgba(167,139,250,0.22),transparent_55%)]" />
        <div className="relative flex h-full flex-col items-center justify-center p-6">
          <div className="relative h-[128px] w-[128px]">
            <svg viewBox="0 0 120 120" className="h-full w-full -rotate-90">
              <circle
                cx="60"
                cy="60"
                r="50"
                fill="none"
                stroke="rgba(255,255,255,0.08)"
                strokeWidth="8"
              />
              <motion.circle
                cx="60"
                cy="60"
                r="50"
                fill="none"
                stroke="url(#scoreGrad)"
                strokeWidth="8"
                strokeLinecap="round"
                strokeDasharray={`${2 * Math.PI * 50}`}
                initial={{ strokeDashoffset: 2 * Math.PI * 50 }}
                animate={{ strokeDashoffset: 2 * Math.PI * 50 * (1 - 0.92) }}
                transition={{ duration: 1.4, delay: 0.35, ease: easeOutExpo }}
              />
              <defs>
                <linearGradient id="scoreGrad" x1="0" y1="0" x2="1" y2="1">
                  <stop offset="0%" stopColor="#c4b5fd" />
                  <stop offset="100%" stopColor="#67e8f9" />
                </linearGradient>
              </defs>
            </svg>
            <div className="absolute inset-0 flex flex-col items-center justify-center">
              <span className="text-3xl font-semibold tracking-tight text-white">92</span>
              <span className="text-[10px] uppercase tracking-[0.16em] text-white/45">Score</span>
            </div>
          </div>
          <p className="mt-3 text-xs font-medium text-white/70">Overall performance</p>
        </div>
      </div>
    </motion.div>
  );
}

function BarsCard({
  x,
  y,
  rotateX,
  rotateY,
}: {
  x: Axis;
  y: Axis;
  rotateX: Axis;
  rotateY: Axis;
}) {
  const bars = [48, 72, 58, 86, 64, 94];
  return (
    <motion.div
      className="absolute left-[8%] top-[14%] w-[180px]"
      style={{ x, y, rotateX, rotateY, transformStyle: 'preserve-3d' }}
      initial={{ opacity: 0, y: 24 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ delay: 0.25, duration: 0.65, ease: easeOutExpo }}
    >
      <div
        className="rounded-2xl border border-white/12 bg-white/[0.08] p-4 backdrop-blur-xl shadow-[0_20px_50px_-18px_rgba(0,0,0,0.55)]"
        style={{ transform: 'translateZ(48px)' }}
      >
        <div className="mb-3 flex items-center justify-between">
          <div className="flex items-center gap-1.5 text-white/70">
            <BarChart3 className="h-3.5 w-3.5" />
            <span className="text-[11px] font-medium">KPI trend</span>
          </div>
          <span className="text-[10px] text-cyan-300/80">+12%</span>
        </div>
        <div className="flex h-20 items-end gap-1.5">
          {bars.map((h, i) => (
            <motion.div
              key={i}
              className="flex-1 rounded-sm bg-gradient-to-t from-primary/70 to-brand-secondary/50"
              initial={{ height: 0 }}
              animate={{ height: `${h}%` }}
              transition={{ delay: 0.45 + i * 0.06, duration: 0.55, ease: easeOutExpo }}
            />
          ))}
        </div>
      </div>
    </motion.div>
  );
}

function GrowthCard({
  x,
  y,
  rotateX,
  rotateY,
}: {
  x: Axis;
  y: Axis;
  rotateX: Axis;
  rotateY: Axis;
}) {
  return (
    <motion.div
      className="absolute right-[7%] top-[16%] w-[168px]"
      style={{ x, y, rotateX, rotateY, transformStyle: 'preserve-3d' }}
      initial={{ opacity: 0, y: 28 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ delay: 0.35, duration: 0.65, ease: easeOutExpo }}
    >
      <div
        className="rounded-2xl border border-white/12 bg-white/[0.08] p-4 backdrop-blur-xl shadow-[0_20px_50px_-18px_rgba(0,0,0,0.55)]"
        style={{ transform: 'translateZ(72px)' }}
      >
        <div className="mb-2 flex items-center gap-1.5 text-white/70">
          <TrendingUp className="h-3.5 w-3.5 text-emerald-300" />
          <span className="text-[11px] font-medium">Growth</span>
        </div>
        <p className="text-2xl font-semibold tracking-tight text-white">+18.4%</p>
        <p className="mt-1 text-[11px] text-white/45">vs last evaluation cycle</p>
        <svg viewBox="0 0 140 36" className="mt-3 h-9 w-full overflow-visible">
          <motion.path
            d="M2 28 C 20 26, 28 18, 42 20 S 70 8, 88 12 S 118 4, 138 6"
            fill="none"
            stroke="rgba(110,231,183,0.85)"
            strokeWidth="2.2"
            strokeLinecap="round"
            initial={{ pathLength: 0 }}
            animate={{ pathLength: 1 }}
            transition={{ delay: 0.6, duration: 1.1, ease: easeOutExpo }}
          />
        </svg>
      </div>
    </motion.div>
  );
}

function GoalsCard({
  x,
  y,
  rotateX,
  rotateY,
}: {
  x: Axis;
  y: Axis;
  rotateX: Axis;
  rotateY: Axis;
}) {
  const goals = [
    { label: 'Delivery', value: '96%' },
    { label: 'Quality', value: '91%' },
    { label: 'Impact', value: '88%' },
  ];
  return (
    <motion.div
      className="absolute left-[10%] bottom-[8%] w-[200px]"
      style={{ x, y, rotateX, rotateY, transformStyle: 'preserve-3d' }}
      initial={{ opacity: 0, y: 30 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ delay: 0.45, duration: 0.65, ease: easeOutExpo }}
    >
      <div
        className="rounded-2xl border border-white/12 bg-white/[0.08] p-4 backdrop-blur-xl shadow-[0_20px_50px_-18px_rgba(0,0,0,0.55)]"
        style={{ transform: 'translateZ(56px)' }}
      >
        <div className="mb-3 flex items-center gap-1.5 text-white/70">
          <Target className="h-3.5 w-3.5 text-primary/80" />
          <span className="text-[11px] font-medium">Goal progress</span>
        </div>
        <div className="space-y-2.5">
          {goals.map((g, i) => (
            <div key={g.label}>
              <div className="mb-1 flex items-center justify-between text-[11px]">
                <span className="text-white/60">{g.label}</span>
                <span className="text-white/80">{g.value}</span>
              </div>
              <div className="h-1.5 rounded-full bg-white/10 overflow-hidden">
                <motion.div
                  className="h-full rounded-full bg-gradient-to-r from-primary/70 to-brand-secondary/60"
                  initial={{ width: 0 }}
                  animate={{ width: g.value }}
                  transition={{ delay: 0.7 + i * 0.1, duration: 0.7, ease: easeOutExpo }}
                />
              </div>
            </div>
          ))}
        </div>
      </div>
    </motion.div>
  );
}

function AchievementChip({
  x,
  y,
  rotateX,
  rotateY,
}: {
  x: Axis;
  y: Axis;
  rotateX: Axis;
  rotateY: Axis;
}) {
  return (
    <motion.div
      className="absolute right-[10%] bottom-[12%]"
      style={{ x, y, rotateX, rotateY, transformStyle: 'preserve-3d' }}
      initial={{ opacity: 0, scale: 0.92 }}
      animate={{ opacity: 1, scale: 1 }}
      transition={{ delay: 0.55, duration: 0.55, ease: easeOutExpo }}
    >
      <motion.div
        className="flex items-center gap-2 rounded-full border border-white/15 bg-white/[0.1] px-3.5 py-2 backdrop-blur-xl shadow-lg"
        style={{ transform: 'translateZ(90px)' }}
        animate={{ y: [0, -6, 0] }}
        transition={{ duration: 4.5, repeat: Infinity, ease: 'easeInOut' }}
      >
        <Award className="h-3.5 w-3.5 text-amber-300" />
        <span className="text-[11px] font-medium text-white/80">Top performer · Q1</span>
      </motion.div>
    </motion.div>
  );
}

export function LoginPerformanceScene() {
  const reduceMotion = useReducedMotion();
  const stageRef = useRef<HTMLDivElement>(null);
  const { springX, springY, onPointerMove, onPointerLeave } =
    usePointerParallax(reduceMotion);

  const stageRotateY = useTransform(springX, [-0.5, 0.5], [-10, 10]);
  const stageRotateX = useTransform(springY, [-0.5, 0.5], [8, -8]);

  const farX = useTransform(springX, [-0.5, 0.5], [-10, 10]);
  const farY = useTransform(springY, [-0.5, 0.5], [-8, 8]);
  const midX = useTransform(springX, [-0.5, 0.5], [-22, 22]);
  const midY = useTransform(springY, [-0.5, 0.5], [-16, 16]);
  const nearX = useTransform(springX, [-0.5, 0.5], [-36, 36]);
  const nearY = useTransform(springY, [-0.5, 0.5], [-28, 28]);
  const chipX = useTransform(springX, [-0.5, 0.5], [-48, 48]);
  const chipY = useTransform(springY, [-0.5, 0.5], [-34, 34]);
  const orbX = useTransform(springX, (v) => v * -28);
  const orbY = useTransform(springY, (v) => v * -20);

  const cardRotateY = useTransform(springX, [-0.5, 0.5], [-6, 6]);
  const cardRotateX = useTransform(springY, [-0.5, 0.5], [5, -5]);

  return (
    <div
      ref={stageRef}
      className="absolute inset-0 overflow-hidden"
      onPointerMove={onPointerMove}
      onPointerLeave={onPointerLeave}
    >
      {/* Atmosphere */}
      <div className="absolute inset-0 bg-[radial-gradient(ellipse_at_30%_20%,rgba(124,58,237,0.28),transparent_50%),radial-gradient(ellipse_at_80%_70%,rgba(34,211,238,0.14),transparent_45%),linear-gradient(165deg,#0b0a12_0%,#141122_48%,#0c1520_100%)]" />

      {/* Soft grid floor */}
      <div
        className="pointer-events-none absolute inset-x-[-20%] bottom-[-10%] h-[55%] opacity-[0.18]"
        style={{
          backgroundImage:
            'linear-gradient(rgba(255,255,255,0.09) 1px, transparent 1px), linear-gradient(90deg, rgba(255,255,255,0.09) 1px, transparent 1px)',
          backgroundSize: '48px 48px',
          transform: 'perspective(700px) rotateX(62deg)',
          maskImage: 'linear-gradient(to top, black, transparent)',
        }}
      />

      <motion.div
        className="pointer-events-none absolute left-[15%] top-[20%] h-56 w-56 rounded-full bg-primary/20 blur-3xl"
        style={{ x: farX, y: farY }}
      />
      <motion.div
        className="pointer-events-none absolute right-[10%] bottom-[22%] h-64 w-64 rounded-full bg-cyan-400/10 blur-3xl"
        style={{ x: orbX, y: orbY }}
      />

      {/* 3D stage — upper ~62% so bottom copy stays clear */}
      <div
        className="absolute inset-x-0 top-0 h-[62%] flex items-center justify-center"
        style={{ perspective: 1100 }}
      >
        <motion.div
          className="relative h-[90%] w-[90%] max-w-[520px]"
          style={{
            rotateX: stageRotateX,
            rotateY: stageRotateY,
            transformStyle: 'preserve-3d',
          }}
        >
          <motion.div
            className="absolute left-1/2 top-1/2 h-[240px] w-[280px] -translate-x-1/2 -translate-y-[40%] rounded-full bg-primary/10 blur-2xl"
            style={{ transform: 'translateZ(-40px)' }}
            animate={reduceMotion ? undefined : { opacity: [0.35, 0.55, 0.35] }}
            transition={{ duration: 5, repeat: Infinity, ease: 'easeInOut' }}
          />

          <BarsCard x={farX} y={farY} rotateX={cardRotateX} rotateY={cardRotateY} />
          <GrowthCard x={midX} y={midY} rotateX={cardRotateX} rotateY={cardRotateY} />
          <ScoreRing rotateX={cardRotateX} rotateY={cardRotateY} />
          <GoalsCard x={nearX} y={nearY} rotateX={cardRotateX} rotateY={cardRotateY} />
          <AchievementChip x={chipX} y={chipY} rotateX={cardRotateX} rotateY={cardRotateY} />
        </motion.div>
      </div>

      {/* Stronger bottom fade so copy sits on a clean band */}
      <div className="pointer-events-none absolute inset-x-0 bottom-0 h-[58%] bg-gradient-to-t from-[#0b0a12] via-[#0b0a12]/90 to-transparent" />
      <div className="pointer-events-none absolute inset-0 bg-gradient-to-r from-[#0b0a12]/40 via-transparent to-transparent" />
    </div>
  );
}
