'use client';

import { useEffect, useState } from 'react';
import { motion, AnimatePresence, useReducedMotion } from 'framer-motion';
import Mascot from '../Mascot';

/**
 * A friendly mascot that sits in the corner and changes its speech bubble based
 * on which section is in view. Sections opt in with a `data-companion="..."`
 * attribute. Uses IntersectionObserver (no scroll listeners). Desktop only.
 */
export default function ScrollCompanion() {
  const reduce = useReducedMotion();
  const [msg, setMsg] = useState<string | null>(null);
  const [visible, setVisible] = useState(false);

  useEffect(() => {
    const nodes = Array.from(document.querySelectorAll<HTMLElement>('[data-companion]'));
    if (nodes.length === 0) return;

    const ratios = new Map<HTMLElement, number>();
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => ratios.set(e.target as HTMLElement, e.isIntersecting ? e.intersectionRatio : 0));
        // pick the most-visible opted-in section
        let best: HTMLElement | null = null;
        let bestRatio = 0.15;
        ratios.forEach((r, node) => {
          if (r > bestRatio) {
            bestRatio = r;
            best = node;
          }
        });
        if (best) {
          setMsg((best as HTMLElement).dataset.companion ?? null);
          setVisible(true);
        } else {
          setVisible(false);
        }
      },
      { threshold: [0, 0.2, 0.5, 0.8] },
    );
    nodes.forEach((n) => io.observe(n));
    return () => io.disconnect();
  }, []);

  return (
    <div className="pointer-events-none fixed bottom-5 left-5 z-30 hidden items-end gap-2 lg:flex">
      <AnimatePresence>
        {visible && msg && (
          <motion.div
            key={msg}
            initial={{ opacity: 0, y: 10, scale: 0.9 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={{ opacity: 0, y: 10, scale: 0.9 }}
            transition={{ type: 'spring', stiffness: 300, damping: 24 }}
            className="mb-3 max-w-[220px] rounded-3xl rounded-bl-lg border border-cream-200 bg-white px-4 py-2.5 text-sm font-semibold text-ink shadow-soft"
          >
            {msg}
          </motion.div>
        )}
      </AnimatePresence>
      <motion.div
        animate={reduce ? {} : { y: [0, -6, 0] }}
        transition={{ duration: 3, repeat: Infinity, ease: 'easeInOut' }}
      >
        <Mascot mood="happy" size={64} />
      </motion.div>
    </div>
  );
}
