import { useEffect, useState } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { useTranslation } from "react-i18next";
import { ChevronLeft, ChevronRight, Sparkles } from "lucide-react";
import { LANGUAGES } from "@/i18n";

const STORAGE_KEY = "nadiplay_lang_chosen";

export function hasChosenLanguage(): boolean {
  try {
    return localStorage.getItem(STORAGE_KEY) === "1";
  } catch {
    return false;
  }
}

interface Props {
  onFinish: () => void;
}

/**
 * Game-style first-run language picker. Big animated flag in the centre,
 * left/right arrows (also keyboard ← → and TV remote) cycle through
 * languages with a flick animation. Pressing Continue commits the
 * selection and marks first-run done.
 */
const FirstRunLanguageSelect = ({ onFinish }: Props) => {
  const { i18n, t } = useTranslation();
  const [index, setIndex] = useState(() => {
    const idx = LANGUAGES.findIndex((l) => l.code === i18n.language);
    return idx >= 0 ? idx : 0;
  });
  // direction: +1 = next, -1 = prev. Used for slide-direction animation.
  const [dir, setDir] = useState<1 | -1>(1);

  const lang = LANGUAGES[index];

  // Live-preview the selected language as the user scrolls flags so the
  // labels (Continue button, hint text) update in real time.
  useEffect(() => {
    void i18n.changeLanguage(lang.code);
  }, [lang.code, i18n]);

  const next = () => {
    setDir(1);
    setIndex((i) => (i + 1) % LANGUAGES.length);
  };
  const prev = () => {
    setDir(-1);
    setIndex((i) => (i - 1 + LANGUAGES.length) % LANGUAGES.length);
  };

  // Keyboard / remote support
  useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "ArrowRight") {
        e.preventDefault();
        next();
      } else if (e.key === "ArrowLeft") {
        e.preventDefault();
        prev();
      } else if (e.key === "Enter") {
        e.preventDefault();
        commit();
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const commit = () => {
    try {
      localStorage.setItem(STORAGE_KEY, "1");
      localStorage.setItem("nadiplay_lang", lang.code);
    } catch {
      /* noop */
    }
    onFinish();
  };

  return (
    <motion.div
      data-testid="first-run-lang-select"
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      exit={{ opacity: 0 }}
      transition={{ duration: 0.5, ease: "easeOut" }}
      className="fixed inset-0 z-[9998] overflow-hidden flex flex-col items-center justify-center px-6"
      style={{
        background:
          "radial-gradient(ellipse at center, hsl(200, 40%, 10%) 0%, hsl(200, 30%, 5%) 55%, #000 100%)",
      }}
    >
      {/* Background nebula */}
      <div
        className="absolute inset-0 opacity-30 bg-cover bg-center"
        style={{ backgroundImage: "url('/images/nebula-bg.png')" }}
      />
      <div className="absolute inset-0 bg-background/55" />

      {/* Soft gold glow rings */}
      {[0, 1].map((i) => (
        <motion.div
          key={i}
          initial={{ scale: 0.4, opacity: 0.0 }}
          animate={{ scale: 2.5, opacity: 0 }}
          transition={{
            duration: 4,
            delay: i * 1.2,
            repeat: Infinity,
            ease: "easeOut",
          }}
          className="absolute rounded-full pointer-events-none"
          style={{
            width: 320,
            height: 320,
            border: "1px solid hsla(40, 80%, 55%, 0.28)",
            boxShadow: "0 0 50px hsla(40, 80%, 55%, 0.18)",
          }}
        />
      ))}

      {/* Title */}
      <motion.div
        initial={{ opacity: 0, y: -16 }}
        animate={{ opacity: 1, y: 0 }}
        transition={{ delay: 0.15, duration: 0.6 }}
        className="relative z-10 flex flex-col items-center gap-2 mb-8"
      >
        <div className="flex items-center gap-2 text-primary/90">
          <Sparkles className="w-4 h-4" />
          <span className="text-[10px] sm:text-xs uppercase tracking-[0.4em]">
            NADIPLAYER
          </span>
        </div>
        <h1
          className="font-display text-2xl sm:text-3xl md:text-4xl gold-text tracking-[0.25em] text-center"
          style={{ textShadow: "0 0 30px hsla(40, 80%, 55%, 0.35)" }}
        >
          {t("firstRun.title")}
        </h1>
        <p className="text-muted-foreground text-[11px] sm:text-xs uppercase tracking-[0.3em] text-center max-w-md">
          {t("firstRun.subtitle")}
        </p>
      </motion.div>

      {/* Flag carousel */}
      <div className="relative z-10 flex items-center justify-center gap-4 sm:gap-8 w-full max-w-2xl">
        <button
          type="button"
          onClick={prev}
          data-testid="first-run-prev-btn"
          aria-label="Previous language"
          className="flex items-center justify-center w-12 h-12 sm:w-14 sm:h-14 rounded-full glass border border-primary/30 text-primary hover:bg-primary/15 active:scale-95 transition shrink-0"
        >
          <ChevronLeft className="w-6 h-6" />
        </button>

        <div className="relative flex-1 h-44 sm:h-52 flex items-center justify-center overflow-hidden">
          <AnimatePresence mode="wait" initial={false} custom={dir}>
            <motion.div
              key={lang.code}
              custom={dir}
              initial={(d: number) => ({ x: d * 280, rotate: d * 18, opacity: 0, scale: 0.7 })}
              animate={{ x: 0, rotate: 0, opacity: 1, scale: 1 }}
              exit={(d: number) => ({ x: d * -280, rotate: d * -18, opacity: 0, scale: 0.7 })}
              transition={{ type: "spring", stiffness: 220, damping: 22 }}
              className="absolute flex flex-col items-center gap-3"
              data-testid={`first-run-flag-${lang.code}`}
            >
              <div
                className="w-32 h-32 sm:w-40 sm:h-40 rounded-3xl glass-card flex items-center justify-center"
                style={{
                  border: "1px solid hsla(40, 80%, 55%, 0.45)",
                  boxShadow:
                    "0 0 60px hsla(40, 80%, 55%, 0.35), inset 0 0 30px hsla(40, 80%, 55%, 0.08)",
                }}
              >
                <span
                  className="text-7xl sm:text-8xl leading-none select-none"
                  style={{ filter: "drop-shadow(0 0 20px hsla(40, 80%, 55%, 0.4))" }}
                >
                  {lang.flag}
                </span>
              </div>
              <div className="text-center">
                <div className="font-display text-xl sm:text-2xl gold-text tracking-[0.2em]">
                  {lang.label}
                </div>
                <div className="text-[10px] uppercase tracking-[0.4em] text-muted-foreground mt-1">
                  {lang.code.toUpperCase()}
                </div>
              </div>
            </motion.div>
          </AnimatePresence>
        </div>

        <button
          type="button"
          onClick={next}
          data-testid="first-run-next-btn"
          aria-label="Next language"
          className="flex items-center justify-center w-12 h-12 sm:w-14 sm:h-14 rounded-full glass border border-primary/30 text-primary hover:bg-primary/15 active:scale-95 transition shrink-0"
        >
          <ChevronRight className="w-6 h-6" />
        </button>
      </div>

      {/* Dots */}
      <div className="relative z-10 flex items-center gap-2 mt-6">
        {LANGUAGES.map((l, i) => (
          <button
            key={l.code}
            type="button"
            onClick={() => {
              setDir(i > index ? 1 : -1);
              setIndex(i);
            }}
            data-testid={`first-run-dot-${l.code}`}
            aria-label={`Select ${l.label}`}
            className={`h-2 rounded-full transition-all ${
              i === index
                ? "w-8 bg-primary shadow-[0_0_12px_hsla(40,80%,55%,0.6)]"
                : "w-2 bg-muted-foreground/30 hover:bg-muted-foreground/60"
            }`}
          />
        ))}
      </div>

      {/* Continue */}
      <motion.button
        type="button"
        onClick={commit}
        data-testid="first-run-continue-btn"
        whileHover={{ scale: 1.03 }}
        whileTap={{ scale: 0.97 }}
        className="relative z-10 mt-10 px-10 py-3 rounded-full bg-primary text-primary-foreground font-semibold tracking-[0.3em] uppercase text-sm shadow-[0_8px_30px_hsla(40,80%,55%,0.4)] hover:brightness-110"
      >
        {t("firstRun.continue")}
      </motion.button>

      <p className="relative z-10 mt-4 text-[10px] uppercase tracking-[0.3em] text-muted-foreground/70">
        {t("firstRun.hint")}
      </p>
    </motion.div>
  );
};

export default FirstRunLanguageSelect;
