"use client";

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

const IDLE_MS = 20_000;
const LINES = [
  "Il se passe quoi ?",
  "On tire, ou on dort ?",
  "Hé… y a quelqu’un ?",
  "C’est calme, pour un stand.",
  "Woodstock, t’as vu du monde ?",
];

export function IdleSnoopy() {
  const [visible, setVisible] = useState(false);
  const [phase, setPhase] = useState<"in" | "talk" | "out">("in");
  const [line, setLine] = useState(LINES[0]);
  const armRef = useRef<(reset?: boolean) => void>(() => {});

  useEffect(() => {
    if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) return;

    let idleTimer = 0;

    const arm = (resetVisible = true) => {
      window.clearTimeout(idleTimer);
      if (resetVisible) {
        setVisible(false);
        setPhase("in");
      }
      idleTimer = window.setTimeout(() => {
        setLine(LINES[Math.floor(Math.random() * LINES.length)]);
        setPhase("in");
        setVisible(true);
      }, IDLE_MS);
    };

    armRef.current = arm;
    arm(false);

    const onAction = () => arm(true);
    const events = ["pointerdown", "keydown", "scroll", "wheel", "touchstart", "mousemove"];
    events.forEach((e) => window.addEventListener(e, onAction, { passive: true }));
    return () => {
      window.clearTimeout(idleTimer);
      events.forEach((e) => window.removeEventListener(e, onAction));
    };
  }, []);

  useEffect(() => {
    if (!visible || phase !== "talk") return;
    const t = window.setTimeout(() => setPhase("out"), 4500);
    return () => window.clearTimeout(t);
  }, [visible, phase]);

  const x = phase === "out" ? "108vw" : "36vw";
  const walking = phase !== "talk";

  return (
    <AnimatePresence>
      {visible && (
        <motion.div
          className="pointer-events-none fixed bottom-6 z-[88] md:bottom-10"
          initial={{ x: "-28vw" }}
          animate={{ x }}
          exit={{ opacity: 0, transition: { duration: 0.25 } }}
          transition={{
            duration: phase === "talk" ? 0.25 : 5.2,
            ease: phase === "talk" ? "easeOut" : "linear",
          }}
          onAnimationComplete={() => {
            if (phase === "in") setPhase("talk");
            if (phase === "out") {
              setVisible(false);
              setPhase("in");
              armRef.current(false);
            }
          }}
        >
          <div className="relative">
            <AnimatePresence>
              {phase === "talk" && (
                <motion.div
                  className="snoopy-bubble absolute top-6 left-[70%] w-max max-w-[250px] md:top-8"
                  initial={{ scale: 0.5, opacity: 0, y: 12 }}
                  animate={{ scale: 1, opacity: 1, y: 0 }}
                  exit={{ scale: 0.8, opacity: 0 }}
                >
                  {line}
                </motion.div>
              )}
            </AnimatePresence>
            <div className="-scale-x-100">
              <img
                src="/images/snoopy.png"
                alt=""
                width={220}
                height={220}
                className={`h-40 w-auto drop-shadow-[4px_10px_0_rgba(0,0,0,0.35)] md:h-52 ${
                  walking ? "snoopy-waddle" : "snoopy-idle"
                }`}
              />
            </div>
          </div>
        </motion.div>
      )}
    </AnimatePresence>
  );
}
