// Floating AI assistant chatbot — uses window.claude.complete
const Chatbot = () => {
  const [open, setOpen] = useState(false);
  const [busy, setBusy] = useState(false);
  const [input, setInput] = useState('');
  const [msgs, setMsgs] = useState([
    { role: 'assistant', text: "Hi — I'm Rocketberry's AI assistant. Ask me anything about AIDD, our solutions, or how we'd approach your workflow." },
  ]);
  const scrollRef = useRef(null);

  useEffect(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [msgs, busy]);

  const send = async (text) => {
    const q = (text ?? input).trim();
    if (!q || busy) return;
    setInput('');
    const next = [...msgs, { role: 'user', text: q }];
    setMsgs(next);
    setBusy(true);
    try {
      const sys = `You are Rocketberry's AI assistant on its marketing website. Rocketberry is an AI engineering & solutions firm that builds outcome-driven systems using AI-Driven Development (AIDD). Solutions include AI chatbots, startup management systems, smart document processing, workflow automation, HRMS, and AI-enabled ERP — across 9 industries. Reply in 2-3 short sentences, friendly and concrete. Always end by inviting the user to book a demo if relevant.`;
      const messages = [
        { role: 'user', content: sys + '\n\nUser question: ' + q },
      ];
      const reply = await window.claude.complete({ messages });
      setMsgs(m => [...m, { role: 'assistant', text: reply }]);
    } catch (e) {
      setMsgs(m => [...m, { role: 'assistant', text: "I couldn't reach the model just now — but you can book a demo any time and a Rocketberry engineer will get back to you." }]);
    } finally {
      setBusy(false);
    }
  };

  const suggestions = [
    'What is AIDD?',
    'Pricing model?',
    'How fast can we ship?',
  ];

  return (
    <>
      {/* Bubble */}
      <button
        onClick={() => setOpen(o => !o)}
        className="fixed bottom-6 right-6 z-40 w-14 h-14 rounded-full shadow-card border border-token flex items-center justify-center transition-transform hover:scale-105 surface"
        aria-label="Open AI assistant"
      >
        {open ? <I.Close size={20}/> : (
          <span className="relative">
            <SwirlMark size={28}/>
          </span>
        )}
      </button>

      {/* Panel */}
      {open && (
        <div className="fixed bottom-24 right-6 z-40 w-[min(380px,calc(100vw-32px))] h-[min(560px,calc(100vh-140px))] card shadow-card flex flex-col overflow-hidden">
          {/* Header */}
          <div className="px-4 py-3 border-b border-token flex items-center justify-between">
            <div className="flex items-center gap-2.5">
              <SwirlMark size={20}/>
              <div>
                <div className="text-[13px] font-medium">Rocketberry Assistant</div>
                <div className="text-[10px] font-mono text-muted flex items-center gap-1.5"><span className="w-1.5 h-1.5 rounded-full bg-brand-purple animate-pulse"/> online</div>
              </div>
            </div>
            <button onClick={() => setOpen(false)} className="text-muted hover:text-[var(--text)]"><I.Close size={16}/></button>
          </div>

          {/* Messages */}
          <div ref={scrollRef} className="flex-1 overflow-y-auto px-4 py-4 space-y-3">
            {msgs.map((m, i) => (
              <div key={i} className={`flex ${m.role === 'user' ? 'justify-end' : 'justify-start'}`}>
                <div className={`max-w-[85%] px-3.5 py-2.5 rounded-2xl text-[13.5px] leading-relaxed ${
                  m.role === 'user'
                    ? 'bg-[var(--text)] text-[var(--bg)] rounded-br-md'
                    : 'border border-token rounded-bl-md'
                }`}>
                  {m.text}
                </div>
              </div>
            ))}
            {busy && (
              <div className="flex justify-start">
                <div className="px-3.5 py-2.5 border border-token rounded-2xl rounded-bl-md flex items-center gap-1.5">
                  <span className="w-1.5 h-1.5 rounded-full bg-muted animate-bounce" style={{animationDelay:'0ms'}}/>
                  <span className="w-1.5 h-1.5 rounded-full bg-muted animate-bounce" style={{animationDelay:'150ms'}}/>
                  <span className="w-1.5 h-1.5 rounded-full bg-muted animate-bounce" style={{animationDelay:'300ms'}}/>
                </div>
              </div>
            )}
          </div>

          {/* Suggestions */}
          {msgs.length <= 1 && (
            <div className="px-4 pb-2 flex flex-wrap gap-1.5">
              {suggestions.map(s => (
                <button key={s} onClick={() => send(s)} className="text-[12px] px-2.5 py-1 rounded-full border border-token text-muted hover:text-[var(--text)]">
                  {s}
                </button>
              ))}
            </div>
          )}

          {/* Input */}
          <form onSubmit={(e)=>{e.preventDefault(); send();}} className="border-t border-token p-3 flex items-center gap-2">
            <input
              value={input}
              onChange={e=>setInput(e.target.value)}
              placeholder="Ask about AIDD, solutions, pricing..."
              className="flex-1 bg-transparent text-[13.5px] px-2 py-1.5 outline-none"
            />
            <button type="submit" disabled={busy || !input.trim()}
              className="w-8 h-8 rounded-lg btn-primary flex items-center justify-center disabled:opacity-40">
              <I.Send size={14}/>
            </button>
          </form>
        </div>
      )}
    </>
  );
};

window.Chatbot = Chatbot;
