<!DOCTYPE html>

<html lang="ru">

<head>

    <meta charset="UTF-8">

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

    <title>Генератор идей</title>

    <style>

        * {

            box-sizing: border-box;

        }

        body {

            margin: 0;

            padding: 20px;

            font-family: 'Helvetica Neue', Arial, sans-serif;

            background: transparent;

        }

    </style>

</head>

<body>


<div id="chat-widget" style="max-width: 600px; margin: 0 auto;">

  <div style="background: #000; color: #fff; padding: 20px; border-radius: 8px 8px 0 0;">

    <h3 style="margin: 0; font-size: 18px; font-weight: 500;">Генератор идей</h3>

  </div>

  

  <div id="chat-messages" style="background: #f7f7f7; height: 400px; overflow-y: auto; padding: 20px; border-left: 1px solid #e0e0e0; border-right: 1px solid #e0e0e0;">

    <div class="message bot-message" style="margin-bottom: 15px;">

      <div style="background: #fff; padding: 12px 16px; border-radius: 8px; display: inline-block; max-width: 80%; box-shadow: 0 1px 2px rgba(0,0,0,0.1);">

        Привет. Я - генератор идей. Начнем

      </div>

    </div>

  </div>

  

  <div style="background: #fff; padding: 15px; border-radius: 0 0 8px 8px; border: 1px solid #e0e0e0; border-top: none;">

    <div style="display: flex; gap: 10px;">

      <input 

        type="text" 

        id="chat-input" 

        placeholder="Напишите ответ..."

        style="flex: 1; padding: 12px 16px; border: 1px solid #e0e0e0; border-radius: 6px; font-size: 14px; outline: none;"

      />

      <button 

        id="chat-send" 

        style="background: #000; color: #fff; border: none; padding: 12px 24px; border-radius: 6px; cursor: pointer; font-size: 14px; font-weight: 500;"

      >

        Отправить

      </button>

    </div>

  </div>

  

  <div id="typing-indicator" style="display: none; padding: 10px 20px; font-size: 12px; color: #999;">

    Генератор думает...

  </div>

</div>


<script>

(function() {

  const API_URL = 'https://plainfrog-5107.torbichev.workers.dev';

  

  let sessionId = localStorage.getItem('chat_session_id');

  if (!sessionId) {

    sessionId = 'session_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);

    localStorage.setItem('chat_session_id', sessionId);

  }

  

  const chatHistory = JSON.parse(localStorage.getItem('chat_history') || '[]');

  const messagesContainer = document.getElementById('chat-messages');

  const input = document.getElementById('chat-input');

  const sendBtn = document.getElementById('chat-send');

  const typingIndicator = document.getElementById('typing-indicator');

  

  if (chatHistory.length > 1) {

    messagesContainer.innerHTML = '';

    chatHistory.forEach(msg => addMessage(msg.text, msg.isUser, false));

  }

  

  function addMessage(text, isUser = false, saveToHistory = true) {

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

    messageDiv.style.marginBottom = '15px';

    messageDiv.style.textAlign = isUser ? 'right' : 'left';

    

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

    bubble.style.background = isUser ? '#000' : '#fff';

    bubble.style.color = isUser ? '#fff' : '#000';

    bubble.style.padding = '12px 16px';

    bubble.style.borderRadius = '8px';

    bubble.style.display = 'inline-block';

    bubble.style.maxWidth = '80%';

    bubble.style.boxShadow = '0 1px 2px rgba(0,0,0,0.1)';

    bubble.style.wordWrap = 'break-word';

    bubble.style.whiteSpace = 'pre-wrap';

    bubble.textContent = text;

    

    messageDiv.appendChild(bubble);

    messagesContainer.appendChild(messageDiv);

    messagesContainer.scrollTop = messagesContainer.scrollHeight;

    

    if (saveToHistory) {

      chatHistory.push({ text, isUser });

      localStorage.setItem('chat_history', JSON.stringify(chatHistory));

    }

  }

  

  async function sendMessage() {

    const message = input.value.trim();

    if (!message) return;

    

    addMessage(message, true);

    input.value = '';

    

    typingIndicator.style.display = 'block';

    sendBtn.disabled = true;

    input.disabled = true;

    

    try {

      const response = await fetch(API_URL, {

        method: 'POST',

        headers: {

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

        },

        body: JSON.stringify({

          chatInput: message,

          sessionId: sessionId

        })

      });

      

      if (!response.ok) {

        throw new Error('HTTP ' + response.status);

      }

      

      const data = await response.json();

      typingIndicator.style.display = 'none';

      

      const botResponse = data.response || data.output || 'Ошибка получения ответа';

      addMessage(botResponse, false);

      

      if (data.isComplete && data.ideas) {

        setTimeout(() => displayIdeas(data.ideas), 500);

      }

      

    } catch (error) {

      console.error('Ошибка:', error);

      typingIndicator.style.display = 'none';

      addMessage('Произошла ошибка соединения.', false);

    } finally {

      sendBtn.disabled = false;

      input.disabled = false;

      input.focus();

    }

  }

  

  function displayIdeas(ideas) {

    let text = '🎯 Ваши ТОП-10 идей:\n\n';

    if (Array.isArray(ideas)) {

      ideas.forEach((idea, i) => {

        text += `${i+1}. ${idea.name}\n${idea.description}\n💰 ${idea.monthly_revenue_potential}₽/мес | ⏱ ${idea.estimated_hours}ч\n\n`;

      });

    }

    addMessage(text, false);

  }

  

  sendBtn.addEventListener('click', sendMessage);

  input.addEventListener('keypress', (e) => {

    if (e.key === 'Enter') sendMessage();

  });

  

  input.focus();

})();

</script>


</body>

</html>