// Chatbot, DeepSeek API powered, smart & CTA-focused
const { useState: useCbState, useEffect: useCbEffect, useRef: useCbRef } = React;

const DEEPSEEK_API_KEY = 'sk-c7ae5ce9cd064028a09892a06345cb36';
const CAL_LINK = 'https://cal.com/ratan-kumar/ai-automation-startegy-call-with-ratan-quantaeight';

const SYSTEM_PROMPT = `You are the Quantaeight AI, a sharp, concise assistant for Quantaeight, an AI automation agency that builds production-grade AI agents and systems for B2B businesses.

ABOUT QUANTAEIGHT:
- Builds custom production AI agents, integrations, automation, and AI software for B2B
- NOT a no-code shop, real agents with memory, tools, evals, custom code
- Verticals: Med Spas, CPA/Accounting, Real Estate, Law Firms, Retail/E-commerce, Logistics, Staffing, Healthcare, Insurance, Property Management, B2B SaaS
- Geographies: US, UK, UAE, Saudi Arabia, Qatar, Kuwait
- Founded by Ratan Kumar

PRICING:
- Starter: $2,000–$3,000 fixed, 2-week sprint, single automation
- Growth: $4,000–$5,000 fixed, 3–4 weeks, full production system (most popular)
- Scale: $5,000–$7,000 fixed, 5–6 weeks, multi-agent/complex
- Maintenance: Essential $1,500/mo · Active $3,000/mo · Partner $4,000/mo
- Enterprise: custom

CASE STUDIES (verified, clients NDA'd):
1. B2B Outbound, $85K saved, 3× qualified leads
2. Logistics Risk Intelligence, $1.2M saved in 6 months, 68% fewer incidents
3. AI Recruitment Engine, $124K+ saved, 50% faster time-to-hire

PROCESS: Free 60-min discovery call → Scoping → Build → Pilot → Ship (6 weeks)

BOOKING: Direct users to book a discovery call at: ${CAL_LINK}

RULES:
- Be concise, 2-4 sentences max, or a short bullet list when needed
- Sound like a smart engineer, not a scripted chatbot
- Never start with "Great question!" or filler phrases
- If someone seems ready to engage, strongly direct them to book the discovery call
- Be honest, if AI isn't the right tool, say so
- Don't discuss competitors
- Never make up metrics or client names beyond what's listed above`;

const SUGGESTED = [
  'What does a typical build cost?',
  'How long does a project take?',
  'Do you work with med spas?',
  'What is your process?',
  'Can you help with a CPA firm?',
];

async function callDeepSeek(messages) {
  const res = await fetch('https://api.deepseek.com/v1/chat/completions', {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Authorization': `Bearer ${DEEPSEEK_API_KEY}`,
    },
    body: JSON.stringify({
      model: 'deepseek-chat',
      messages: [
        { role: 'system', content: SYSTEM_PROMPT },
        ...messages,
      ],
      max_tokens: 400,
      temperature: 0.7,
      stream: false,
    }),
  });
  if (!res.ok) throw new Error(`DeepSeek API error: ${res.status}`);
  const data = await res.json();
  return data.choices?.[0]?.message?.content || 'Something went wrong. Please try again.';
}

function Chatbot() {
  const [open, setOpen] = useCbState(false);
  const [messages, setMessages] = useCbState([
    {
      role: 'assistant',
      content: "Hi, I'm the Quantaeight AI. Ask me anything about our services, pricing, or case studies. Ready to talk? I'll get you to the right person. 👋",
    },
  ]);
  const [input, setInput] = useCbState('');
  const [loading, setLoading] = useCbState(false);
  const [showSuggestions, setShowSuggestions] = useCbState(true);
  const messagesRef = useCbRef(null);
  const inputRef = useCbRef(null);
  const [hasUnread, setHasUnread] = useCbState(true);

  useCbEffect(() => {
    if (open && messagesRef.current) {
      messagesRef.current.scrollTop = messagesRef.current.scrollHeight;
    }
  }, [messages, open]);

  useCbEffect(() => {
    if (open) {
      setHasUnread(false);
      setTimeout(() => inputRef.current?.focus(), 120);
    }
  }, [open]);

  const sendMessage = async (text) => {
    if (!text.trim() || loading) return;
    const userMsg = { role: 'user', content: text };
    const newMessages = [...messages, userMsg];
    setMessages(newMessages);
    setInput('');
    setLoading(true);
    setShowSuggestions(false);

    try {
      // Build history for DeepSeek (exclude initial greeting from system)
      const history = newMessages
        .filter(m => !(m.role === 'assistant' && newMessages.indexOf(m) === 0))
        .map(m => ({ role: m.role, content: m.content }))
        .slice(-10); // last 10 messages for context

      const reply = await callDeepSeek(history);
      setMessages(prev => [...prev, { role: 'assistant', content: reply }]);
    } catch (err) {
      // Fallback to built-in claude if DeepSeek fails
      try {
        const fallback = await window.claude.complete({
          messages: [
            { role: 'user', content: `[Context: You are Quantaeight AI. ${SYSTEM_PROMPT.slice(0,500)}]\n\nUser asked: ${text}` },
          ],
        });
        setMessages(prev => [...prev, { role: 'assistant', content: fallback }]);
      } catch {
        setMessages(prev => [...prev, {
          role: 'assistant',
          content: `I'm having trouble connecting right now. For immediate help, book a discovery call: ${CAL_LINK}`,
        }]);
      }
    } finally {
      setLoading(false);
    }
  };

  const handleKey = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMessage(input); }
  };

  // Render text with clickable cal.com links
  const renderMsg = (text) => {
    const calRegex = /(book a discovery call|book.*?call|discovery call|https:\/\/cal\.com[^\s]*)/gi;
    const parts = text.split(calRegex);
    return parts.map((part, i) => {
      if (/book.*?call|discovery call/i.test(part)) {
        return (
          <a key={i} href={CAL_LINK} target="_blank" rel="noopener"
            onClick={() => setOpen(false)}
            style={{ color: 'var(--text-primary)', borderBottom: '1px dotted var(--accent-mint)', textDecoration: 'none' }}>
            {part}
          </a>
        );
      }
      if (/cal\.com/i.test(part)) {
        return (
          <a key={i} href={CAL_LINK} target="_blank" rel="noopener"
            style={{ color: 'var(--text-primary)', borderBottom: '1px dotted var(--accent-mint)', fontSize: 11, wordBreak: 'break-all', textDecoration: 'none' }}>
            Book a call →
          </a>
        );
      }
      return part;
    });
  };

  return (
    <>
      {/* Floating button */}
      <button onClick={() => setOpen(!open)} title="Chat with Quantaeight AI"
        style={{
          position: 'fixed', bottom: 28, right: 28, zIndex: 200,
          width: 52, height: 52, borderRadius: '50%',
          background: open ? 'var(--bg-tertiary)' : 'var(--accent-mint)',
          border: open ? '1.5px solid var(--border-emphasis)' : 'none',
          cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          boxShadow: open ? 'none' : '0 4px 24px rgba(0,217,160,0.45)',
          transition: 'all 0.3s cubic-bezier(0.16,1,0.3,1)',
        }}
        onMouseEnter={e => { if (!open) e.currentTarget.style.transform = 'scale(1.08)'; }}
        onMouseLeave={e => { e.currentTarget.style.transform = 'scale(1)'; }}
      >
        {open ? (
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="var(--text-secondary)" strokeWidth="2.5" strokeLinecap="round">
            <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
          </svg>
        ) : (
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#0A0A0B" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
            <path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>
          </svg>
        )}
        {!open && hasUnread && (
          <span style={{
            position: 'absolute', top: 2, right: 2,
            width: 12, height: 12, borderRadius: '50%',
            background: '#F59E0B',
            border: '2px solid var(--bg-primary)',
            animation: 'cb-pulse 2s ease infinite',
          }} />
        )}
      </button>

      {/* Chat window */}
      {open && (
        <div style={{
          position: 'fixed', bottom: 90, right: 28, zIndex: 199,
          width: 360, maxHeight: 540,
          background: '#0E1018',
          border: '1px solid var(--border-subtle)',
          borderRadius: 16,
          boxShadow: '0 20px 60px rgba(0,0,0,0.5)',
          display: 'flex', flexDirection: 'column',
          overflow: 'hidden',
          animation: 'cb-open 0.3s cubic-bezier(0.16,1,0.3,1)',
        }} className="cb-window">
          {/* Header */}
          <div style={{
            padding: '13px 16px',
            borderBottom: '1px solid var(--border-subtle)',
            display: 'flex', alignItems: 'center', gap: 10,
            background: 'var(--bg-tertiary)', flexShrink: 0,
          }}>
            <div style={{
              width: 34, height: 34, borderRadius: '50%',
              background: 'linear-gradient(135deg, var(--accent-mint), var(--accent-violet))',
              display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
              padding: 6, overflow: 'hidden',
            }}>
              <img src="assets/logo.png" alt="Quantaeight"
                style={{
                  width: '100%', height: '100%', objectFit: 'contain',
                  filter: 'invert(1) brightness(10)',
                }}
              />
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{
                fontFamily: '"Plus Jakarta Sans", Syne, sans-serif', fontSize: 14, fontWeight: 700,
                color: 'var(--text-primary)', letterSpacing: '0.01em',
              }}>Quantaeight AI</div>
              <div style={{
                display: 'flex', alignItems: 'center', gap: 5,
                fontFamily: 'JetBrains Mono, monospace', fontSize: 10,
                color: 'var(--accent-mint)',
              }}>
                <span style={{
                  width: 5, height: 5, borderRadius: '50%',
                  background: 'var(--accent-mint)', boxShadow: '0 0 5px var(--accent-mint)',
                  animation: 'cb-pulse 2s ease infinite',
                }} />
                online · instant replies
              </div>
            </div>
            <a href={CAL_LINK} target="_blank" rel="noopener"
              onClick={() => setOpen(false)}
              style={{
                fontFamily: 'JetBrains Mono, monospace', fontSize: 10,
                color: 'var(--text-primary)', textDecoration: 'none',
                padding: '5px 10px',
                border: '1px solid var(--accent-mint)',
                borderRadius: 6, flexShrink: 0,
                transition: 'all 0.2s ease',
              }}
              onMouseEnter={e => { e.currentTarget.style.background = 'var(--accent-mint)'; e.currentTarget.style.color = '#0A0A0B'; }}
              onMouseLeave={e => { e.currentTarget.style.background = 'transparent'; e.currentTarget.style.color = 'var(--text-primary)'; }}
            >Book call</a>
          </div>

          {/* Messages */}
          <div ref={messagesRef} style={{
            flex: 1, overflowY: 'auto', padding: '14px 14px 8px',
            display: 'flex', flexDirection: 'column', gap: 10,
            scrollbarWidth: 'thin',
          }}>
            {messages.map((msg, i) => (
              <div key={i} style={{
                display: 'flex',
                justifyContent: msg.role === 'user' ? 'flex-end' : 'flex-start',
              }}>
                <div style={{
                  maxWidth: '84%',
                  padding: '10px 13px',
                  borderRadius: msg.role === 'user' ? '12px 12px 3px 12px' : '12px 12px 12px 3px',
                  background: msg.role === 'user' ? 'var(--accent-mint)' : 'var(--bg-tertiary)',
                  border: msg.role === 'user' ? 'none' : '1px solid var(--border-subtle)',
                  color: msg.role === 'user' ? '#0A0A0B' : 'var(--text-primary)',
                  fontSize: 13, lineHeight: 1.55,
                  fontFamily: 'Inter, sans-serif',
                }}>
                  {msg.role === 'assistant' ? renderMsg(msg.content) : msg.content}
                </div>
              </div>
            ))}

            {loading && (
              <div style={{ display: 'flex', justifyContent: 'flex-start' }}>
                <div style={{
                  padding: '10px 14px',
                  borderRadius: '12px 12px 12px 3px',
                  background: 'var(--bg-tertiary)',
                  border: '1px solid var(--border-subtle)',
                  display: 'flex', gap: 4, alignItems: 'center',
                }}>
                  {[0,1,2].map(j => (
                    <span key={j} style={{
                      width: 6, height: 6, borderRadius: '50%',
                      background: 'var(--text-tertiary)',
                      animation: `cb-bounce 1s ease-in-out ${j * 0.15}s infinite`,
                    }} />
                  ))}
                </div>
              </div>
            )}

            {/* Suggested questions */}
            {showSuggestions && messages.length === 1 && (
              <div style={{ display: 'flex', flexDirection: 'column', gap: 5, marginTop: 4 }}>
                {SUGGESTED.map((q, i) => (
                  <button key={i} onClick={() => sendMessage(q)} style={{
                    background: 'transparent',
                    border: '1px solid var(--border-subtle)',
                    borderRadius: 8, padding: '7px 11px',
                    color: 'var(--text-secondary)', fontSize: 12,
                    fontFamily: 'Inter, sans-serif', cursor: 'pointer',
                    textAlign: 'left', transition: 'all 0.2s ease',
                  }}
                  onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--accent-mint)'; e.currentTarget.style.color = 'var(--accent-mint)'; }}
                  onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--border-subtle)'; e.currentTarget.style.color = 'var(--text-secondary)'; }}
                  >{q}</button>
                ))}
              </div>
            )}
          </div>

          {/* Input */}
          <div style={{
            padding: '10px 12px',
            borderTop: '1px solid var(--border-subtle)',
            display: 'flex', gap: 8, alignItems: 'flex-end',
            background: 'var(--bg-tertiary)', flexShrink: 0,
          }}>
            <textarea
              ref={inputRef}
              value={input}
              onChange={e => setInput(e.target.value)}
              onKeyDown={handleKey}
              placeholder="Ask about pricing, services, case studies..."
              rows={1}
              style={{
                flex: 1, background: 'var(--bg-secondary)',
                border: '1px solid var(--border-subtle)',
                borderRadius: 8, padding: '9px 12px',
                color: 'var(--text-primary)', fontSize: 13,
                fontFamily: 'Inter, sans-serif',
                outline: 'none', resize: 'none',
                maxHeight: 80, overflowY: 'auto',
                lineHeight: 1.4,
                transition: 'border-color 0.2s ease',
              }}
              onFocus={e => e.target.style.borderColor = 'var(--accent-mint)'}
              onBlur={e => e.target.style.borderColor = 'var(--border-subtle)'}
            />
            <button
              onClick={() => sendMessage(input)}
              disabled={loading || !input.trim()}
              style={{
                width: 36, height: 36, borderRadius: 8, flexShrink: 0,
                background: (loading || !input.trim()) ? 'var(--bg-tertiary)' : 'var(--accent-mint)',
                border: `1px solid ${(loading || !input.trim()) ? 'var(--border-subtle)' : 'transparent'}`,
                cursor: (loading || !input.trim()) ? 'not-allowed' : 'pointer',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                transition: 'all 0.2s ease',
              }}
            >
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none"
                stroke={(loading || !input.trim()) ? 'var(--text-tertiary)' : '#0A0A0B'}
                strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                <line x1="22" y1="2" x2="11" y2="13"/>
                <polygon points="22 2 15 22 11 13 2 9 22 2"/>
              </svg>
            </button>
          </div>

          {/* Footer CTA */}
          <div style={{
            padding: '8px 14px',
            borderTop: '1px solid var(--border-subtle)',
            background: 'var(--bg-tertiary)',
            textAlign: 'center',
          }}>
            <a href={CAL_LINK} target="_blank" rel="noopener"
              onClick={() => setOpen(false)}
              style={{
                fontFamily: 'JetBrains Mono, monospace', fontSize: 11,
                color: 'var(--text-primary)', textDecoration: 'none',
                display: 'inline-flex', alignItems: 'center', gap: 5,
              }}
            >
              <span style={{
                width: 5, height: 5, borderRadius: '50%',
                background: 'var(--accent-mint)',
                animation: 'cb-pulse 2s ease infinite',
                display: 'inline-block',
              }} />
              Book a free 60-min discovery call →
            </a>
          </div>
        </div>
      )}

      <style>{`
        @keyframes cb-open   { from{opacity:0;transform:translateY(12px) scale(0.97)} to{opacity:1;transform:translateY(0) scale(1)} }
        @keyframes cb-pulse  { 0%,100%{opacity:1} 50%{opacity:0.3} }
        @keyframes cb-bounce { 0%,80%,100%{transform:translateY(0)} 40%{transform:translateY(-5px)} }
        @media (max-width: 600px) {
          .cb-window {
            position: fixed !important;
            bottom: 0 !important;
            left: 0 !important;
            right: 0 !important;
            width: 100vw !important;
            max-height: 92svh !important;
            border-radius: 20px 20px 0 0 !important;
            background: #0C0E14 !important;
          }
        }
      `}</style>
    </>
  );
}

Object.assign(window, { Chatbot });
