import { useState, useRef, useEffect } from "react"
import { X, Send, Bot, User } from "lucide-react"

const FAQ_RESPONSES: Record<string, string> = {
  "delivery": "All orders are delivered instantly via WhatsApp or email within 2-10 minutes. Our automated system ensures the fastest delivery possible.",
  "refund": "We offer a 24-hour money-back guarantee on all purchases. If you face any issue, contact our support team immediately for a full refund.",
  "payment": "We accept UPI (Google Pay, PhonePe, Paytm), PayPal for international orders, and Cryptocurrency (Bitcoin, Ethereum, USDT).",
  "genuine": "All our licenses are 100% genuine and sourced through official channels. We have served 10,000+ customers since 2023 with a 99.8% success rate.",
  "support": "Our support team is available 24/7 via WhatsApp at +91 7038146526 or Telegram @mfatool. Average response time is under 5 minutes.",
  "discount": "You can use coupon code HERO20 for 20% OFF on orders above $10. We also run flash sales regularly with up to 40% discounts.",
  "contact": "You can reach us via WhatsApp at +91 7038146526, Telegram @mfatool, or email through our Contact page.",
  "hello": "Hello! Welcome to Subscription Hero. How can I help you today? Ask me about our products, pricing, delivery, or support.",
  "hi": "Hi there! I'm your AI assistant for Subscription Hero. What can I help you with today?",
}

function getResponse(input: string): string {
  const lower = input.toLowerCase()
  for (const [key, value] of Object.entries(FAQ_RESPONSES)) {
    if (lower.includes(key)) return value
  }
  if (lower.includes("price") || lower.includes("cost")) return "Our prices are up to 96% off retail. ChatGPT Plus starts at $19, Canva Pro at just $2, Netflix 4K at $7. Check our Shop page for all pricing."
  if (lower.includes("netflix")) return "Netflix 4K Premium subscriptions start at $7 (72% off). We offer 1-month, 3-month, 6-month, and 12-month plans. All include private profile access."
  if (lower.includes("chatgpt") || lower.includes("gpt")) return "ChatGPT Plus starts at $19/month (49% off). We also offer ChatGPT Business at $31 and Team plans at $50. All include GPT-4 access."
  if (lower.includes("canva")) return "Canva Pro starts at just $2 for 1 year (96% off!) or $4 for lifetime access. Includes all premium templates, background remover, and brand kit."
  if (lower.includes("spotify")) return "Spotify Premium starts at $3 for 1 year (85% off). Includes ad-free listening, offline downloads, and high-quality audio."
  if (lower.includes("vpn")) return "We offer NordVPN from $7, ExpressVPN, Surfshark, and more. All provide secure, anonymous browsing with global server access."
  return "Great question! For the most accurate answer, please contact our 24/7 support via WhatsApp at +91 7038146526 or browse our Shop page. You can also ask me about delivery, refunds, or specific products!"
}

export function AIChatbot() {
  const [open, setOpen] = useState(false)
  const [messages, setMessages] = useState<{role: string; text: string}[]>([
    { role: "bot", text: "Hey there! I'm your Subscription Hero assistant. Ask me about products, pricing, delivery, or support!" }
  ])
  const [input, setInput] = useState("")
  const [typing, setTyping] = useState(false)
  const scrollRef = useRef<HTMLDivElement>(null)

  useEffect(() => { scrollRef.current?.scrollTo(0, scrollRef.current.scrollHeight) }, [messages])

  const handleSend = () => {
    if (!input.trim()) return
    const userMsg = input.trim()
    setMessages(prev => [...prev, { role: "user", text: userMsg }])
    setInput("")
    setTyping(true)
    setTimeout(() => {
      setMessages(prev => [...prev, { role: "bot", text: getResponse(userMsg) }])
      setTyping(false)
    }, 800)
  }

  return (
    <>
      <button onClick={() => setOpen(!open)}
        className="fixed bottom-24 right-6 z-[55] w-12 h-12 bg-gradient-to-br from-[#f97316] to-[#ea580c] rounded-full flex items-center justify-center shadow-lg hover:scale-110 transition-transform duration-300">
        {open ? <X className="w-5 h-5 text-white" /> : <Bot className="w-5 h-5 text-white" />}
      </button>
      {open && (
        <div className="fixed bottom-40 right-6 z-[55] w-80 h-[28rem] glass-card flex flex-col overflow-hidden animate-fade-in">
          <div className="p-3 bg-gradient-to-r from-[#f97316] to-[#ea580c] flex items-center gap-2">
            <Bot className="w-5 h-5 text-white" />
            <span className="font-semibold text-sm">Subscription Hero AI</span>
          </div>
          <div ref={scrollRef} className="flex-1 overflow-y-auto p-3 space-y-3">
            {messages.map((m, i) => (
              <div key={i} className={`flex gap-2 ${m.role === "user" ? "flex-row-reverse" : ""}`}>
                <div className={`w-7 h-7 rounded-full flex items-center justify-center flex-shrink-0 ${m.role === "user" ? "bg-white/10" : "bg-[#f97316]/20"}`}>
                  {m.role === "user" ? <User className="w-3.5 h-3.5" /> : <Bot className="w-3.5 h-3.5 text-[#f97316]" />}
                </div>
                <div className={`text-sm p-2.5 rounded-xl max-w-[85%] ${m.role === "user" ? "bg-[#f97316] text-white" : "bg-white/5 text-slate-300"}`}>
                  {m.text}
                </div>
              </div>
            ))}
            {typing && <div className="flex gap-2"><div className="w-7 h-7 rounded-full bg-[#f97316]/20 flex items-center justify-center"><Bot className="w-3.5 h-3.5 text-[#f97316]" /></div><div className="text-sm p-2.5 bg-white/5 rounded-xl text-slate-400 animate-pulse">Typing...</div></div>}
          </div>
          <div className="p-3 border-t border-white/5 flex gap-2">
            <input value={input} onChange={e => setInput(e.target.value)} onKeyDown={e => e.key === "Enter" && handleSend()}
              placeholder="Ask about products..." className="flex-1 px-3 py-2 rounded-lg bg-white/5 border border-white/10 text-sm focus:outline-none focus:border-[#f97316] transition-colors" />
            <button onClick={handleSend} className="p-2 bg-[#f97316] rounded-lg hover:bg-[#ea580c] transition-colors"><Send className="w-4 h-4 text-white" /></button>
          </div>
        </div>
      )}
    </>
  )
}
