/**
 * ChatbotWidget — Interactive demo chatbot widget
 * Design: Warm Showroom — forest green header, cream body, terracotta accents
 * Floats in bottom-right corner, exactly as it would appear on homelegance.com
 */
import { useState, useRef, useEffect, useCallback } from "react";
import { MessageCircle, X, Send, Bot, User } from "lucide-react";
import { motion, AnimatePresence } from "framer-motion";

interface Message {
  id: number;
  text: string;
  sender: "bot" | "user";
  options?: string[];
  quickReplies?: string[];
  metadata?: { quickReplies?: string[]; [k: string]: any };
}

const INITIAL_MESSAGES: Message[] = [
  {
    id: 1,
    text: "Welcome to Homelegance! I'm your virtual assistant. How can I help you today?",
    sender: "bot",
    options: [
      "Browse Products",
      "Find a Dealer",
      "Order Status",
      "Parts & Warranty",
      "Talk to Sales Rep",
    ],
  },
];

const BOT_RESPONSES: Record<string, Message> = {
  "Browse Products": {
    id: 0,
    text: "I'd love to help you find the right furniture! Which category are you interested in?",
    sender: "bot",
    options: ["Bedroom", "Dining", "Seating", "Youth", "Accent Chairs", "Office"],
  },
  "Find a Dealer": {
    id: 0,
    text: "I can help you locate an authorized Homelegance dealer near you. Could you share your zip code or city?",
    sender: "bot",
  },
  "Order Status": {
    id: 0,
    text: "To check your order status, please provide your order number or the email address associated with your account.",
    sender: "bot",
  },
  "Parts & Warranty": {
    id: 0,
    text: "Homelegance offers a limited warranty on all products. I can help you with a parts request or warranty claim. What do you need?",
    sender: "bot",
    options: ["Request Replacement Parts", "File Warranty Claim", "View Warranty Policy"],
  },
  "Talk to Sales Rep": {
    id: 0,
    text: "I'll connect you with a sales representative right away. Please hold for a moment while I transfer you to our team.",
    sender: "bot",
  },
  Bedroom: {
    id: 0,
    text: "Great choice! Our bedroom collections include the popular Lofton Collection with modern elegance, and the new Sloane Collection for youth rooms. Would you like to see best sellers or new arrivals?",
    sender: "bot",
    options: ["Best Sellers", "New Arrivals", "View All Bedroom"],
  },
  Dining: {
    id: 0,
    text: "Our dining collections range from traditional to contemporary. The Isla Collection offers versatile modular options. Would you like to explore?",
    sender: "bot",
    options: ["Best Sellers", "New Arrivals", "View All Dining"],
  },
  Seating: {
    id: 0,
    text: "From sofas to accent chairs, we have a wide selection. Our Isla modular seating collection is very popular with dealers. What are you looking for?",
    sender: "bot",
    options: ["Sofas & Sectionals", "Accent Chairs", "Recliners"],
  },
  default: {
    id: 0,
    text: "Thank you for your message! Let me look into that for you. Is there anything else I can help with?",
    sender: "bot",
    options: ["Browse Products", "Find a Dealer", "Talk to Sales Rep"],
  },
};

export default function ChatbotWidget() {
  const [isOpen, setIsOpen] = useState(false);
  const [messages, setMessages] = useState<Message[]>(INITIAL_MESSAGES);
  const [inputValue, setInputValue] = useState("");
  const [isTyping, setIsTyping] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const scrollContainerRef = useRef<HTMLDivElement>(null);
  const isNearBottomRef = useRef(true);
  const inputRef = useRef<HTMLInputElement>(null);
  let nextId = useRef(2);

  useEffect(() => {
    if (isNearBottomRef.current) {
      messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
    }
  }, [messages, isTyping]);

  const handleScroll = useCallback(() => {
    const el = scrollContainerRef.current;
    if (!el) return;
    isNearBottomRef.current = el.scrollHeight - el.scrollTop - el.clientHeight < 100;
  }, []);

  useEffect(() => {
    if (isOpen) {
      setTimeout(() => inputRef.current?.focus(), 300);
    }
  }, [isOpen]);

  const addBotResponse = (userText: string) => {
    setIsTyping(true);
    setTimeout(() => {
      const response = BOT_RESPONSES[userText] || BOT_RESPONSES["default"];
      const botMsg: Message = {
        ...response,
        id: nextId.current++,
      };
      setMessages((prev) => [...prev, botMsg]);
      setIsTyping(false);
    }, 800 + Math.random() * 600);
  };

  const handleSend = (text?: string) => {
    const messageText = text || inputValue.trim();
    if (!messageText) return;

    isNearBottomRef.current = true;

    const userMsg: Message = {
      id: nextId.current++,
      text: messageText,
      sender: "user",
    };
    setMessages((prev) => [...prev, userMsg]);
    setInputValue("");
    addBotResponse(messageText);
  };

  const handleKeyDown = (e: React.KeyboardEvent) => {
    if (e.key === "Enter") {
      e.preventDefault();
      handleSend();
    }
  };

  return (
    <>
      {/* Floating trigger button */}
      <AnimatePresence>
        {!isOpen && (
          <motion.button
            initial={{ scale: 0, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            exit={{ scale: 0, opacity: 0 }}
            whileHover={{ scale: 1.08 }}
            whileTap={{ scale: 0.95 }}
            onClick={() => setIsOpen(true)}
            className="fixed bottom-6 right-6 z-50 w-16 h-16 rounded-full flex items-center justify-center shadow-lg"
            style={{
              background: "linear-gradient(135deg, #14532D 0%, #1a6b3a 100%)",
              boxShadow: "0 8px 32px rgba(20, 83, 45, 0.35), 0 2px 8px rgba(0,0,0,0.1)",
            }}
          >
            <MessageCircle className="w-7 h-7 text-white" />
            {/* Pulse ring */}
            <span className="absolute inset-0 rounded-full animate-ping opacity-20" style={{ background: "#14532D" }} />
          </motion.button>
        )}
      </AnimatePresence>

      {/* Chat window */}
      <AnimatePresence>
        {isOpen && (
          <motion.div
            initial={{ opacity: 0, y: 20, scale: 0.95 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={{ opacity: 0, y: 20, scale: 0.95 }}
            transition={{ type: "spring", damping: 25, stiffness: 300 }}
            className="fixed bottom-6 right-6 z-50 w-[380px] max-w-[calc(100vw-2rem)] rounded-2xl overflow-hidden flex flex-col"
            style={{
              height: "520px",
              boxShadow: "0 20px 60px rgba(20, 83, 45, 0.2), 0 4px 16px rgba(0,0,0,0.08)",
            }}
          >
            {/* Header */}
            <div
              className="px-5 py-4 flex items-center justify-between shrink-0"
              style={{
                background: "linear-gradient(135deg, #14532D 0%, #1a6b3a 100%)",
              }}
            >
              <div className="flex items-center gap-3">
                <div className="w-10 h-10 rounded-full bg-white/15 flex items-center justify-center">
                  <Bot className="w-5 h-5 text-white" />
                </div>
                <div>
                  <h3 className="text-white font-semibold text-sm" style={{ fontFamily: "'Source Sans 3', sans-serif" }}>
                    Homelegance Assistant
                  </h3>
                  <div className="flex items-center gap-1.5">
                    <span className="w-2 h-2 rounded-full bg-green-300 animate-pulse" />
                    <span className="text-green-200 text-xs">Online</span>
                  </div>
                </div>
              </div>
              <button
                onClick={() => setIsOpen(false)}
                className="w-8 h-8 rounded-full bg-white/10 hover:bg-white/20 flex items-center justify-center transition-colors"
              >
                <X className="w-4 h-4 text-white" />
              </button>
            </div>

            {/* Messages area */}
            <div
              ref={scrollContainerRef}
              onScroll={handleScroll}
              className="flex-1 overflow-y-auto px-4 py-4 space-y-4"
              style={{ background: "#FFFBEB" }}
            >
              {messages.map((msg) => (
                <motion.div
                  key={msg.id}
                  initial={{ opacity: 0, y: 8 }}
                  animate={{ opacity: 1, y: 0 }}
                  transition={{ duration: 0.3 }}
                  className={`flex gap-2 ${msg.sender === "user" ? "justify-end" : "justify-start"}`}
                >
                  {msg.sender === "bot" && (
                    <div className="w-7 h-7 rounded-full shrink-0 flex items-center justify-center mt-1" style={{ background: "#14532D" }}>
                      <Bot className="w-3.5 h-3.5 text-white" />
                    </div>
                  )}
                  <div className={`max-w-[75%] ${msg.sender === "user" ? "" : ""}`}>
                    <div
                      className="px-4 py-2.5 rounded-2xl text-sm leading-relaxed"
                      style={
                        msg.sender === "user"
                          ? {
                              background: "#14532D",
                              color: "#fff",
                              borderBottomRightRadius: "6px",
                              fontFamily: "'Source Sans 3', sans-serif",
                            }
                          : {
                              background: "#fff",
                              color: "#292524",
                              borderBottomLeftRadius: "6px",
                              boxShadow: "0 1px 4px rgba(120, 113, 108, 0.1)",
                              fontFamily: "'Source Sans 3', sans-serif",
                            }
                      }
                    >
                      {msg.text}
                    </div>
                    {(() => {
                      const quickReplies = msg.options
                        ?? msg.quickReplies
                        ?? msg.metadata?.quickReplies;
                      if (!quickReplies || quickReplies.length === 0) return null;
                      return (
                      <div className="flex flex-wrap gap-1.5 mt-2">
                        {quickReplies.map((opt) => (
                          <button
                            key={opt}
                            onClick={() => handleSend(opt)}
                            className="px-3 py-1.5 text-xs rounded-full border transition-all hover:shadow-sm"
                            style={{
                              borderColor: "#C2410C",
                              color: "#C2410C",
                              background: "rgba(194, 65, 12, 0.05)",
                              fontFamily: "'Source Sans 3', sans-serif",
                              fontWeight: 500,
                            }}
                            onMouseEnter={(e) => {
                              e.currentTarget.style.background = "#C2410C";
                              e.currentTarget.style.color = "#fff";
                            }}
                            onMouseLeave={(e) => {
                              e.currentTarget.style.background = "rgba(194, 65, 12, 0.05)";
                              e.currentTarget.style.color = "#C2410C";
                            }}
                          >
                            {opt}
                          </button>
                        ))}
                      </div>
                      );
                    })()}
                  </div>
                  {msg.sender === "user" && (
                    <div className="w-7 h-7 rounded-full shrink-0 flex items-center justify-center mt-1" style={{ background: "#78716C" }}>
                      <User className="w-3.5 h-3.5 text-white" />
                    </div>
                  )}
                </motion.div>
              ))}

              {/* Typing indicator */}
              {isTyping && (
                <motion.div
                  initial={{ opacity: 0 }}
                  animate={{ opacity: 1 }}
                  className="flex gap-2 items-start"
                >
                  <div className="w-7 h-7 rounded-full shrink-0 flex items-center justify-center" style={{ background: "#14532D" }}>
                    <Bot className="w-3.5 h-3.5 text-white" />
                  </div>
                  <div className="px-4 py-3 rounded-2xl bg-white" style={{ borderBottomLeftRadius: "6px", boxShadow: "0 1px 4px rgba(120, 113, 108, 0.1)" }}>
                    <div className="flex gap-1">
                      <span className="w-2 h-2 rounded-full bg-stone-400 animate-bounce" style={{ animationDelay: "0ms" }} />
                      <span className="w-2 h-2 rounded-full bg-stone-400 animate-bounce" style={{ animationDelay: "150ms" }} />
                      <span className="w-2 h-2 rounded-full bg-stone-400 animate-bounce" style={{ animationDelay: "300ms" }} />
                    </div>
                  </div>
                </motion.div>
              )}
              <div ref={messagesEndRef} />
            </div>

            {/* Input area */}
            <div className="px-4 py-3 border-t shrink-0" style={{ background: "#fff", borderColor: "#e7e0d5" }}>
              <div className="flex items-center gap-2">
                <input
                  ref={inputRef}
                  type="text"
                  value={inputValue}
                  onChange={(e) => setInputValue(e.target.value)}
                  onKeyDown={handleKeyDown}
                  placeholder="Type your message..."
                  className="flex-1 px-4 py-2.5 rounded-full text-sm border-none outline-none"
                  style={{
                    background: "#f5f0e8",
                    color: "#292524",
                    fontFamily: "'Source Sans 3', sans-serif",
                  }}
                />
                <button
                  onClick={() => handleSend()}
                  disabled={!inputValue.trim()}
                  className="w-10 h-10 rounded-full flex items-center justify-center transition-all disabled:opacity-40"
                  style={{
                    background: inputValue.trim() ? "#14532D" : "#d6d3d1",
                  }}
                >
                  <Send className="w-4 h-4 text-white" />
                </button>
              </div>
              <p className="text-center text-[10px] mt-2" style={{ color: "#a8a29e", fontFamily: "'Source Sans 3', sans-serif" }}>
                Powered by Homelegance AI
              </p>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  );
}
