<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8" />

  <meta name="viewport" content="width=device-width, initial-scale=1.0" />

  <title>Edge AI Chatbot</title>

  <style>

    * { box-sizing: border-box; }

    body {

      font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;

      background: #090d16;

      color: #f1f5f9;

      margin: 0;

      display: flex;

      justify-content: center;

      align-items: center;

      min-height: 100vh;

      padding: 1rem;

    }

    .chat-box {

      background: #111827;

      border: 1px solid #1f2937;

      border-radius: 12px;

      width: 100%;

      max-width: 520px;

      height: 80vh;

      display: flex;

      flex-direction: column;

      box-shadow: 0 20px 25px -5px rgba(0,0,0,0.5);

    }

    .header {

      padding: 1rem 1.25rem;

      border-bottom: 1px solid #374151;

      font-weight: bold;

      color: #f97316;

      display: flex;

      justify-content: space-between;

      align-items: center;

    }

    .badge {

      font-size: 0.75rem;

      background: #1f2937;

      border: 1px solid #374151;

      padding: 0.2rem 0.5rem;

      border-radius: 4px;

      color: #94a3b8;

    }

    .messages {

      flex: 1;

      padding: 1rem;

      overflow-y: auto;

      display: flex;

      flex-direction: column;

      gap: 0.75rem;

    }

    .msg {

      max-width: 82%;

      padding: 0.7rem 1rem;

      border-radius: 8px;

      font-size: 0.9rem;

      line-height: 1.4;

      white-space: pre-wrap;

    }

    .user { align-self: flex-end; background: #2563eb; color: #fff; }

    .assistant { align-self: flex-start; background: #1e293b; color: #e2e8f0; border: 1px solid #334155; }

    .input-row { display: flex; padding: 0.75rem; border-top: 1px solid #1f2937; gap: 0.5rem; }

    input {

      flex: 1;

      background: #030712;

      border: 1px solid #374151;

      color: #fff;

      padding: 0.65rem 0.9rem;

      border-radius: 6px;

      outline: none;

    }

    input:focus { border-color: #f97316; }

    button {

      background: #f97316;

      border: none;

      color: #fff;

      padding: 0 1.2rem;

      border-radius: 6px;

      font-weight: bold;

      cursor: pointer;

    }

    button:disabled { opacity: 0.5; }

  </style>

</head>

<body>

  <div class="chat-box">

    <div class="header">

      <span>🤖 Portfolio Assistant</span>

      <span class="badge">Pages Frontend</span>

    </div>

    <div class="messages" id="msgs">

      <div class="msg assistant">Hi! This frontend is served by Cloudflare Pages, calling a Worker on the backend.</div>

    </div>

    <form class="input-row" id="chatForm">

      <input id="prompt" type="text" placeholder="Type a message..." required autocomplete="off" />

      <button id="sendBtn" type="submit">Send</button>

    </form>

  </div>


  <script>

    const form = document.getElementById('chatForm');

    const input = document.getElementById('prompt');

    const sendBtn = document.getElementById('sendBtn');

    const msgs = document.getElementById('msgs');

    let history = [];


    function appendMessage(role, text) {

      const el = document.createElement('div');

      el.className = 'msg ' + role;

      el.textContent = text;

      msgs.appendChild(el);

      msgs.scrollTop = msgs.scrollHeight;

      return el;

    }


    form.onsubmit = async (e) => {

      e.preventDefault();

      const val = input.value.trim();

      if (!val) return;


      appendMessage('user', val);

      history.push({ role: 'user', content: val });

      input.value = '';

      input.disabled = true;

      sendBtn.disabled = true;


      const aiMsg = appendMessage('assistant', '...');


      try {

        const res = await fetch('/chatbot/api', {

          method: 'POST',

          headers: { 'Content-Type': 'application/json' },

          body: JSON.stringify({ messages: history })

        });


        aiMsg.textContent = '';

        const reader = res.body.getReader();

        const decoder = new TextDecoder();

        let fullReply = '';


        while (true) {

          const { done, value } = await reader.read();

          if (done) break;


          const chunk = decoder.decode(value, { stream: true });

          const lines = chunk.split('\\n');


          for (const line of lines) {

            if (line.startsWith('data: ')) {

              const dataStr = line.replace('data: ', '').trim();

              if (dataStr === '[DONE]') continue;

              try {

                const parsed = JSON.parse(dataStr);

                if (parsed.response) {

                  fullReply += parsed.response;

                  aiMsg.textContent = fullReply;

                  msgs.scrollTop = msgs.scrollHeight;

                }

              } catch (_) {}

            }

          }

        }

        history.push({ role: 'assistant', content: fullReply });

      } catch (err) {

        aiMsg.textContent = 'Error: ' + err.message;

      } finally {

        input.disabled = false;

        sendBtn.disabled = false;

        input.focus();

      }

    };

  </script>

</body>

</html>