// Dev — Devarsh Patel's portfolio AI assistant.
// Floating pill launcher + chat panel. Adapted for CDN React (no npm imports).

const { useState: useStateAD, useRef: useRefAD, useEffect: useEffectAD } = React;

const DEV = {
  name: 'Dev',
  role: 'Devarsh’s AI',
  greeting: "Hey — I’m Dev, Devarsh’s AI. Ask me about his work, his process, or how to reach him.",
  suggestions: [
    'Tell me about SolarSync',
    'What is Daily Living Lab?',
    'What is he good at?',
    'How do I reach him?',
  ],
};

const C = {
  accent: '#5AFF27',
  text: '#FFFBFB',
  muted: '#8A8A8A',
  body: '#D1D1D1',
  pink: '#EC008C',
  panel: 'rgba(10,10,10,0.96)',
  launcher: 'rgba(14,14,14,0.92)',
  hairline: 'rgba(255,255,255,0.10)',
  hairlineSoft: 'rgba(255,255,255,0.07)',
  surface: 'rgba(255,255,255,0.05)',
};

function AskDev() {
  const [open, setOpen] = useStateAD(false);
  const [messages, setMessages] = useStateAD([{ role: 'assistant', content: DEV.greeting }]);
  const [input, setInput] = useStateAD('');
  const [loading, setLoading] = useStateAD(false);
  const [error, setError] = useStateAD(null);

  const scrollRef = useRefAD(null);
  const inputRef = useRefAD(null);

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

  useEffectAD(() => {
    if (open) setTimeout(() => inputRef.current && inputRef.current.focus(), 260);
  }, [open]);

  useEffectAD(() => {
    const onKey = (e) => e.key === 'Escape' && setOpen(false);
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, []);

  async function send(text) {
    const content = (text !== undefined ? text : input).trim();
    if (!content || loading) return;

    const next = [...messages, { role: 'user', content }];
    setMessages(next);
    setInput('');
    setLoading(true);
    setError(null);

    try {
      const res = await fetch('/api/chat', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ messages: next.slice(1) }),
      });
      if (!res.ok) throw new Error('bad response');
      const data = await res.json();
      setMessages((m) => [...m, { role: 'assistant', content: data.reply }]);
    } catch {
      setError("Dev couldn’t be reached. Try again in a moment.");
    } finally {
      setLoading(false);
    }
  }

  function onKeyDown(e) {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      send();
    }
  }

  return (
    <React.Fragment>
      <style>{`
        @keyframes devBreathe {
          0%, 100% { opacity: 1;   transform: scale(1); }
          50%      { opacity: .55; transform: scale(.82); }
        }
        @keyframes devPing {
          0%   { opacity: .5; transform: scale(1); }
          70%  { opacity: 0;  transform: scale(2.6); }
          100% { opacity: 0;  transform: scale(2.6); }
        }
        @keyframes devThink {
          0%, 60%, 100% { opacity: .3; transform: translateY(0); }
          30%           { opacity: 1;  transform: translateY(-4px); }
        }
        .askdev-launcher:hover {
          transform: translateY(-2px) !important;
          border-color: rgba(255,255,255,0.20) !important;
        }
        @media (prefers-reduced-motion: reduce) {
          .askdev-launcher { transition: none !important; }
        }
      `}</style>

      {/* Launcher pill */}
      <button
        onClick={() => setOpen((v) => !v)}
        aria-label={open ? 'Close Dev' : 'Ask Dev — Devarsh’s AI assistant'}
        aria-expanded={open}
        className="askdev-launcher"
        style={{
          position: 'fixed', bottom: 24, right: 24, zIndex: 9999,
          display: 'flex', alignItems: 'center', gap: 10,
          height: 50, padding: open ? '0 16px' : '0 20px 0 16px',
          borderRadius: 100,
          border: `0.5px solid ${C.hairline}`,
          background: C.launcher,
          backdropFilter: 'blur(20px)', WebkitBackdropFilter: 'blur(20px)',
          color: C.text, cursor: 'pointer',
          fontFamily: "'Inter', system-ui, sans-serif",
          boxShadow: '0 8px 32px rgba(0,0,0,0.5)',
          transition: 'transform .3s cubic-bezier(.16,1,.3,1), padding .3s cubic-bezier(.16,1,.3,1), border-color .25s',
        }}
      >
        {open ? (
          <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round">
            <line x1="18" y1="6" x2="6" y2="18" /><line x1="6" y1="6" x2="18" y2="18" />
          </svg>
        ) : (
          <React.Fragment>
            {/* Breathing dot */}
            <span style={{ position: 'relative', display: 'grid', placeItems: 'center', width: 8, height: 8 }}>
              <span style={{ position: 'absolute', width: 8, height: 8, borderRadius: '50%', background: C.accent, animation: 'devPing 2.4s cubic-bezier(0,0,0.2,1) infinite' }} />
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: C.accent, animation: 'devBreathe 2.4s ease-in-out infinite' }} />
            </span>
            <span style={{ fontSize: 14, fontWeight: 600, letterSpacing: '-0.01em', whiteSpace: 'nowrap' }}>
              Ask <span style={{ fontStyle: 'italic' }}>Dev</span>
            </span>
          </React.Fragment>
        )}
      </button>

      {/* Chat panel */}
      <div
        role="dialog"
        aria-label="Chat with Dev"
        style={{
          position: 'fixed', bottom: 88, right: 24, zIndex: 9998,
          width: 'min(392px, calc(100vw - 48px))',
          height: 'min(580px, calc(100vh - 140px))',
          display: 'flex', flexDirection: 'column',
          background: C.panel,
          backdropFilter: 'blur(24px)', WebkitBackdropFilter: 'blur(24px)',
          border: `0.5px solid ${C.hairline}`,
          borderRadius: 22, overflow: 'hidden',
          boxShadow: '0 24px 64px rgba(0,0,0,0.6)',
          fontFamily: "'Inter', system-ui, sans-serif",
          opacity: open ? 1 : 0,
          transform: open ? 'translateY(0) scale(1)' : 'translateY(14px) scale(0.97)',
          pointerEvents: open ? 'auto' : 'none',
          transition: 'opacity .3s ease, transform .3s cubic-bezier(.16,1,.3,1)',
        }}
      >
        {/* Header */}
        <header style={{ padding: '16px 20px', borderBottom: `0.5px solid ${C.hairlineSoft}`, display: 'flex', alignItems: 'center', gap: 13, flexShrink: 0 }}>
          {/* Avatar */}
          <div style={{ position: 'relative', flexShrink: 0 }}>
            <div style={{ width: 36, height: 36, borderRadius: '50%', background: '#141414', border: `0.5px solid ${C.hairline}`, display: 'grid', placeItems: 'center', fontSize: 15, fontWeight: 700, fontStyle: 'italic', color: C.text, letterSpacing: '-0.02em' }}>D</div>
            <span style={{ position: 'absolute', bottom: 0, right: 0, width: 9, height: 9, borderRadius: '50%', background: C.accent, border: '2px solid #0A0A0A', animation: 'devBreathe 2.4s ease-in-out infinite' }} />
          </div>
          <div style={{ lineHeight: 1.35 }}>
            <div style={{ fontSize: 15, fontWeight: 600, color: C.text, letterSpacing: '-0.01em', fontStyle: 'italic' }}>{DEV.name}</div>
            <div style={{ fontSize: 10, color: C.muted, textTransform: 'uppercase', letterSpacing: '0.14em', fontWeight: 500 }}>{DEV.role}</div>
          </div>
        </header>

        {/* Messages */}
        <div ref={scrollRef} style={{ flex: 1, overflowY: 'auto', padding: 20, display: 'flex', flexDirection: 'column', gap: 14 }}>
          {messages.map((m, i) => {
            const isUser = m.role === 'user';
            return (
              <div key={i} style={{ display: 'flex', justifyContent: isUser ? 'flex-end' : 'flex-start' }}>
                <div style={{
                  maxWidth: '85%', fontSize: 14, lineHeight: 1.62, padding: '11px 15px',
                  borderRadius: 16,
                  borderBottomRightRadius: isUser ? 4 : 16,
                  borderBottomLeftRadius: isUser ? 16 : 4,
                  background: isUser ? C.text : C.surface,
                  color: isUser ? '#000' : C.body,
                  border: isUser ? 'none' : `0.5px solid ${C.hairlineSoft}`,
                  whiteSpace: 'pre-wrap', wordBreak: 'break-word',
                }}>{m.content}</div>
              </div>
            );
          })}

          {loading && (
            <div style={{ display: 'flex', gap: 5, padding: '10px 4px' }}>
              {[0, 1, 2].map((i) => (
                <span key={i} style={{ width: 6, height: 6, borderRadius: '50%', background: '#6A6A6A', animation: `devThink 1.2s ${i * 0.15}s infinite ease-in-out` }} />
              ))}
            </div>
          )}

          {error && <div style={{ fontSize: 12, color: C.pink, padding: '4px 2px' }}>{error}</div>}

          {messages.length === 1 && !loading && (
            <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8, marginTop: 6 }}>
              {DEV.suggestions.map((s) => (
                <button
                  key={s}
                  onClick={() => send(s)}
                  style={{ fontSize: 12, color: C.body, background: 'rgba(255,255,255,0.04)', border: `0.5px solid ${C.hairline}`, borderRadius: 40, padding: '7px 13px', cursor: 'pointer', fontFamily: 'inherit', transition: 'background .2s, border-color .2s' }}
                  onMouseEnter={(e) => { e.currentTarget.style.background = 'rgba(255,255,255,0.08)'; e.currentTarget.style.borderColor = 'rgba(255,255,255,0.18)'; }}
                  onMouseLeave={(e) => { e.currentTarget.style.background = 'rgba(255,255,255,0.04)'; e.currentTarget.style.borderColor = C.hairline; }}
                >{s}</button>
              ))}
            </div>
          )}
        </div>

        {/* Composer */}
        <div style={{ padding: 14, borderTop: `0.5px solid ${C.hairlineSoft}`, display: 'flex', gap: 8, alignItems: 'flex-end', flexShrink: 0 }}>
          <textarea
            ref={inputRef}
            rows={1}
            value={input}
            onChange={(e) => setInput(e.target.value)}
            onKeyDown={onKeyDown}
            placeholder="Ask Dev anything…"
            style={{ flex: 1, resize: 'none', maxHeight: 96, background: 'rgba(255,255,255,0.04)', border: `0.5px solid ${C.hairline}`, borderRadius: 12, padding: '11px 14px', color: C.text, fontSize: 14, fontFamily: 'inherit', lineHeight: 1.5, outline: 'none' }}
          />
          <button
            onClick={() => send()}
            disabled={!input.trim() || loading}
            aria-label="Send"
            style={{ width: 40, height: 40, flexShrink: 0, borderRadius: 12, border: 'none', background: input.trim() && !loading ? C.text : 'rgba(255,255,255,0.08)', color: input.trim() && !loading ? '#000' : '#5A5A5A', cursor: input.trim() && !loading ? 'pointer' : 'default', display: 'grid', placeItems: 'center', transition: 'background .2s' }}
          >
            <svg width="17" height="17" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" 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>
      </div>
    </React.Fragment>
  );
}

Object.assign(window, { AskDev });
