// Toggle chatbot visibility
function toggleChatbot() {
  const chatbot = document.getElementById('chatbot-window');
  if (!chatbot) return;
  chatbot.style.display = chatbot.style.display === 'flex' ? 'none' : 'flex';
}

// Add message to chat
function addMessage(text, type = 'bot') {
  const messages = document.getElementById('chat-messages');
  if (!messages) return;

  const msg = document.createElement('div');
  msg.className = 'message ' + (type === 'user' ? 'user-message' : 'bot-message');
  msg.textContent = text;
  messages.appendChild(msg);

  // Scroll to bottom
  messages.scrollTop = messages.scrollHeight;
}

// Send message to PHP backend
async function sendMessage() {
  const input = document.getElementById('chat-input-field');
  if (!input) return;

  const text = input.value.trim();
  if (!text) return;

  addMessage(text, 'user');
  input.value = '';

  try {
    const response = await fetch('/ai_chat_action.php', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ message: text })
    });

    const data = await response.json();
    const reply = data.reply || '⚠️ No response from the assistant.';
    addMessage(reply, 'bot');

  } catch (err) {
    console.error('Chatbot error:', err);
    addMessage('❌ Failed to reach the server. Please try again.', 'bot');
  }
}

// Optional: Auto-open chatbot on mobile
document.addEventListener("DOMContentLoaded", () => {
  if (window.innerWidth <= 480) {
    toggleChatbot(); // Auto open on small screens
  }

  // Optionally, add "Enter" key support
  const input = document.getElementById('chat-input-field');
  if (input) {
    input.addEventListener('keydown', function (e) {
      if (e.key === 'Enter') {
        sendMessage();
      }
    });
  }
});
