"use client";

import { useRef, useState } from "react";
import { AnimatePresence, motion } from "framer-motion";
import { Hash } from "lucide-react";
import { gsap } from "@/lib/gsap";
import { popConfetti } from "@/lib/confetti";
import { useSound } from "@/components/providers/sound-provider";
import { useLocalStorage } from "@/hooks/use-local-storage";
import { usePrefersReducedMotion } from "@/hooks/use-prefers-reduced-motion";

const randInt = (lo: number, hi: number) =>
  lo + Math.floor(Math.random() * (hi - lo + 1));

const toInt = (raw: string) => {
  const n = Math.round(Number(raw));
  return Number.isFinite(n) ? n : 0;
};

export default function RandomNumber() {
  const [min, setMin] = useLocalStorage("num-min", 1);
  const [max, setMax] = useLocalStorage("num-max", 100);
  const [display, setDisplay] = useState<string | null>(null);
  const [rolling, setRolling] = useState(false);
  const [done, setDone] = useState(false);

  const lastPaintRef = useRef(0);
  const { play } = useSound();
  const reduced = usePrefersReducedMotion();

  const roll = () => {
    if (rolling) return;

    const lo = Math.min(min, max);
    const hi = Math.max(min, max);
    const result = randInt(lo, hi);

    setRolling(true);
    setDone(false);
    play("whoosh");

    const dur = reduced ? 0.3 : 1.7;
    const proxy = { p: 0 };
    lastPaintRef.current = 0;

    gsap.to(proxy, {
      p: 1,
      duration: dur,
      ease: "power2.out",
      onUpdate: () => {
        const now = performance.now();
        // Wechsel-Intervall wächst → Slot-Machine-Effekt
        const interval = reduced ? 60 : 28 + 240 * proxy.p;
        if (now - lastPaintRef.current > interval) {
          lastPaintRef.current = now;
          setDisplay(String(randInt(lo, hi)));
        }
      },
      onComplete: () => {
        setDisplay(String(result));
        setRolling(false);
        setDone(true);
        play("pop");
        popConfetti();
      },
    });
  };

  return (
    <div className="grid items-center gap-10 lg:grid-cols-[1.15fr_0.85fr]">
      {/* Anzeige */}
      <div className="flex flex-col items-center">
        <div className="flex min-h-[190px] items-center justify-center rounded-[2rem] border border-line bg-cream/70 px-10 py-8">
          <AnimatePresence mode="wait">
            {display === null ? (
              <motion.p
                key="idle"
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                className="text-center font-display text-xl font-medium text-ink-soft"
              >
                Bereit, wenn du es bist.
              </motion.p>
            ) : (
              <motion.p
                key={display + (done ? "-done" : "")}
                initial={done ? { scale: 1.35, opacity: 0 } : false}
                animate={{ scale: 1, opacity: 1 }}
                transition={{ type: "spring", stiffness: 320, damping: 18 }}
                className={`tabular font-display text-8xl font-semibold tracking-tight sm:text-9xl ${
                  done ? "text-primary" : "text-ink/70"
                }`}
                aria-live="polite"
              >
                {display}
              </motion.p>
            )}
          </AnimatePresence>
        </div>

        <motion.button
          type="button"
          onClick={roll}
          disabled={rolling}
          whileTap={{ scale: 0.95 }}
          className="mt-6 inline-flex cursor-pointer items-center gap-2 rounded-full bg-primary px-9 py-3.5 text-base font-semibold text-white shadow-cta transition-colors duration-200 hover:bg-primary-strong disabled:cursor-not-allowed disabled:opacity-60"
        >
          <Hash className="h-5 w-5" />
          {rolling ? "Rollt …" : "Zahl generieren"}
        </motion.button>
        <p className="mt-3 text-xs text-ink-soft">
          Zufallszahl zwischen {Math.min(min, max)} und {Math.max(min, max)}
        </p>
      </div>

      {/* Einstellungen */}
      <div className="rounded-3xl border border-line bg-cream/70 p-5">
        <h3 className="text-sm font-semibold uppercase tracking-[0.16em] text-ink-soft">
          Zahlenraum
        </h3>
        <div className="mt-4 grid grid-cols-2 gap-3">
          <label className="block">
            <span className="mb-1.5 block text-xs font-medium text-ink-soft">
              Minimum
            </span>
            <input
              type="number"
              step={1}
              value={min}
              onChange={(e) => setMin(toInt(e.target.value))}
              disabled={rolling}
              className="tabular w-full rounded-xl border border-line bg-surface px-3.5 py-2.5 text-sm font-medium outline-none transition focus:border-primary/60 focus:ring-2 focus:ring-primary/20 disabled:cursor-not-allowed disabled:opacity-60"
            />
          </label>
          <label className="block">
            <span className="mb-1.5 block text-xs font-medium text-ink-soft">
              Maximum
            </span>
            <input
              type="number"
              step={1}
              value={max}
              onChange={(e) => setMax(toInt(e.target.value))}
              disabled={rolling}
              className="tabular w-full rounded-xl border border-line bg-surface px-3.5 py-2.5 text-sm font-medium outline-none transition focus:border-primary/60 focus:ring-2 focus:ring-primary/20 disabled:cursor-not-allowed disabled:opacity-60"
            />
          </label>
        </div>
        <p className="mt-3 text-xs leading-relaxed text-ink-soft">
          Perfekt für Lose, Teams oder „Wie viele Liegestütze?“. Reihenfolge
          von Min &amp; Max ist egal.
        </p>
      </div>
    </div>
  );
}
