"use client";

import { useEffect, useState } from "react";
import { AnimatePresence, motion } from "framer-motion";
import { Sparkles } from "lucide-react";
import { useAuthStore, isAdmin } from "@/lib/store/useAuthStore";
import AgentePanel from "./AgentePanel";

export default function RichardLauncher() {
  const user = useAuthStore((s) => s.user);
  const [open, setOpen] = useState(false);

  // Cerrar con Escape
  useEffect(() => {
    if (!open) return;
    const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") setOpen(false); };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open]);

  if (!user || !isAdmin(user)) return null;

  return (
    <>
      {/* Botón — arriba a la derecha, gradiente distinto + halo animado constante */}
      <motion.button
        type="button"
        onClick={() => setOpen(true)}
        whileHover={{ scale: 1.03 }}
        whileTap={{ scale: 0.97 }}
        animate={{
          boxShadow: [
            "0 0 0 0 rgba(168,85,247,0.45)",
            "0 0 0 7px rgba(168,85,247,0)",
          ],
        }}
        transition={{ duration: 1.9, repeat: Infinity, ease: "easeOut" }}
        className="hidden md:inline-flex items-center gap-2 rounded-full bg-gradient-to-r from-violet-500 to-fuchsia-500 px-3.5 py-2 text-sm font-bold text-white shadow-sm"
      >
        <motion.span
          animate={{ rotate: [0, 12, -8, 0], scale: [1, 1.12, 1] }}
          transition={{ duration: 2.6, repeat: Infinity, ease: "easeInOut" }}
          className="grid place-items-center"
        >
          <Sparkles size={16} />
        </motion.span>
        Asistente de IA
      </motion.button>

      {/* Drawer lateral derecho */}
      <AnimatePresence>
        {open && (
          <>
            <motion.div
              className="fixed inset-0 z-40 bg-black/30 backdrop-blur-[1px]"
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              exit={{ opacity: 0 }}
              onClick={() => setOpen(false)}
            />
            <motion.div
              role="dialog"
              aria-label="Asistente de IA"
              className="fixed right-0 top-0 z-50 h-dvh w-[440px] max-w-[92vw] border-l border-line bg-surface shadow-[var(--shadow-lg)]"
              initial={{ x: "100%" }}
              animate={{ x: 0 }}
              exit={{ x: "100%" }}
              transition={{ type: "spring", stiffness: 380, damping: 38 }}
            >
              <AgentePanel onClose={() => setOpen(false)} />
            </motion.div>
          </>
        )}
      </AnimatePresence>
    </>
  );
}
