// AI chatbot — production calls Cloudflare Pages Function /api/chat
const { useState: useStateChat, useRef: useRefChat, useEffect: useEffectChat } = React;

const SYSTEM_CONTEXT = `You are an AI representative for Jesús Álvarez, a Senior Healthcare Data Programmer with 35+ years of experience. Your job is to enthusiastically and professionally answer questions from recruiters, hiring managers, and visitors about why they should work with Jesús. Be confident, warm, and specific.

KEY FACTS ABOUT JESÚS:
- Based in Goleta, CA. U.S. Citizen. Founded Yu-Pa Corporation, a certified minority-owned business, in 2000.
- Education: B.S. Computer Systems Engineering, Instituto Tecnológico de Monterrey, Querétaro Campus, México.
- 35+ years of healthcare data programming experience.

CAREER HIGHLIGHTS:
1. IBM / Truven Health / Medstat (2000–2022, 22 years): Senior Programmer Consultant on AHRQ's Healthcare Cost & Utilization Project (HCUP). ARCHITECTED the master SAS processor program — the foundational engine producing 130+ national healthcare research databases each year, drawing data from nearly 50 U.S. states. Enforced HIPAA + federal data use agreements. Mentored new staff; recognized as the team's strongest programmer.
2. Foley Bezek Behle & Curtis (1998–1999): Built medical-deposition scanning + statistical extraction systems.
3. Shared Medical Systems (1993–1997): Joint Commission ORYX accreditation models + Executive Information System. TWO MERIT AWARDS.
4. SysteMetrics (1987–1992): Founding work on HCUP-1, HCUP-2, HCCRP databases. SAS 6.07, PL/I, mainframe.

SKILLS: SAS/Macro, SAS/C, SAS/Toolkit, SAS/ODS, Python, SQL, DB2, MS Access, Visual Basic, C, C++, JCL, TSO, ISPF, COBOL, FORTRAN, ICD-10-CM/PCS, CPT/HCPCS, DRG Groupers, HIPAA compliance.

WHAT COLLEAGUES SAY:
- Judy Parlato (Sr. PM, IBM): "Extraordinary communication skills... utmost professionalism and integrity."
- David Ross (Lead Programmer, Optum): "Very detail oriented and an excellent quality assurance reviewer."
- Mika Nagamine: "Arguably the strongest programming expertise in our office."

TONE: Be specific, never generic. If asked about something you don't know, say so honestly. Keep responses to 2-3 short paragraphs max. Sound like a confident friend recommending Jesús — not a corporate brochure. To contact him: alvarezjesus007@hotmail.com or (805) 453-5516.`;

function Chatbot() {
  const [open, setOpen] = useStateChat(false);
  const [messages, setMessages] = useStateChat([
    { role: 'assistant', content: "Hi — I'm an AI trained on Jesús's career. Ask me anything: his HCUP work, technical skills, why he'd be a great fit for your team, or how to reach him." },
  ]);
  const [input, setInput] = useStateChat('');
  const [loading, setLoading] = useStateChat(false);
  const scrollRef = useRefChat(null);

  useEffectChat(() => {
    if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
  }, [messages, loading]);

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

    try {
      const apiMessages = newMsgs
        .filter(m => m.role === 'user' || m.role === 'assistant')
        .slice(-8);

      let reply = '';
      const response = await fetch('/api/chat', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify({ messages: apiMessages }),
      });

      if (response.ok) {
        const data = await response.json();
        reply = data.reply;
      }

      if (!reply && window.claude && window.claude.complete) {
        const fallbackMessages = [
          { role: 'user', content: SYSTEM_CONTEXT + "\n\nThe visitor asks: " + text + "\n\nRespond as if you are Jesús's AI advocate. Keep it short and specific." },
        ];
        reply = await window.claude.complete({ messages: fallbackMessages });
      }

      if (!reply) throw new Error('No chatbot reply returned.');
      setMessages(m => [...m, { role: 'assistant', content: reply }]);
    } catch (err) {
      setMessages(m => [...m, { role: 'assistant', content: "Sorry — I'm having trouble right now. Reach Jesús directly at alvarezjesus007@hotmail.com or (805) 453-5516." }]);
    } finally {
      setLoading(false);
    }
  };

  const suggestions = [
    'Why hire Jesús?',
    'Tell me about HCUP',
    'What languages does he know?',
    'What do colleagues say?',
  ];

  return (
    <>
      {!open && (
        <button className="chat-pill" onClick={() => setOpen(true)}>
          <span className="pulse" />
          <span>Ask about Jesús</span>
        </button>
      )}
      {open && (
        <div style={{
          position: 'fixed', bottom: 24, right: 24, zIndex: 95,
          width: 'min(420px, calc(100vw - 32px))',
          height: 'min(580px, calc(100vh - 48px))',
          background: 'var(--ink-2)',
          border: '1px solid var(--rule)',
          borderRadius: 8,
          boxShadow: '0 24px 60px rgba(0,0,0,0.7)',
          display: 'flex', flexDirection: 'column',
          overflow: 'hidden',
          fontFamily: 'var(--sans)',
        }}>
          {/* header */}
          <div style={{
            padding: '14px 16px',
            borderBottom: '1px solid var(--rule)',
            display: 'flex', alignItems: 'center', justifyContent: 'space-between',
            background: 'var(--ink-3)',
          }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
              <span style={{
                width: 8, height: 8, borderRadius: '50%',
                background: 'var(--accent)',
                boxShadow: '0 0 10px var(--accent)',
              }} />
              <div>
                <div style={{ fontFamily: 'var(--serif)', fontSize: 17, fontStyle: 'italic' }}>Jesús's AI Advocate</div>
                <div style={{ fontFamily: 'var(--mono)', fontSize: 9, letterSpacing: '0.15em', color: 'var(--bone-faint)', textTransform: 'uppercase', marginTop: 2 }}>
                  ONLINE · ANSWERS IN SECONDS
                </div>
              </div>
            </div>
            <button onClick={() => setOpen(false)} style={{
              background: 'transparent', border: 'none', color: 'var(--bone-dim)', cursor: 'pointer',
              fontSize: 18, padding: 4, lineHeight: 1,
            }}>×</button>
          </div>

          {/* messages */}
          <div ref={scrollRef} style={{ flex: 1, overflowY: 'auto', padding: '16px', display: 'flex', flexDirection: 'column', gap: 12 }}>
            {messages.map((m, i) => (
              <div key={i} style={{
                alignSelf: m.role === 'user' ? 'flex-end' : 'flex-start',
                maxWidth: '85%',
                padding: '10px 14px',
                borderRadius: m.role === 'user' ? '14px 14px 2px 14px' : '14px 14px 14px 2px',
                background: m.role === 'user' ? 'var(--accent)' : 'var(--ink-3)',
                color: m.role === 'user' ? 'var(--ink)' : 'var(--bone)',
                fontSize: 14, lineHeight: 1.5,
                whiteSpace: 'pre-wrap',
              }}>
                {m.content}
              </div>
            ))}
            {loading && (
              <div style={{
                alignSelf: 'flex-start', padding: '10px 14px',
                borderRadius: '14px 14px 14px 2px',
                background: 'var(--ink-3)',
                display: 'flex', gap: 4, alignItems: 'center',
              }}>
                {[0, 1, 2].map(i => (
                  <span key={i} style={{
                    width: 6, height: 6, borderRadius: '50%', background: 'var(--bone-dim)',
                    animation: `bounce 1.2s infinite ${i * 0.15}s`,
                  }} />
                ))}
              </div>
            )}

            {messages.length === 1 && !loading && (
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginTop: 6 }}>
                {suggestions.map(s => (
                  <button key={s} onClick={() => send(s)} style={{
                    background: 'transparent',
                    border: '1px solid var(--rule)',
                    color: 'var(--bone-dim)',
                    padding: '7px 11px', borderRadius: 999,
                    fontSize: 12, fontFamily: 'var(--mono)', cursor: 'pointer',
                    letterSpacing: '0.04em',
                  }}>{s}</button>
                ))}
              </div>
            )}
          </div>

          {/* input */}
          <form onSubmit={e => { e.preventDefault(); send(input); }} style={{
            borderTop: '1px solid var(--rule)',
            padding: 12,
            display: 'flex', gap: 8,
            background: 'var(--ink-2)',
          }}>
            <input
              value={input}
              onChange={e => setInput(e.target.value)}
              placeholder="Ask anything about Jesús..."
              style={{
                flex: 1, background: 'var(--ink)', border: '1px solid var(--rule)',
                color: 'var(--bone)', padding: '10px 14px', borderRadius: 999,
                fontFamily: 'var(--sans)', fontSize: 14, outline: 'none',
              }}
            />
            <button type="submit" disabled={loading || !input.trim()} style={{
              background: 'var(--accent)', color: 'var(--ink)', border: 'none',
              padding: '0 16px', borderRadius: 999, cursor: 'pointer',
              fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.1em',
              textTransform: 'uppercase',
              opacity: loading || !input.trim() ? 0.4 : 1,
            }}>Send</button>
          </form>
        </div>
      )}
      <style>{`@keyframes bounce { 0%, 100% { transform: translateY(0); opacity: 0.4; } 50% { transform: translateY(-4px); opacity: 1; } }`}</style>
    </>
  );
}

window.Chatbot = Chatbot;
