'use client';

import React, { useEffect, useState } from 'react';
import { AnimatePresence, motion, useReducedMotion } from 'framer-motion';
import { CHAKRA_METADATA } from '@/lib/aura/calculator';
import { chakraMeta } from '@/lib/aura/chakraMeta';
import { useLocale, useMessages } from '@/i18n/client';
import { ChakraType } from '@/lib/aura/types';

/** How long the scan sequence runs; the parent waits at least this long. */
export const AURA_SCAN_MIN_MS = 4200;

const CHAKRAS: ChakraType[] = [
  'root',
  'sacral',
  'solar_plexus',
  'heart',
  'throat',
  'third_eye',
  'crown',
];

const CHAKRA_COLORS = CHAKRAS.map((c) => CHAKRA_METADATA[c].color);
/** Every language has the same number of scan steps. */
const STEP_COUNT = 5;
const AURA_CONIC = `conic-gradient(from 0deg, ${[...CHAKRA_COLORS, CHAKRA_COLORS[0]].join(', ')})`;

// Keeps only a thin band at the outer edge of a circle.
const RING_MASK =
  'radial-gradient(farthest-side, transparent calc(100% - 4px), #000 calc(100% - 3px))';

interface AuraScanAnimationProps {
  photo: string;
}

export const AuraScanAnimation: React.FC<AuraScanAnimationProps> = ({ photo }) => {
  const reduceMotion = useReducedMotion();
  const locale = useLocale();
  const t = useMessages().camera.scan;
  const SCAN_STEPS = t.steps;
  const [step, setStep] = useState(0);

  useEffect(() => {
    const interval = AURA_SCAN_MIN_MS / STEP_COUNT;
    const id = window.setInterval(() => {
      setStep((s) => Math.min(s + 1, STEP_COUNT - 1));
    }, interval);
    return () => window.clearInterval(id);
  }, []);

  const spin = (duration: number, reverse = false) =>
    reduceMotion
      ? {}
      : {
          animate: { rotate: reverse ? -360 : 360 },
          transition: { duration, repeat: Infinity, ease: 'linear' as const },
        };

  return (
    <motion.div
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      transition={{ duration: 0.4 }}
      className="relative flex flex-col items-center justify-center overflow-hidden px-6 py-12 text-center sm:py-16"
    >
      {/* Ambient aura bloom behind everything */}
      <motion.div
        aria-hidden
        className="pointer-events-none absolute top-1/2 left-1/2 size-[440px] -translate-x-1/2 -translate-y-[60%] rounded-full opacity-30 blur-[90px]"
        style={{ background: AURA_CONIC }}
        {...spin(10)}
      />

      <div className="relative size-56 sm:size-64">
        {/* Expanding energy pulses */}
        {!reduceMotion &&
          [0, 1, 2].map((i) => (
            <motion.div
              key={i}
              aria-hidden
              className="absolute inset-0 rounded-full border border-white/30"
              initial={{ scale: 1, opacity: 0 }}
              animate={{ scale: [1, 1.55], opacity: [0.5, 0] }}
              transition={{ duration: 2.4, repeat: Infinity, delay: i * 0.8, ease: 'easeOut' }}
            />
          ))}

        {/* Glowing chakra ring (blurred copy + crisp copy) */}
        <motion.div
          aria-hidden
          className="absolute -inset-3 rounded-full blur-md"
          style={{ background: AURA_CONIC, mask: RING_MASK, WebkitMask: RING_MASK }}
          {...spin(4)}
        />
        <motion.div
          aria-hidden
          className="absolute -inset-3 rounded-full"
          style={{ background: AURA_CONIC, mask: RING_MASK, WebkitMask: RING_MASK }}
          {...spin(4)}
        />

        {/* Dashed tech ring, counter-rotating */}
        <motion.div
          aria-hidden
          className="absolute -inset-7 rounded-full border border-dashed border-white/15"
          {...spin(18, true)}
        />

        {/* Orbiting chakra particles */}
        <motion.div aria-hidden className="absolute -inset-7" {...spin(9)}>
          {CHAKRA_COLORS.map((color, i) => {
            const angle = (i / CHAKRA_COLORS.length) * Math.PI * 2;
            return (
              <span
                key={color}
                className="absolute size-2 -translate-x-1/2 -translate-y-1/2 rounded-full"
                style={{
                  left: `${50 + 50 * Math.cos(angle)}%`,
                  top: `${50 + 50 * Math.sin(angle)}%`,
                  backgroundColor: color,
                  boxShadow: `0 0 12px 2px ${color}`,
                }}
              />
            );
          })}
        </motion.div>

        {/* Portrait with scan overlays */}
        <div className="absolute inset-0 overflow-hidden rounded-full border border-white/20 bg-black">
          <motion.img
            src={photo}
            alt={t.photoAlt}
            className="size-full object-cover"
            initial={{ scale: 1.15, filter: 'saturate(0.4) brightness(0.8)' }}
            animate={{ scale: 1, filter: 'saturate(1.1) brightness(1)' }}
            transition={{ duration: AURA_SCAN_MIN_MS / 1000, ease: 'easeOut' }}
          />

          {/* Biometric dot grid */}
          <motion.div
            aria-hidden
            className="absolute inset-0 mix-blend-screen"
            style={{
              backgroundImage:
                'radial-gradient(circle, rgba(165,180,252,0.55) 1px, transparent 1.5px)',
              backgroundSize: '14px 14px',
            }}
            animate={reduceMotion ? undefined : { opacity: [0.15, 0.5, 0.15] }}
            transition={{ duration: 2, repeat: Infinity, ease: 'easeInOut' }}
          />

          {/* Colour wash that cycles through the chakra hues */}
          <motion.div
            aria-hidden
            className="absolute inset-0 mix-blend-soft-light"
            animate={reduceMotion ? undefined : { backgroundColor: CHAKRA_COLORS }}
            transition={{ duration: 5, repeat: Infinity, ease: 'linear' }}
            style={{ opacity: 0.55 }}
          />

          {/* Scan beam */}
          {!reduceMotion && (
            <motion.div
              aria-hidden
              className="absolute inset-x-0 h-24"
              initial={{ top: '-30%' }}
              animate={{ top: ['-30%', '100%'] }}
              transition={{ duration: 1.8, repeat: Infinity, repeatType: 'reverse', ease: 'easeInOut' }}
            >
              <div className="h-full w-full bg-gradient-to-b from-transparent via-indigo-300/25 to-transparent" />
              <div className="absolute inset-x-0 top-1/2 h-px bg-indigo-100 shadow-[0_0_14px_3px_rgba(165,180,252,0.9)]" />
            </motion.div>
          )}
        </div>

        {/* Corner brackets */}
        <div aria-hidden className="pointer-events-none absolute -inset-10">
          {[
            'top-0 left-0 border-t-2 border-l-2 rounded-tl-lg',
            'top-0 right-0 border-t-2 border-r-2 rounded-tr-lg',
            'bottom-0 left-0 border-b-2 border-l-2 rounded-bl-lg',
            'bottom-0 right-0 border-b-2 border-r-2 rounded-br-lg',
          ].map((pos) => (
            <motion.span
              key={pos}
              className={`absolute size-5 border-white/60 ${pos}`}
              animate={reduceMotion ? undefined : { opacity: [0.3, 1, 0.3] }}
              transition={{ duration: 1.6, repeat: Infinity }}
            />
          ))}
        </div>
      </div>

      {/* Status copy */}
      <div className="relative mt-16 w-full max-w-xs space-y-4">
        <h4 className="text-xl font-medium tracking-tight text-white">{t.title}</h4>

        <div className="relative h-5">
          <AnimatePresence mode="wait">
            <motion.p
              key={step}
              initial={{ opacity: 0, y: 8, filter: 'blur(4px)' }}
              animate={{ opacity: 1, y: 0, filter: 'blur(0px)' }}
              exit={{ opacity: 0, y: -8, filter: 'blur(4px)' }}
              transition={{ duration: 0.3 }}
              className="absolute inset-x-0 font-mono text-xs tracking-wide text-indigo-200/80"
            >
              {SCAN_STEPS[step]}…
            </motion.p>
          </AnimatePresence>
        </div>

        {/* Progress */}
        <div className="h-1 w-full overflow-hidden rounded-full bg-white/10">
          <motion.div
            className="h-full rounded-full"
            style={{ background: `linear-gradient(90deg, ${CHAKRA_COLORS.join(', ')})` }}
            initial={{ width: '0%' }}
            animate={{ width: '96%' }}
            transition={{ duration: AURA_SCAN_MIN_MS / 1000, ease: [0.16, 1, 0.3, 1] }}
          />
        </div>

        {/* Chakras lighting up root → crown */}
        <div className="flex items-center justify-center gap-2.5 pt-1">
          {CHAKRAS.map((c, i) => {
            const color = CHAKRA_METADATA[c].color;
            return (
              <motion.span
                key={c}
                title={chakraMeta(locale)[c].name}
                className="size-2.5 rounded-full"
                initial={{ backgroundColor: 'rgba(255,255,255,0.12)', scale: 0.8 }}
                animate={{
                  backgroundColor: color,
                  scale: [0.8, 1.4, 1],
                  boxShadow: `0 0 10px 1px ${color}`,
                }}
                transition={{
                  delay: ((i + 1) / (CHAKRAS.length + 1)) * (AURA_SCAN_MIN_MS / 1000),
                  duration: 0.45,
                }}
              />
            );
          })}
        </div>
      </div>
    </motion.div>
  );
};
