'use client'

import { useEffect } from 'react'
import { AnimatePresence, motion } from 'framer-motion'
import { MessageSquare, X } from 'lucide-react'
import { useDaliBot } from '@/hooks/useDaliBot'
import { DaliBotPanel } from './DaliBotPanel'

export function DaliBotLauncher() {
  const { isOpen, open, close, toggle, messages, isLoading, sendMessage, reset } = useDaliBot()

  // Listen for custom open events from other components (e.g., CTASection)
  useEffect(() => {
    const handler = () => open()
    window.addEventListener('dalibot:open', handler)
    return () => window.removeEventListener('dalibot:open', handler)
  }, [open])

  return (
    <div className="fixed bottom-6 right-6 z-50 flex flex-col items-end gap-3">
      {/* Panel */}
      <AnimatePresence>
        {isOpen && (
          <DaliBotPanel
            messages={messages}
            isLoading={isLoading}
            onSend={sendMessage}
            onClose={close}
            onReset={reset}
          />
        )}
      </AnimatePresence>

      {/* Launcher button */}
      <motion.button
        onClick={toggle}
        className="w-14 h-14 rounded-2xl flex items-center justify-center shadow-lg relative"
        style={{
          background: 'var(--dt-gradient-accent)',
          boxShadow: 'var(--dt-shadow-glow), 0 8px 24px rgba(0,0,0,0.3)',
        }}
        whileHover={{ scale: 1.06 }}
        whileTap={{ scale: 0.95 }}
        transition={{ type: 'spring', stiffness: 400, damping: 25 }}
        aria-label={isOpen ? 'Close DaliBot' : 'Open DaliBot'}
      >
        <AnimatePresence mode="wait">
          {isOpen ? (
            <motion.div
              key="close"
              initial={{ rotate: -90, opacity: 0 }}
              animate={{ rotate: 0, opacity: 1 }}
              exit={{ rotate: 90, opacity: 0 }}
              transition={{ duration: 0.2 }}
            >
              <X className="w-6 h-6 text-white" />
            </motion.div>
          ) : (
            <motion.div
              key="open"
              initial={{ rotate: 90, opacity: 0 }}
              animate={{ rotate: 0, opacity: 1 }}
              exit={{ rotate: -90, opacity: 0 }}
              transition={{ duration: 0.2 }}
            >
              <MessageSquare className="w-6 h-6 text-white" />
            </motion.div>
          )}
        </AnimatePresence>

        {/* Unread indicator */}
        {!isOpen && (
          <motion.div
            className="absolute -top-1 -right-1 w-3.5 h-3.5 rounded-full bg-green-400 border-2"
            style={{ borderColor: 'var(--dt-bg-base)' }}
            animate={{ scale: [1, 1.2, 1] }}
            transition={{ duration: 2, repeat: Infinity, repeatDelay: 3 }}
          />
        )}
      </motion.button>
    </div>
  )
}
