/* ChatBot.jsx — Simple rule-based chatbot (no API calls needed) */
const { useState, useRef, useEffect, createElement: e } = React;

/* Knowledge base: questions → answers */
const KNOWLEDGE_BASE = [
  {
    keywords: ['what', 'is'],
    answer: 'Yottasecure provides contextual vulnerability intelligence. We turn raw CVE data and alerts into a ranked, actionable plan of attack—giving your team the context they need to prioritize fixes efficiently.'
  },
  {
    keywords: ['how', 'does', 'work'],
    answer: 'Our context engine maps vulnerabilities to your specific network assets in real-time. Instead of drowning in alerts, you get prioritized intelligence that tells you what matters most for your environment.'
  },
  {
    keywords: ['demo', 'walkthrough', 'book'],
    answer: 'We would love to show you how Yottasecure works. Check out our contact page to book a demo or walkthrough tailored to your network.'
  },
  {
    keywords: ['pricing', 'cost', 'price'],
    answer: 'For pricing information, please contact our sales team. Every organization has unique needs, so we customize our offering. Reach out via the contact page!'
  },
  {
    keywords: ['rsac', 'conference', 'event'],
    answer: 'Yottasecure was featured at RSAC. Check out our RSAC page for more details about our research and insights.'
  },
  {
    keywords: ['vulnerability', 'cve', 'alert', 'risk'],
    answer: 'Yottasecure transforms vulnerability data and alerts into context-rich intelligence. We help you understand which vulnerabilities pose real risk to your assets and how to prioritize remediation.'
  },
  {
    keywords: ['team', 'about'],
    answer: 'Learn more about the Yottasecure team on our About page. We are security experts passionate about making vulnerability intelligence actionable.'
  },
  {
    keywords: ['contact', 'email', 'reach'],
    answer: 'You can reach us through our Contact page. We would love to hear from you!'
  },
  {
    keywords: ['hello', 'hi', 'hey'],
    answer: 'Hey there! 👋 I am the Yottasecure chatbot. Ask me about our platform, how it works, or how to get in touch. What can I help you with?'
  }
];

/* Score a user message against knowledge base */
function findBestMatch(userMessage) {
  const msg = userMessage.toLowerCase();
  let bestMatch = null;
  let bestScore = 0;

  for (const qa of KNOWLEDGE_BASE) {
    const matchedKeywords = qa.keywords.filter(kw => msg.includes(kw));
    const score = matchedKeywords.length;
    if (score > bestScore) {
      bestScore = score;
      bestMatch = qa;
    }
  }

  if (bestMatch) return bestMatch.answer;
  return "I'm not sure about that. Feel free to explore our site or reach out on the Contact page!";
}

function ChatBot() {
  const { Icon } = window;
  const [open, setOpen] = useState(false);
  const [messages, setMessages] = useState([
    { role: 'bot', text: 'Hi! 👋 Ask me about Yottasecure or how we can help.' }
  ]);
  const [input, setInput] = useState('');
  const messagesEndRef = useRef(null);

  /* Auto-scroll to latest message */
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  }, [messages]);

  const handleSend = () => {
    if (!input.trim()) return;

    const userMsg = input.trim();
    setInput('');

    /* Add user message */
    setMessages(prev => [...prev, { role: 'user', text: userMsg }]);

    /* Get bot response (small delay for feel) */
    setTimeout(() => {
      const botResponse = findBestMatch(userMsg);
      setMessages(prev => [...prev, { role: 'bot', text: botResponse }]);
    }, 300);
  };

  const handleKeyPress = (event) => {
    if (event.key === 'Enter' && !event.shiftKey) {
      event.preventDefault();
      handleSend();
    }
  };

  return e('div', { className: 'ys-chatbot-container', style: { position: 'fixed', bottom: 20, right: 20, zIndex: 999 } },
    /* Chat bubble icon */
    !open && e('button', {
      className: 'ys-chatbot-fab',
      onClick: () => setOpen(true),
      title: 'Open chat'
    },
      e(Icon, { name: 'message-circle', size: 24 })
    ),

    /* Chat window */
    open && e('div', { className: 'ys-chatbot-window' },
      /* Header */
      e('div', { className: 'ys-chatbot-header' },
        e('div', null, 'Yottasecure Assistant'),
        e('button', {
          className: 'ys-chatbot-close',
          onClick: () => setOpen(false),
          title: 'Close'
        }, '✕')
      ),

      /* Messages */
      e('div', { className: 'ys-chatbot-messages' },
        messages.map((msg, i) =>
          e('div', {
            key: i,
            className: `ys-chatbot-message ys-chatbot-${msg.role}`
          },
            e('div', { className: 'ys-chatbot-text' }, msg.text)
          )
        ),
        e('div', { ref: messagesEndRef })
      ),

      /* Input */
      e('div', { className: 'ys-chatbot-input-area' },
        e('input', {
          type: 'text',
          className: 'ys-chatbot-input',
          placeholder: 'Ask me anything...',
          value: input,
          onChange: (e) => setInput(e.target.value),
          onKeyPress: handleKeyPress
        }),
        e('button', {
          className: 'ys-chatbot-send',
          onClick: handleSend,
          disabled: !input.trim(),
          title: 'Send'
        }, '→')
      )
    )
  );
}

window.ChatBot = ChatBot;
