// js/chat-widget.js
// Front-end logic with minimize + typing indicator + session logging

document.addEventListener('DOMContentLoaded', () => {
  const bot         = document.getElementById('ace-chatbot');
  const btnToggle   = document.getElementById('ace-chatbot-toggle');
  const btnMinimize = document.getElementById('ace-chatbot-minimize');
  const btnClose    = document.getElementById('ace-chatbot-close');
  const contactSec  = document.getElementById('ace-contact-section');
  const contactForm = document.getElementById('ace-contact-form');
  const emailInput  = document.getElementById('ace-contact-email');
  const phoneInput  = document.getElementById('ace-contact-phone');
  const bodyArea    = document.getElementById('ace-chatbot-body');
  const chatForm    = document.getElementById('ace-chatbot-form');
  const chatInput   = document.getElementById('ace-chatbot-input');

  let chatId = sessionStorage.getItem('ace_chatId') || '';
  let email  = sessionStorage.getItem('ace_email')  || '';
  let phone  = sessionStorage.getItem('ace_phone')  || '';
  let history = [];

  const scrollBottom = () => { bodyArea.scrollTop = bodyArea.scrollHeight; };
  const addMessage   = (txt, from='bot') => {
    const wrap = document.createElement('div');
    wrap.className = `ace-chatbot-message ${from}`;
    wrap.innerHTML = `<span>${txt}</span>`;
    bodyArea.appendChild(wrap);
    scrollBottom();
  };

  // Open/close widget
  btnToggle.addEventListener('click', () => bot.classList.toggle('d-none'));
  btnClose.addEventListener('click',  () => bot.classList.add('d-none'));

  // Minimize/unminimize
  btnMinimize.addEventListener('click', () => {
    bot.classList.toggle('minimized');
  });

  // Skip form if contact info exists
  if (email && phone) {
    contactSec.classList.add('d-none');
    bodyArea.classList.remove('d-none');
    chatForm.classList.remove('d-none');
    addMessage('Hi 👋 I’m your Social Link Scraper assistant. How can I help you today?');
  }

  // Contact form submission
  contactForm.addEventListener('submit', e => {
    e.preventDefault();
    email = emailInput.value.trim();
    phone = phoneInput.value.trim();
    if (!email || !phone) return;
    sessionStorage.setItem('ace_email', email);
    sessionStorage.setItem('ace_phone', phone);
    contactSec.classList.add('d-none');
    bodyArea.classList.remove('d-none');
    chatForm.classList.remove('d-none');
    addMessage('Hi 👋 I’m your Social Link Scraper assistant. How can I help you today?');
  });

  // Chat message submission with typing indicator
  chatForm.addEventListener('submit', async e => {
    e.preventDefault();
    const text = chatInput.value.trim();
    if (!text) return;
    addMessage(text, 'user');
    chatInput.value = '';

    // Insert typing indicator
    const typingEl = document.createElement('div');
    typingEl.className = 'ace-typing-indicator bot';
    typingEl.innerHTML = `
      <span class="dot"></span>
      <span class="dot"></span>
      <span class="dot"></span>
    `;
    bodyArea.appendChild(typingEl);
    scrollBottom();

    const payload = { email, phone, message: text, history, chatId };

    try {
      const res = await fetch('chat.php', {
        method: 'POST',
        headers:{ 'Content-Type':'application/json' },
        body: JSON.stringify(payload)
      });
      const data = await res.json();

      // Remove typing indicator
      typingEl.remove();

      // Persist chatId
      if (data.chatId) {
        chatId = data.chatId;
        sessionStorage.setItem('ace_chatId', chatId);
      }

      // Show bot reply
      addMessage(data.reply, 'bot');
      history.push({ user:text, bot:data.reply });
    } catch (err) {
      typingEl.remove();
      addMessage('Network error – please try again later.', 'bot');
      console.error(err);
    }
  });
});
