// AI Chat — uses window.claude.complete with Tim's CV+portfolio as context

const { useState: useStateChat, useEffect: useEffectChat, useRef: useRefChat } = React;

function buildSystemContext() {
  const d = window.DATA;
  let ctx = `Je bent Tim Overbeek's CV-assistant. Spreek Nederlands (tenzij de vraag in Engels wordt gesteld). Houd antwoorden kort, vriendelijk en feitelijk — 2 tot 4 zinnen. Je beantwoordt vragen over Tim's ervaring, projecten, skills, en achtergrond. Je verzint niets wat niet in de context staat; als je iets niet weet, zeg dat eerlijk en verwijs naar Tim zelf (tim@overbeek.info).\n\n`;
  ctx += `--- TIM'S GEGEVENS ---\n`;
  ctx += `Naam: ${d.name}\n`;
  ctx += `Rol: ${d.tagline}\n`;
  ctx += `Intro: ${d.intro}\n\n`;
  ctx += `Over mij:\n${d.about.join('\n')}\n\n`;
  ctx += `ERVARING:\n`;
  d.experience.forEach(e => {
    ctx += `- ${e.title} bij ${e.org} (${e.when}): ${e.body}\n`;
  });
  ctx += `\nOPLEIDING:\n`;
  d.education.forEach(e => {
    ctx += `- ${e.title} — ${e.org} (${e.when}): ${e.body}\n`;
  });
  ctx += `\nVAARDIGHEDEN:\n${d.skills.map(s => s.name).join(', ')}\n\n`;
  ctx += `PORTFOLIO PROJECTEN:\n`;
  d.portfolio.forEach(p => {
    ctx += `• ${p.title} (${p.kind}, ${p.org}, ${p.year}). Rol: ${p.role}. ${p.lede} ${p.body.join(' ').replace(/<[^>]+>/g,'')}\n`;
  });
  ctx += `\nContact: ${d.contact.email} · ${d.contact.phone}`;
  if (d.aiContext) {
    ctx += `\n\n--- EXTRA CONTEXT ---\n${d.aiContext.trim()}`;
  }
  return ctx;
}

const INITIAL = {
  role: 'ai',
  text: "Hoi! Ik ben Tim's CV-assistant. Vraag me gerust over zijn ervaring, projecten bij PGGM, skills of werk met generatieve AI.",
};

const SUGGESTIONS = [
  "Welke AI-assistants heeft Tim gebouwd?",
  "Wat doet hij bij UWV?",
  "Wat zijn Tim's sterkste skills?",
  "Hoeveel impact hadden zijn workshops?",
];

function Chat() {
  const [open, setOpen] = useStateChat(false);
  const [messages, setMessages] = useStateChat([INITIAL]);
  const [input, setInput] = useStateChat('');
  const [loading, setLoading] = useStateChat(false);
  const bodyRef = useRefChat(null);
  const taRef = useRefChat(null);

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

  const send = async (text) => {
    const q = (text || input).trim();
    if (!q || loading) return;
    setInput('');
    const newMessages = [...messages, { role: 'user', text: q }];
    setMessages(newMessages);
    setLoading(true);
    try {
      const conv = newMessages.filter(m => m.role !== 'ai' || m !== INITIAL).map(m => ({
        role: m.role === 'ai' ? 'assistant' : 'user',
        content: m.text,
      }));

      let reply;
      if (typeof window !== 'undefined' && window.claude && typeof window.claude.complete === 'function') {
        // Claude preview / artifact environment: use built-in helper
        const ctx = buildSystemContext();
        const prompt = {
          messages: [
            { role: 'user', content: `${ctx}\n\n--- EINDE CONTEXT ---\n\nDe gebruiker stelt nu een vraag. Antwoord alleen op basis van de gegevens hierboven. Vraag: "${q}"` },
          ],
        };
        reply = await window.claude.complete(prompt);
      } else {
        // Deployed environment: call our own rate-limited endpoint
        const res = await fetch('/api/chat', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ messages: conv }),
        });
        const data = await res.json().catch(() => ({}));
        if (!res.ok) {
          throw new Error(data.error || `HTTP ${res.status}`);
        }
        reply = data.reply;
      }

      setMessages([...newMessages, { role: 'ai', text: reply || 'Sorry, geen antwoord.' }]);
    } catch (err) {
      const msg = err && err.message ? err.message : 'Er ging iets mis. Probeer het later nog eens of mail Tim direct: tim@overbeek.info';
      setMessages([...newMessages, { role: 'ai', text: msg }]);
    } finally {
      setLoading(false);
    }
  };

  const onKey = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      send();
    }
  };

  if (!open) {
    return (
      <button className="chat-fab" onClick={() => setOpen(true)}>
        <span className="dot"></span>
        <span>Vraag Tim's AI iets</span>
        <span className="arrow">↗</span>
      </button>
    );
  }

  return (
    <div className="chat-panel" role="dialog" aria-label="AI chat over Tim">
      <div className="chat-head">
        <div className="av">T</div>
        <div className="info">
          <div className="name">Tim's CV-assistant</div>
          <div className="status">Live · Claude Haiku 4.5</div>
        </div>
        <button className="close" onClick={() => setOpen(false)} aria-label="Sluiten">×</button>
      </div>
      <div className="chat-body" ref={bodyRef}>
        {messages.map((m, i) => (
          <div key={i} className={`bubble ${m.role}`} dangerouslySetInnerHTML={{__html: m.text.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')}} />
        ))}
        {loading && (
          <div className="bubble ai"><div className="typing"><span></span><span></span><span></span></div></div>
        )}
      </div>
      {messages.length === 1 && !loading && (
        <div className="chat-suggestions">
          {SUGGESTIONS.map(s => (
            <button key={s} onClick={() => send(s)}>{s}</button>
          ))}
        </div>
      )}
      <div className="chat-input">
        <textarea
          ref={taRef}
          rows={1}
          value={input}
          onChange={e => setInput(e.target.value)}
          onKeyDown={onKey}
          placeholder="Stel een vraag over Tim..."
        />
        <button className="send" onClick={() => send()} disabled={!input.trim() || loading} aria-label="Verstuur">
          <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" width="16" height="16">
            <path d="M5 12h14M13 6l6 6-6 6"/>
          </svg>
        </button>
      </div>
    </div>
  );
}

window.Chat = Chat;
