/* global React, SITE, IconX */

const IconChat = ({ size = 24 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
    <path d="M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z"/>
  </svg>
);

const QUICK_REPLIES = [
  "Pricing Plans",
  "Rank Predictor",
  "How Guidance Works",
  "Talk to Support"
];

const Chatbot = () => {
  const [isOpen, setIsOpen] = React.useState(false);
  const [isTyping, setIsTyping] = React.useState(false);
  const [messages, setMessages] = React.useState([
    { sender: 'bot', text: 'Hi there! 👋 I am the CounselExpert Assistant. How can I help you regarding JEE or BITSAT admissions today?' }
  ]);
  const [input, setInput] = React.useState('');
  const messagesEndRef = React.useRef(null);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  React.useEffect(() => {
    if (isOpen) scrollToBottom();
  }, [messages, isOpen, isTyping]);

  const getBotResponse = (userText) => {
    const lower = userText.toLowerCase();

    // 1. Contextual Intents via Regex
    if (lower.match(/\b(hi|hello|hey|greetings|morning|evening|namaste)\b/)) {
      return "Hello! How can we help you secure your dream college today?";
    }
    if (lower.match(/\b(price|pricing|cost|fee|plans|pay|purchase|buy)\b/)) {
      const plans = SITE?.plans ? Object.values(SITE.plans).map(p => `${p.name} (₹${p.price})`).join(', ') : 'our plans on the site';
      return `Our counseling packages are: ${plans}. You can read the detailed breakdown in the Pricing section of our website!`;
    }
    if (lower.match(/\b(contact|phone|whatsapp|email|support|human|talk|speak|help)\b/)) {
      const wa = SITE?.footer?.cols?.[2]?.links?.find(l => l.label === 'WhatsApp')?.href || 'our site';
      return `For human support or follow-up questions, message us directly on WhatsApp: ${wa} or email counsel.expert.1@gmail.com. We usually reply within a few hours.`;
    }
    if (lower.match(/\b(predictor|rank|college predictor|marks|score)\b/)) {
      return `We have a highly accurate, 100% free Rank Predictor tool! It uses JoSAA historical data to suggest colleges based on your rank. Head to the Predictor tab or visit #/predictor to try it out.`;
    }
    if (lower.match(/\b(guidance|counsel|counselling|mentor|process|how it works)\b/)) {
      return `Our counselling is a 1-on-1 personalized process. IIT/BITS alumni mentors analyse your rank and guide you through preference filling step-by-step over a video call. Click "Get guidance" at the top to start the wizard!`;
    }

    // 2. Dynamic FAQ Keyword Sub-Matching
    if (SITE && SITE.faq) {
       for (let item of SITE.faq) {
           const keywords = item.q.toLowerCase().replace(/[^\w\s]/g, '').split(' ').filter(w => w.length > 3);
           const match = keywords.some(w => lower.includes(w));
           if (match && lower.length > 3) {
               return `From our FAQ: ${item.a}`;
           }
       }
    }

    // 3. Fallback Intent
    return "I'm still learning! You can ask me about our pricing, the rank predictor, how our counselling works, or ask to talk to human support.";
  };

  const handleSend = (text) => {
    const userText = typeof text === 'string' ? text.trim() : input.trim();
    if (!userText) return;

    // Add user message
    setMessages(prev => [...prev, { sender: 'user', text: userText }]);
    
    // Clear input box
    if (typeof text !== 'string') setInput('');

    // Simulate typing indicator
    setIsTyping(true);

    // Dynamic processing delay based on string length to simulate human reading
    const delay = 800 + Math.random() * 800; // 0.8s to 1.6s delay
    setTimeout(() => {
      const botResponse = getBotResponse(userText);
      setIsTyping(false);
      setMessages(prev => [...prev, { sender: 'bot', text: botResponse }]);
    }, delay); 
  };

  return (
    <>
      {/* Floating CTA Button */}
      <button
        onClick={() => setIsOpen(true)}
        style={{
          position: 'fixed', bottom: '24px', right: '24px', width: '60px', height: '60px',
          borderRadius: '30px', backgroundColor: 'var(--color-primary)', color: '#fff',
          border: 'none', boxShadow: '0 6px 16px rgba(0,0,0,0.2)', display: isOpen ? 'none' : 'flex',
          alignItems: 'center', justifyContent: 'center', cursor: 'pointer', zIndex: 9999,
          transition: 'transform 0.25s cubic-bezier(0.175, 0.885, 0.32, 1.275)',
        }}
        onMouseEnter={e => e.currentTarget.style.transform = 'scale(1.1) translateY(-4px)'}
        onMouseLeave={e => e.currentTarget.style.transform = 'scale(1) translateY(0px)'}
        title="Chat with CounselExpert"
      >
        <IconChat size={30} />
      </button>

      {/* Main Chat Window */}
      {isOpen && (
        <div style={{
          position: 'fixed', bottom: '24px', right: '24px', width: '380px',
          maxWidth: 'calc(100vw - 48px)', height: '580px', backgroundColor: 'var(--color-surface)',
          borderRadius: '20px', boxShadow: '0 12px 40px rgba(0,0,0,0.18)', display: 'flex',
          flexDirection: 'column', zIndex: 10000, border: '1px solid var(--color-hairline)',
          overflow: 'hidden', animation: 'slideUp 0.3s ease-out'
        }}>
          <style>{`
            @keyframes slideUp {
              from { opacity: 0; transform: translateY(20px) scale(0.98); }
              to { opacity: 1; transform: translateY(0) scale(1); }
            }
            .hide-scroll::-webkit-scrollbar { display: none; }
          `}</style>
          
          {/* Header */}
          <div style={{
            padding: '18px 20px', backgroundColor: 'var(--color-primary)', color: '#fff',
            display: 'flex', justifyContent: 'space-between', alignItems: 'center',
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: '10px' }}>
               <div style={{
                 backgroundColor: 'rgba(255,255,255,0.2)', borderRadius: '50%', padding: '6px',
                 display: 'flex', alignItems: 'center', justifyContent: 'center'
               }}>
                 <IconChat size={18} />
               </div>
               <div style={{ display: 'flex', flexDirection: 'column' }}>
                 <span style={{ fontWeight: 600, fontFamily: 'var(--font-sans)', fontSize: 16, lineHeight: 1.2 }}>CounselExpert bot</span>
                 <span style={{ fontSize: 12, opacity: 0.85 }}>Typically replies instantly</span>
               </div>
            </div>
            <button
              onClick={() => setIsOpen(false)}
              style={{ background: 'transparent', border: 'none', color: '#fff', cursor: 'pointer', display: 'flex', padding: '4px', opacity: 0.8, transition: 'opacity 0.2s' }}
              onMouseEnter={e => e.currentTarget.style.opacity = '1'}
              onMouseLeave={e => e.currentTarget.style.opacity = '0.8'}
            >
              <IconX size={22} />
            </button>
          </div>

          {/* Messages Area */}
          <div style={{
            flex: 1, overflowY: 'auto', padding: '20px', display: 'flex', flexDirection: 'column',
            gap: '14px', background: 'var(--color-canvas)', scrollBehavior: 'smooth'
          }}>
            <div style={{ textAlign: 'center', fontSize: 11, color: 'var(--color-body)', marginBottom: 12, fontFamily: 'var(--font-sans)', textTransform: 'uppercase', letterSpacing: '0.5px' }}>
              FEEL FREE TO ASK ANYTHING!
            </div>

            {messages.map((m, i) => (
              <div key={i} style={{
                alignSelf: m.sender === 'user' ? 'flex-end' : 'flex-start',
                backgroundColor: m.sender === 'user' ? 'var(--color-primary)' : 'var(--color-surface-soft)',
                color: m.sender === 'user' ? '#fff' : 'var(--color-ink)',
                padding: '12px 16px', borderRadius: '16px',
                borderBottomRightRadius: m.sender === 'user' ? '4px' : '16px',
                borderBottomLeftRadius: m.sender === 'bot' ? '4px' : '16px',
                maxWidth: '85%', fontSize: '14px', fontFamily: 'var(--font-sans)', lineHeight: 1.5,
                boxShadow: '0 2px 5px rgba(0,0,0,0.04)'
              }}>
                {m.text}
              </div>
            ))}
            
            {/* Typing Indicator */}
            {isTyping && (
              <div style={{
                alignSelf: 'flex-start', backgroundColor: 'var(--color-surface-soft)', color: 'var(--color-body)',
                padding: '12px 18px', borderRadius: '16px', borderBottomLeftRadius: '4px',
                display: 'flex', gap: '4px', alignItems: 'center'
              }}>
                 <span style={{ animation: 'blink 1.4s infinite .2s', display: 'inline-block', width: '4px', height: '4px', backgroundColor: 'currentColor', borderRadius: '50%' }}></span>
                 <span style={{ animation: 'blink 1.4s infinite .4s', display: 'inline-block', width: '4px', height: '4px', backgroundColor: 'currentColor', borderRadius: '50%' }}></span>
                 <span style={{ animation: 'blink 1.4s infinite .6s', display: 'inline-block', width: '4px', height: '4px', backgroundColor: 'currentColor', borderRadius: '50%' }}></span>
                 <style>{`@keyframes blink { 0% { opacity: 0.2; } 20% { opacity: 1; } 100% { opacity: 0.2; } }`}</style>
              </div>
            )}
            <div ref={messagesEndRef} />
          </div>

          {/* Action Chips (Quick Replies) */}
          {!isTyping && (
            <div style={{
              background: 'var(--color-canvas)', borderTop: '1px solid var(--color-hairline)',
              padding: '12px 16px 8px 16px', msOverflowStyle: 'none', scrollbarWidth: 'none'
            }}>
              <div className="hide-scroll" style={{ display: 'flex', gap: '8px', overflowX: 'auto', paddingBottom: '4px' }}>
                {QUICK_REPLIES.map((qr, idx) => (
                  <button
                    key={idx}
                    onClick={() => handleSend(qr)}
                    style={{
                      whiteSpace: 'nowrap', padding: '6px 14px', borderRadius: '20px',
                      background: 'var(--color-surface-soft)', border: '1px solid var(--color-hairline)',
                      color: 'var(--color-ink)', fontSize: '13px', fontFamily: 'var(--font-sans)',
                      cursor: 'pointer', transition: 'all 0.2s ease', fontWeight: 500
                    }}
                    onMouseEnter={e => { e.currentTarget.style.background = 'var(--color-primary-soft)'; e.currentTarget.style.borderColor = 'var(--color-primary)'; e.currentTarget.style.color = 'var(--color-primary-active)'; }}
                    onMouseLeave={e => { e.currentTarget.style.background = 'var(--color-surface-soft)'; e.currentTarget.style.borderColor = 'var(--color-hairline)'; e.currentTarget.style.color = 'var(--color-ink)'; }}
                  >
                    {qr}
                  </button>
                ))}
              </div>
            </div>
          )}

          {/* Input Interface */}
          <div style={{
            padding: '14px 16px', background: 'var(--color-surface)', display: 'flex', gap: '10px',
            borderTop: 'none', alignItems: 'center'
          }}>
            <input
              type="text" value={input} onChange={e => setInput(e.target.value)}
              onKeyDown={e => e.key === 'Enter' && handleSend()}
              placeholder="Ask me anything..."
              disabled={isTyping}
              style={{
                flex: 1, padding: '12px 16px', border: '1px solid var(--color-hairline)',
                borderRadius: '24px', fontSize: '15px', fontFamily: 'var(--font-sans)',
                outline: 'none', backgroundColor: 'var(--color-canvas)', color: 'var(--color-ink)',
                transition: 'border-color 0.2s', opacity: isTyping ? 0.6 : 1
              }}
              onFocus={e => e.currentTarget.style.borderColor = 'var(--color-primary)'}
              onBlur={e => e.currentTarget.style.borderColor = 'var(--color-hairline)'}
            />
            <button
              onClick={handleSend}
              disabled={!input.trim() || isTyping}
              style={{
                backgroundColor: input.trim() && !isTyping ? 'var(--color-primary)' : 'var(--color-surface-soft)',
                color: input.trim() && !isTyping ? '#fff' : 'var(--color-body)', border: 'none',
                borderRadius: '50%', width: '44px', height: '44px', display: 'flex', alignItems: 'center',
                justifyContent: 'center', cursor: input.trim() && !isTyping ? 'pointer' : 'not-allowed',
                transition: 'background-color 0.2s, transform 0.1s', transform: input.trim() && !isTyping ? 'scale(1.05)' : 'scale(1)'
              }}
            >
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                <line x1="22" y1="2" x2="11" y2="13"></line>
                <polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
              </svg>
            </button>
          </div>
        </div>
      )}
    </>
  );
};

window.Chatbot = Chatbot;
