"use client";

import { AnimatePresence, motion } from "framer-motion";
import { useEffect, useRef, useState } from "react";

interface TypingRoomIntroProps {
  active: boolean;
  onFinish: () => void;
}

export function TypingRoomIntro({ active, onFinish }: TypingRoomIntroProps) {
  const [step, setStep] = useState(0);
  const [garble, setGarble] = useState("");
  const garbleRef = useRef<number | null>(null);

  useEffect(() => {
    if (!active) {
      setStep(0);
      return;
    }

    const timers = [
      window.setTimeout(() => setStep(1), 280),
      window.setTimeout(() => setStep(2), 900),
      window.setTimeout(() => setStep(3), 1700),
      window.setTimeout(() => setStep(4), 2800),
      window.setTimeout(onFinish, 3600),
    ];

    return () => {
      timers.forEach((timer) => window.clearTimeout(timer));
    };
  }, [active, onFinish]);

  // Garbled typing generator while Space is "typing"
  useEffect(() => {
    if (step >= 3 && step < 4) {
      setGarble("");
      const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()[]{}<>~-=_+";
      garbleRef.current = window.setInterval(() => {
        // create a short random string to simulate garble
        const len = 20;
        let s = "";
        for (let i = 0; i < len; i++) {
          s += charset[Math.floor(Math.random() * charset.length)];
        }
        setGarble(s);
      }, 120);
    } else {
      if (garbleRef.current) {
        window.clearInterval(garbleRef.current);
        garbleRef.current = null;
      }
      setGarble("");
    }

    return () => {
      if (garbleRef.current) {
        window.clearInterval(garbleRef.current);
        garbleRef.current = null;
      }
    };
  }, [step]);

  useEffect(() => {
    if (!active) {
      return;
    }

    const originalOverflow = document.body.style.overflow;
    document.body.style.overflow = "hidden";

    return () => {
      document.body.style.overflow = originalOverflow;
    };
  }, [active]);

  useEffect(() => {
    if (!active) {
      return;
    }

    const handleEscape = (event: KeyboardEvent) => {
      if (event.key === "Escape") {
        onFinish();
      }
    };

    window.addEventListener("keydown", handleEscape);

    return () => {
      window.removeEventListener("keydown", handleEscape);
    };
  }, [active, onFinish]);

  return (
    <AnimatePresence>
      {active && (
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          exit={{ opacity: 0, transition: { duration: 0.45, ease: "easeInOut" } }}
          className="fixed inset-0 z-[220] flex items-center justify-center bg-[#020205] px-4"
          aria-live="polite"
          role="dialog"
          aria-modal="true"
        >
          <div className="absolute inset-0 bg-[radial-gradient(circle_at_20%_20%,rgba(56,189,248,0.25),transparent_45%),radial-gradient(circle_at_80%_70%,rgba(59,130,246,0.16),transparent_45%),#020205]" />
          <div className="absolute inset-0 bg-[linear-gradient(transparent_95%,rgba(255,255,255,0.03)_100%)] bg-[length:100%_6px] opacity-60" />

          <motion.div
            initial={{ y: 32, scale: 0.96, opacity: 0 }}
            animate={{ y: 0, scale: 1, opacity: 1 }}
            exit={{ y: -24, scale: 0.98, opacity: 0 }}
          transition={{ duration: 0.55, ease: [0.22, 1, 0.36, 1] }}
            className="relative w-full max-w-[20rem] overflow-hidden rounded-3xl border border-cyan-300/20 bg-black/55 backdrop-blur-xl shadow-[0_32px_90px_rgba(14,165,233,0.25)] sm:max-w-2xl"
          >
            <div className="flex items-center justify-between border-b border-white/10 bg-white/5 px-4 py-3 sm:px-5">
              <div className="flex items-center gap-2">
                <span className="h-2.5 w-2.5 rounded-full bg-red-400/80" />
                <span className="h-2.5 w-2.5 rounded-full bg-amber-300/80" />
                <span className="h-2.5 w-2.5 rounded-full bg-emerald-400/80" />
              </div>
              <p className="text-xs uppercase tracking-[0.3em] text-cyan-100/70">
                Orbital Chat
              </p>
              <span className="rounded-full border border-cyan-300/30 px-2 py-0.5 text-[10px] font-medium text-cyan-200/80">
                live
              </span>
            </div>

            <div className="space-y-4 p-4 sm:p-6 md:p-8">
              <motion.p
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                className="text-xs uppercase tracking-[0.25em] text-cyan-100/50"
              >
                Breaking Websockets...
              </motion.p>

              {step >= 1 && (
                <motion.div
                  initial={{ opacity: 0, x: -16 }}
                  animate={{ opacity: 1, x: 0 }}
                  className="max-w-[86%] rounded-2xl rounded-bl-md border border-white/10 bg-white/10 px-3 py-2.5 text-xs text-gray-100 sm:px-4 sm:py-3 sm:text-sm"
                >
                  Why is this page taking so long to load??
                </motion.div>
              )}

              {step >= 2 && (
                <motion.div
                  initial={{ opacity: 0, x: 16 }}
                  animate={{ opacity: 1, x: 0 }}
                  className="ml-auto max-w-[88%] rounded-2xl rounded-br-md border border-cyan-300/30 bg-cyan-400/15 px-3 py-2.5 text-xs text-cyan-50 sm:px-4 sm:py-3 sm:text-sm"
                >
                  I have to somehow hide the fact that my discord status is taking a while to load... :D
                </motion.div>
              )}

              {step >= 4 && (
                <motion.div
                  initial={{ opacity: 0, x: 12 }}
                  animate={{ opacity: 1, x: 0 }}
                  className="ml-auto max-w-[88%] rounded-2xl rounded-br-md border border-cyan-300/35 bg-cyan-400/20 px-3 py-2.5 text-xs text-cyan-50 sm:px-4 sm:py-3 sm:text-sm"
                >
                  Ok done, just one more animation
                </motion.div>
              )}
            </div>

            <div className="relative border-t border-white/10 bg-black/35 px-4 pb-4 pt-4 sm:px-6 sm:pb-5">
              {/* Small badge left-above the input showing typing status (hidden once final message shows) */}
              {step < 4 && (
                <div className="absolute left-4 -top-6 flex items-center gap-2 sm:left-6">
                  <span className="text-xs font-medium text-cyan-100 sm:text-sm">Space is typing...</span>
                  <div className="flex items-center gap-1.5">
                    {[0, 1, 2].map((dot) => (
                      <motion.span
                        key={dot}
                        animate={{ y: [0, -3, 0], opacity: [0.3, 1, 0.3] }}
                        transition={{ duration: 0.95, repeat: Infinity, delay: dot * 0.14, ease: "easeInOut" }}
                        className="h-1.5 w-1.5 rounded-full bg-cyan-200"
                      />
                    ))}
                  </div>
                </div>
              )}

              <div className="flex items-center justify-between gap-3 text-xs text-cyan-100/70">
                <span className="inline-flex items-center gap-2">
                  <span className="h-2 w-2 rounded-full bg-emerald-300 shadow-[0_0_10px_rgba(110,231,183,0.75)]" />
                  You & Space
                </span>
                <span className="text-[11px] text-gray-400">Esc to skip</span>
              </div>

              <div className="mt-3 flex min-h-[44px] items-center rounded-xl border border-white/10 bg-white/5 px-3 py-2.5 sm:px-4">
                {step >= 3 && step < 4 ? (
                  <motion.div initial={{ opacity: 0, y: 6 }} animate={{ opacity: 1, y: 0 }} className="flex items-center gap-2.5 font-mono text-xs text-cyan-100 sm:text-sm">
                    <span className="select-all">{garble || "…"}</span>
                  </motion.div>
                ) : (
                  <p className="text-xs text-gray-500 sm:text-sm">Message Space</p>
                )}
              </div>
            </div>

            <motion.div
              initial={{ scaleX: 0 }}
              animate={{ scaleX: step >= 4 ? 1 : step / 4 }}
              transition={{ duration: 0.45, ease: "easeOut" }}
              className="h-1 origin-left bg-gradient-to-r from-cyan-300 via-blue-400 to-cyan-300"
            />
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>
  );
}
