import React, { useState, useEffect, useRef, useCallback } from 'react'
import { motion, AnimatePresence } from 'framer-motion'

const spring = { type: 'spring', stiffness: 280, damping: 18 }

const TAP_LINES = [
    'Hi there!', 'Need data?', "Let's go!", 'Boop!',
    'Cheap rates inside', 'Tap tap!', "I'm Fargo!", 'Ready when you are',
]

// mode: 'idle' | 'typing' | 'covered' | 'peek' | 'happy' | 'worried' | 'processing'
export default function Mascot({ mode = 'idle', typedLength = 0, size = 116, interactive = true }) {
    const wrapRef = useRef(null)
    const [pupil, setPupil] = useState({ x: 0, y: 0 })
    const [blink, setBlink] = useState(false)
    const [sleepy, setSleepy] = useState(false)
    const [tapped, setTapped] = useState(false)
    const [bubble, setBubble] = useState(null)
    const idleTimer = useRef(null)

    const covered = mode === 'covered'
    const peek = mode === 'peek'
    const happy = mode === 'happy'
    const worried = mode === 'worried'
    const processing = mode === 'processing'
    const eyesShut = (covered && !peek) || happy
    const shut = eyesShut || blink

    // Sleepy after 8s of no mouse movement
    const resetIdle = useCallback(() => {
        setSleepy(false)
        clearTimeout(idleTimer.current)
        idleTimer.current = setTimeout(() => setSleepy(true), 15000)
    }, [])

    useEffect(() => {
        const move = (e) => {
            resetIdle()
            if (!wrapRef.current || covered || happy) return
            const r = wrapRef.current.getBoundingClientRect()
            const cx = r.left + r.width / 2
            const cy = r.top + r.height / 2
            const dx = (e.clientX - cx) / r.width
            const dy = (e.clientY - cy) / r.height
            const max = 3.2
            setPupil({
                x: Math.max(-max, Math.min(max, dx * 8)),
                y: Math.max(-max, Math.min(max, dy * 8)),
            })
        }
        window.addEventListener('mousemove', move)
        resetIdle()
        return () => { window.removeEventListener('mousemove', move); clearTimeout(idleTimer.current) }
    }, [covered, happy, resetIdle])

    // Auto-blink
    useEffect(() => {
        let t
        const loop = () => {
            const delay = 3000 + Math.random() * 2500
            t = setTimeout(() => {
                setBlink(true)
                setTimeout(() => setBlink(false), 130)
                loop()
            }, delay)
        }
        loop()
        return () => clearTimeout(t)
    }, [])

    const handleTap = () => {
        if (!interactive) return
        setSleepy(false)
        resetIdle()
        setTapped(true)
        setTimeout(() => setTapped(false), 600)
        const line = TAP_LINES[Math.floor(Math.random() * TAP_LINES.length)]
        setBubble(line)
        setTimeout(() => setBubble(null), 1800)
    }

    // open mouth state: happy, peek, tapped, or talking
    const mouthOpen = happy || peek || tapped || !!bubble
    const blush = tapped || happy

    return (
        <div className="flex justify-center relative" ref={wrapRef}>
            {/* Speech bubble */}
            <AnimatePresence>
                {bubble && (
                    <motion.div
                        initial={{ opacity: 0, y: 8, scale: 0.8 }}
                        animate={{ opacity: 1, y: 0, scale: 1 }}
                        exit={{ opacity: 0, y: 8, scale: 0.8 }}
                        transition={spring}
                        className="absolute -top-2 left-1/2 -translate-x-1/2 -translate-y-full z-20"
                    >
                        <div className="text-white text-[12px] font-semibold px-3 py-1.5 rounded-2xl whitespace-nowrap shadow-lg" style={{ background: 'var(--accent)' }}>
                            {bubble}
                        </div>
                        <div className="w-2 h-2 rotate-45 mx-auto -mt-1" style={{ background: 'var(--accent)' }} />
                    </motion.div>
                )}
            </AnimatePresence>

            <motion.div
                onTap={handleTap}
                whileTap={interactive ? { scale: 0.92 } : {}}
                animate={
                    tapped ? { rotate: [0, -8, 8, -4, 0], y: [0, -6, 0] }
                    : happy ? { y: [0, -10, 0], scale: [1, 1.05, 1] }
                    : worried ? { rotate: [-4, 4, -4, 0] }
                    : processing ? { y: [0, -3, 0] }
                    : { y: [0, -4, 0] }
                }
                transition={
                    tapped ? { duration: 0.5 }
                    : happy ? { duration: 0.5, repeat: 1 }
                    : worried ? { duration: 0.4 }
                    : processing ? { duration: 0.8, repeat: Infinity, ease: 'easeInOut' }
                    : { duration: 3.5, repeat: Infinity, ease: 'easeInOut' }
                }
                style={{ cursor: interactive ? 'pointer' : 'default' }}
            >
                <svg width={size} height={size} viewBox="0 0 120 120">
                    <defs>
                        <radialGradient id="orb" cx="38%" cy="32%" r="75%">
                            <stop offset="0%" stopColor="#363B42" />
                            <stop offset="55%" stopColor="#22262B" />
                            <stop offset="100%" stopColor="#15181C" />
                        </radialGradient>
                        <radialGradient id="rim" cx="50%" cy="50%" r="50%">
                            <stop offset="80%" stopColor="transparent" />
                            <stop offset="100%" stopColor="#1A56DB30" />
                        </radialGradient>
                        <radialGradient id="eye" cx="35%" cy="30%" r="70%">
                            <stop offset="0%" stopColor="#FFFFFF" />
                            <stop offset="70%" stopColor="#EDF1F6" />
                            <stop offset="100%" stopColor="#D4DCE6" />
                        </radialGradient>
                        <filter id="soft" x="-50%" y="-50%" width="200%" height="200%">
                            <feGaussianBlur stdDeviation="3" />
                        </filter>
                        <clipPath id="mouthClip">
                            <motion.path
                                animate={{
                                    d: mouthOpen
                                        ? 'M 48 70 Q 60 70 72 70 Q 72 84 60 84 Q 48 84 48 70 Z'
                                        : 'M 50 74 Q 60 76 70 74 Q 60 76 50 74 Z',
                                }}
                                transition={{ duration: 0.2 }}
                            />
                        </clipPath>
                    </defs>

                    {/* Shadow */}
                    <motion.ellipse
                        cx="60" cy="110" rx="26" ry="5"
                        fill="#000" opacity="0.35" filter="url(#soft)"
                        animate={{ rx: [26, 22, 26], opacity: [0.35, 0.25, 0.35] }}
                        transition={{ duration: 3.5, repeat: Infinity, ease: 'easeInOut' }}
                    />

                   

                    {/* Rings */}
                    <circle cx="60" cy="56" r="46" fill="none" stroke="#1A56DB" strokeWidth="1.5" opacity="0.3" />
                    <circle cx="60" cy="56" r="50" fill="url(#rim)" />

                    {/* Head */}
                    <motion.circle
                        cx="60" cy="56" r="40"
                        fill="url(#orb)" stroke="#2E333A" strokeWidth="1"
                        animate={{ scaleX: covered ? 1.02 : 1, scaleY: covered ? 0.97 : 1 }}
                        transition={spring}
                        style={{ transformOrigin: '60px 56px' }}
                    />
                    <ellipse cx="48" cy="40" rx="16" ry="10" fill="#FFFFFF" opacity="0.06" />

                    {/* Blush */}
                    <AnimatePresence>
                        {blush && (
                            <>
                                <motion.circle
                                    initial={{ opacity: 0 }} animate={{ opacity: 0.3 }} exit={{ opacity: 0 }}
                                    cx="38" cy="62" r="6" fill="#E8907A" />
                                <motion.circle
                                    initial={{ opacity: 0 }} animate={{ opacity: 0.3 }} exit={{ opacity: 0 }}
                                    cx="82" cy="62" r="6" fill="#E8907A" />
                            </>
                        )}
                    </AnimatePresence>

                    {/* Eyes */}
                    <motion.g animate={{ y: happy ? -2 : 0 }} transition={spring}>
                        {[46, 74].map((ex, idx) => (
                            <g key={idx}>
                                <motion.ellipse
                                    cx={ex} cy="54" rx="7" ry="7" fill="url(#eye)"
                                    animate={{ scaleY: shut ? 0.1 : sleepy ? 0.5 : 1 }}
                                    transition={{ duration: 0.12 }}
                                    style={{ transformOrigin: `${ex}px 54px` }}
                                />
                                {!shut && !sleepy && (
                                    <>
                                        <circle cx={ex + pupil.x} cy={54 + pupil.y} r="2.6" fill="#15181C" />
                                        <circle cx={ex - 1.4 + pupil.x} cy={52.4 + pupil.y} r="1" fill="#fff" opacity="0.9" />
                                    </>
                                )}
                                {/* sleepy lid */}
                                {sleepy && !shut && (
                                    <line x1={ex - 7} y1="54" x2={ex + 7} y2="54" stroke="#A8893F" strokeWidth="2" strokeLinecap="round" />
                                )}
                            </g>
                        ))}
                    </motion.g>

                    

                    {/* Mouth */}
                    {mouthOpen ? (
                        <g>
                            {/* mouth interior */}
                            <motion.path
                                fill="#1A1015"
                                animate={{
                                    d: 'M 48 70 Q 60 70 72 70 Q 72 84 60 84 Q 48 84 48 70 Z',
                                }}
                                transition={{ duration: 0.2 }}
                            />
                            {/* teeth */}
                            <rect x="49" y="70" width="22" height="4" rx="1.5" fill="#fff" clipPath="url(#mouthClip)" />
                            {/* tongue */}
                            <ellipse cx="60" cy="82" rx="7" ry="4" fill="#E8907A" clipPath="url(#mouthClip)" />
                        </g>
                    ) : (
                        <motion.path
                            fill="none" stroke="#C2C7CD" strokeWidth="2.4" strokeLinecap="round"
                            animate={{
                                d: worried ? 'M 50 78 Q 60 72 70 78'
                                    : covered ? 'M 53 76 L 67 76'
                                    : sleepy ? 'M 54 77 Q 60 79 66 77'
                                    : 'M 52 75 Q 60 79 68 75',
                            }}
                            transition={{ duration: 0.25 }}
                        />
                    )}

                    {/* Hands */}
                    <motion.circle
                        r="12" fill="#2E333A" stroke="#3A4048" strokeWidth="1"
                        initial={false}
                        animate={{ cx: covered ? 46 : 14, cy: covered ? 55 : 108, opacity: covered ? 1 : 0 }}
                        transition={spring}
                    />
                    <motion.circle
                        r="12" fill="#2E333A" stroke="#3A4048" strokeWidth="1"
                        initial={false}
                        animate={{ cx: covered ? 74 : 106, cy: covered ? (peek ? 38 : 55) : 108, opacity: covered ? 1 : 0 }}
                        transition={spring}
                    />

                    {/* Z's when sleepy */}
                    <AnimatePresence>
                        {sleepy && (
                            <motion.text
                                initial={{ opacity: 0, y: 0 }}
                                animate={{ opacity: [0, 1, 0], y: -12 }}
                                exit={{ opacity: 0 }}
                                transition={{ duration: 2, repeat: Infinity }}
                                x="88" y="34" fill="#9BA1A8" fontSize="14" fontWeight="bold"
                            >
                                z
                            </motion.text>
                        )}
                    </AnimatePresence>
                </svg>
            </motion.div>
        </div>
    )
}