// crm-chat.jsx — AI Chat Assistant (floating panel)
const { useState, useEffect, useRef } = React;

// ── Minimal markdown renderer ──────────────────────────────
function inlineMarkdown(text) {
  const parts = [];
  const rx = /\*\*(.+?)\*\*|\*(.+?)\*|`(.+?)`/g;
  let last = 0, m, k = 0;
  while ((m = rx.exec(text)) !== null) {
    if (m.index > last) parts.push(text.slice(last, m.index));
    if (m[1]) parts.push(<strong key={k++}>{m[1]}</strong>);
    else if (m[2]) parts.push(<em key={k++}>{m[2]}</em>);
    else if (m[3]) parts.push(
      <code key={k++} style={{background:'rgba(0,0,0,.08)',padding:'1px 5px',borderRadius:3,fontFamily:'monospace',fontSize:'.88em'}}>{m[3]}</code>
    );
    last = m.index + m[0].length;
  }
  if (last < text.length) parts.push(text.slice(last));
  return parts.length === 0 ? '' : parts.length === 1 && typeof parts[0] === 'string' ? parts[0] : parts;
}

function MarkdownBlock({ text }) {
  if (!text) return null;
  const lines = text.split('\n');
  const out = [];
  let i = 0;
  while (i < lines.length) {
    const line = lines[i];
    if (!line.trim()) { i++; continue; }
    if (line.startsWith('### ')) {
      out.push(<div key={i} style={{fontWeight:700,fontSize:13,color:'var(--navy)',marginTop:8,marginBottom:3}}>{inlineMarkdown(line.slice(4))}</div>);
      i++; continue;
    }
    if (line.startsWith('## ') || line.startsWith('# ')) {
      const lvl = line.startsWith('# ') && !line.startsWith('## ') ? 1 : 2;
      out.push(<div key={i} style={{fontWeight:700,fontSize:14-lvl,color:'var(--navy)',marginTop:8,marginBottom:3}}>{inlineMarkdown(line.replace(/^#{1,3} /,''))}</div>);
      i++; continue;
    }
    if (/^[-•*]\s/.test(line)) {
      const items = [];
      while (i < lines.length && /^[-•*]\s/.test(lines[i]))
        items.push(<li key={i}>{inlineMarkdown(lines[i++].slice(2))}</li>);
      out.push(<ul key={'u'+i} style={{paddingLeft:18,margin:'4px 0',lineHeight:1.65}}>{items}</ul>);
      continue;
    }
    if (/^\d+\.\s/.test(line)) {
      const items = [];
      while (i < lines.length && /^\d+\.\s/.test(lines[i]))
        items.push(<li key={i}>{inlineMarkdown(lines[i++].replace(/^\d+\.\s/,''))}</li>);
      out.push(<ol key={'o'+i} style={{paddingLeft:18,margin:'4px 0',lineHeight:1.65}}>{items}</ol>);
      continue;
    }
    out.push(<p key={i} style={{margin:'3px 0',lineHeight:1.65}}>{inlineMarkdown(line)}</p>);
    i++;
  }
  return <div>{out}</div>;
}

// ── FloatingChat component ─────────────────────────────────
function FloatingChat({ user }) {
  const GREETING = {
    role:'assistant', done:true,
    content:`Hi ${user.name.split(' ')[0]}! I'm your CRM assistant. I can answer questions about leads, accounts, pipeline, revenue, tickets, and more. What would you like to know?`,
  };

  const [open,      setOpen]      = useState(false);
  const [messages,  setMessages]  = useState([GREETING]);
  const [input,     setInput]     = useState('');
  const [loading,   setLoading]   = useState(false);
  const [unread,    setUnread]    = useState(0);
  const [typeText,  setTypeText]  = useState('');  // currently animating text
  const [typeFull,  setTypeFull]  = useState('');  // full target text
  const [typeTools, setTypeTools] = useState([]);

  const bottomRef  = useRef();
  const inputRef   = useRef();
  const timerRef   = useRef();

  // Auto-scroll
  useEffect(() => { bottomRef.current?.scrollIntoView({ behavior:'smooth' }); }, [messages, typeText, loading]);

  // Focus input when opened
  useEffect(() => { if (open) { setUnread(0); setTimeout(() => inputRef.current?.focus(), 100); } }, [open]);

  // Typewriter effect
  useEffect(() => {
    if (!typeFull) return;
    clearInterval(timerRef.current);
    let idx = 0;
    timerRef.current = setInterval(() => {
      idx += 4;
      if (idx >= typeFull.length) {
        clearInterval(timerRef.current);
        setMessages(prev => [...prev, { role:'assistant', done:true, content:typeFull, tools:typeTools }]);
        setTypeText('');
        setTypeFull('');
        setTypeTools([]);
      } else {
        setTypeText(typeFull.slice(0, idx));
      }
    }, 18);
    return () => clearInterval(timerRef.current);
  }, [typeFull]);

  const send = async () => {
    const text = input.trim();
    if (!text || loading || typeFull) return;

    const userMsg   = { role:'user', done:true, content:text };
    const newMsgs   = [...messages, userMsg];
    setMessages(newMsgs);
    setInput('');
    setLoading(true);

    try {
      // Build history (skip greeting at index 0)
      const history = newMsgs
        .filter((m, i) => i > 0 && m.done)
        .map(m => ({ role: m.role, content: m.content }));

      const res  = await fetch('/api/chat', {
        method: 'POST',
        headers: { 'Content-Type':'application/json' },
        body: JSON.stringify({ messages: history }),
      });

      let data;
      try { data = await res.json(); }
      catch { throw new Error(`Server error (${res.status}) — check API key and server logs`); }
      if (!res.ok) throw new Error(data?.error || `Error ${res.status}`);

      setLoading(false);
      setTypeTools(data.toolsUsed || []);
      setTypeFull(data.reply || 'Sorry, I could not generate a response.');
      if (!open) setUnread(u => u + 1);
    } catch (e) {
      setLoading(false);
      setMessages(prev => [...prev, { role:'assistant', done:true, error:true, content:`Sorry, I ran into an error: ${e.message}` }]);
    }
  };

  const clearChat = () => {
    clearInterval(timerRef.current);
    setMessages([GREETING]);
    setTypeText('');
    setTypeFull('');
    setInput('');
    setLoading(false);
  };

  const busy = loading || !!typeFull;

  // Suggested prompts for empty chat
  const suggestions = [
    'Summarize the pipeline',
    "What's the revenue forecast?",
    'Show overdue follow-ups',
    'Who are the top performers?',
  ];

  return (
    <>
      {/* ── Chat panel ── */}
      {open && (
        <div style={{
          position:'fixed', bottom:76, right:20, width:390,
          maxHeight:'calc(100vh - 110px)',
          background:'white', borderRadius:16,
          boxShadow:'0 12px 48px rgba(0,0,0,.2)',
          display:'flex', flexDirection:'column',
          zIndex:1100, overflow:'hidden',
          border:'1px solid var(--g200)',
          animation:'chatSlideUp .2s ease',
        }}>
          {/* Header */}
          <div style={{background:'var(--navy)',color:'white',padding:'12px 16px',display:'flex',alignItems:'center',gap:10,flexShrink:0}}>
            <div style={{width:34,height:34,borderRadius:'50%',background:'rgba(255,255,255,.15)',display:'flex',alignItems:'center',justifyContent:'center',fontSize:18}}>🤖</div>
            <div style={{flex:1}}>
              <div style={{fontWeight:700,fontSize:14,lineHeight:1.2}}>CRM Assistant</div>
              <div style={{fontSize:11,opacity:.6}}>Powered by Claude · asks your live data</div>
            </div>
            <button title="Clear conversation" onClick={clearChat}
              style={{background:'none',border:'none',color:'rgba(255,255,255,.55)',cursor:'pointer',fontSize:16,padding:'4px 6px',borderRadius:4,lineHeight:1}}>🗑</button>
            <button onClick={() => setOpen(false)}
              style={{background:'none',border:'none',color:'white',cursor:'pointer',fontSize:20,lineHeight:1,padding:'2px 4px'}}>×</button>
          </div>

          {/* Messages area */}
          <div style={{flex:1,overflowY:'auto',padding:'14px 14px 6px',display:'flex',flexDirection:'column',gap:12,minHeight:0}}>
            {messages.map((msg, idx) => (
              <div key={idx} style={{display:'flex',alignItems:'flex-start',justifyContent:msg.role==='user'?'flex-end':'flex-start',gap:8}}>
                {msg.role === 'assistant' && (
                  <div style={{width:26,height:26,borderRadius:'50%',background:'var(--navy)',color:'white',display:'flex',alignItems:'center',justifyContent:'center',fontSize:13,flexShrink:0,marginTop:2}}>🤖</div>
                )}
                <div style={{
                  maxWidth:'84%',fontSize:13,lineHeight:1.5,
                  background: msg.role==='user' ? 'var(--navy)' : msg.error ? '#fef2f2' : 'var(--off)',
                  color:      msg.role==='user' ? 'white'       : msg.error ? '#991b1b' : 'var(--navy)',
                  borderRadius: msg.role==='user' ? '14px 14px 4px 14px' : '14px 14px 14px 4px',
                  padding:'10px 13px',
                }}>
                  {msg.role === 'user'
                    ? msg.content
                    : <MarkdownBlock text={msg.content} />}
                  {msg.tools?.length > 0 && (
                    <div style={{marginTop:6,fontSize:11,opacity:.5,fontStyle:'italic'}}>
                      🔍 {msg.tools.map(t => t.replace('get_','').replace(/_/g,' ')).join(', ')}
                    </div>
                  )}
                </div>
              </div>
            ))}

            {/* Typewriter bubble */}
            {typeText && (
              <div style={{display:'flex',alignItems:'flex-start',gap:8}}>
                <div style={{width:26,height:26,borderRadius:'50%',background:'var(--navy)',color:'white',display:'flex',alignItems:'center',justifyContent:'center',fontSize:13,flexShrink:0,marginTop:2}}>🤖</div>
                <div style={{maxWidth:'84%',background:'var(--off)',borderRadius:'14px 14px 14px 4px',padding:'10px 13px',fontSize:13,color:'var(--navy)'}}>
                  <MarkdownBlock text={typeText} />
                  <span style={{opacity:.45,fontFamily:'monospace'}}>▍</span>
                </div>
              </div>
            )}

            {/* Thinking dots */}
            {loading && !typeText && (
              <div style={{display:'flex',alignItems:'flex-start',gap:8}}>
                <div style={{width:26,height:26,borderRadius:'50%',background:'var(--navy)',color:'white',display:'flex',alignItems:'center',justifyContent:'center',fontSize:13,flexShrink:0}}>🤖</div>
                <div style={{background:'var(--off)',borderRadius:'14px 14px 14px 4px',padding:'12px 16px',display:'flex',gap:5,alignItems:'center'}}>
                  {[0,.22,.44].map((d,i) => (
                    <div key={i} style={{width:7,height:7,borderRadius:'50%',background:'var(--g300)',animation:`chatDot 1.3s ease-in-out ${d}s infinite`}} />
                  ))}
                </div>
              </div>
            )}

            <div ref={bottomRef} />
          </div>

          {/* Suggestions (first message only) */}
          {messages.length === 1 && !loading && (
            <div style={{padding:'0 14px 10px',display:'flex',flexWrap:'wrap',gap:6}}>
              {suggestions.map(s => (
                <button key={s} onClick={() => { setInput(s); setTimeout(() => inputRef.current?.focus(), 0); }}
                  style={{fontSize:12,padding:'5px 10px',borderRadius:20,border:'1px solid var(--g200)',background:'white',cursor:'pointer',color:'var(--g600)',fontFamily:'var(--font)'}}>
                  {s}
                </button>
              ))}
            </div>
          )}

          {/* Input row */}
          <div style={{borderTop:'1px solid var(--g100)',padding:'10px 12px',display:'flex',gap:8,flexShrink:0}}>
            <textarea ref={inputRef} value={input} rows={1}
              onChange={e => setInput(e.target.value)}
              onKeyDown={e => { if (e.key==='Enter' && !e.shiftKey) { e.preventDefault(); send(); } }}
              placeholder="Ask anything about your CRM…"
              disabled={busy}
              style={{
                flex:1, border:`1.5px solid ${busy?'var(--g200)':'var(--g200)'}`,
                borderRadius:8, padding:'8px 12px', fontSize:13,
                fontFamily:'var(--font)', color:'var(--navy)',
                resize:'none', outline:'none', lineHeight:1.5,
                maxHeight:90, overflowY:'auto',
                background: busy ? 'var(--off)' : 'white',
                transition:'border-color .15s',
              }}
              onFocus={e => { if (!busy) e.target.style.borderColor='var(--navy)'; }}
              onBlur={e => { e.target.style.borderColor='var(--g200)'; }}
            />
            <button onClick={send} disabled={!input.trim() || busy}
              style={{
                background:'var(--navy)', color:'white', border:'none',
                borderRadius:8, width:40, cursor: (!input.trim()||busy) ? 'default':'pointer',
                opacity: (!input.trim()||busy) ? .35 : 1,
                fontSize:17, flexShrink:0, transition:'opacity .15s',
                display:'flex', alignItems:'center', justifyContent:'center',
              }}>➤</button>
          </div>
        </div>
      )}

      {/* ── Floating button ── */}
      <button onClick={() => setOpen(o => !o)}
        style={{
          position:'fixed', bottom:20, right:20,
          width:54, height:54, borderRadius:'50%',
          background: open ? 'var(--g500)' : 'var(--navy)',
          color:'white', border:'none', cursor:'pointer',
          fontSize: open ? 22 : 24,
          boxShadow:'0 4px 18px rgba(0,0,0,.28)',
          display:'flex', alignItems:'center', justifyContent:'center',
          zIndex:1099, transition:'background .2s, transform .15s',
        }}
        title={open ? 'Close assistant' : 'Open CRM assistant'}>
        {open ? '×' : '💬'}
        {!open && unread > 0 && (
          <div style={{
            position:'absolute', top:-2, right:-2,
            width:20, height:20, borderRadius:'50%',
            background:'var(--red)', fontSize:11, fontWeight:700,
            display:'flex', alignItems:'center', justifyContent:'center',
            border:'2px solid white',
          }}>{unread > 9 ? '9+' : unread}</div>
        )}
      </button>

      {/* ── Keyframe animations ── */}
      <style>{`
        @keyframes chatDot {
          0%,80%,100%{transform:scale(.8);opacity:.4}
          40%{transform:scale(1.2);opacity:1}
        }
        @keyframes chatSlideUp {
          from{opacity:0;transform:translateY(12px)}
          to{opacity:1;transform:translateY(0)}
        }
      `}</style>
    </>
  );
}

Object.assign(window, { FloatingChat });
