<!DOCTYPE html>

<html lang="it">

<head>

  <meta charset="UTF-8">

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

  <title>Chat con Claude (Proxy)</title>

  <style>

    body { max-width: 800px; margin: 20px auto; font-family: system-ui; }

    #chat { border: 1px solid #ccc; height: 400px; overflow-y: auto; padding: 10px; margin-bottom: 10px; background: #f9f9f9; }

    .msg { margin: 8px 0; padding: 8px; border-radius: 8px; }

    .user { background: #d1ecf1; text-align: right; }

    .claude { background: #e2e3e5; text-align: left; }

    input { width: calc(100% - 80px); padding: 10px; }

    button { padding: 10px 20px; }

  </style>

</head>

<body>

  <h1>Claude Chat (via proxy)</h1>

  <div id="chat"></div>

  <input type="text" id="message" placeholder="Scrivi un messaggio..." />

  <button onclick="sendMessage()">Invia</button>


  <script>

    // !! Sostituisci con il tuo vero URL del Worker !!

    const PROXY_URL = 'https://proxy.tuodominio.com/v1/messages';


    function appendMessage(role, text) {

      const chatDiv = document.getElementById('chat');

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

      div.className = 'msg ' + (role === 'user' ? 'user' : 'claude');

      div.innerHTML = '<strong>' + (role === 'user' ? 'Tu' : 'Claude') + ':</strong> ' + text;

      chatDiv.appendChild(div);

      chatDiv.scrollTop = chatDiv.scrollHeight;

    }


    async function sendMessage() {

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

      const message = input.value.trim();

      if (!message) return;


      appendMessage('user', message);

      input.value = '';


      try {

        const response = await fetch(PROXY_URL, {

          method: 'POST',

          headers: {

            'Content-Type': 'application/json',

            'anthropic-version': '2023-06-01'   // se vuoi, anche se il Worker lo forza

          },

          body: JSON.stringify({

            model: 'claude-3-5-sonnet-20241022',   // modello aggiornato

            max_tokens: 1024,

            messages: [{ role: 'user', content: message }],

            stream: true   // ATTIVA LO STREAMING

          })

        });


        if (!response.ok) {

          const err = await response.text();

          appendMessage('claude', 'Errore: ' + err);

          return;

        }


        // Gestione streaming: leggi i chunk SSE

        const reader = response.body.getReader();

        const decoder = new TextDecoder();

        let buffer = '';


        appendMessage('claude', ''); // placeholder per il messaggio in arrivo

        const lastMsgDiv = document.querySelector('#chat .msg:last-child');

        // Rimuovi il contenuto precedente per poi aggiungere man mano

        lastMsgDiv.innerHTML = '<strong>Claude:</strong> <span id="stream-text"></span>';

        const streamSpan = document.getElementById('stream-text');


        while (true) {

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

          if (done) break;


          buffer += decoder.decode(value, { stream: true });

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

          buffer = lines.pop() || ''; // l'ultimo pezzo incompleto rimane nel buffer


          for (const line of lines) {

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

              const data = line.slice(6);

              if (data === '[DONE]') break;

              try {

                const json = JSON.parse(data);

                if (json.type === 'content_block_delta' && json.delta?.text) {

                  streamSpan.textContent += json.delta.text;

                }

              } catch (e) {

                // non è JSON valido, ignora

              }

            }

          }

        }

      } catch (error) {

        appendMessage('claude', 'Errore di rete: ' + error.message);

      }

    }

  </script>

</body>

</html>