/* ============================================================
   Gmind Institute — Chat Widget JavaScript
   Vanilla ES2022, no jQuery, no dependencies
   ============================================================ */

(() => {
  'use strict';

  const BASE = document.querySelector('meta[name="base-path"]')?.content || '/gmind';

  // Admin-configured welcome message (passed from footer.php via window.GMIND_CHAT_CONFIG).
  // Fallback to the previous hardcoded message if the admin setting is missing.
  const WELCOME_MESSAGE =
    (window.GMIND_CHAT_CONFIG && window.GMIND_CHAT_CONFIG.welcomeMessage) ||
    'Hello! Welcome to Gmind Institute. How can we help you today?';

  // ─── State ──────────────────────────────────────────────
  let conversationId = null;
  let lastMsgId = 0;
  let pollTimer = null;
  let isOpen = false;
  let isInitialized = false;

  // ─── DOM References ─────────────────────────────────────
  const toggle = document.getElementById('chatToggle');
  const window_ = document.getElementById('chatWindow');
  const body = document.getElementById('chatBody');
  const input = document.getElementById('chatInput');
  const sendBtn = document.getElementById('chatSendBtn');
  const preForm = document.getElementById('chatPreForm');
  const chatMain = document.getElementById('chatMain');
  const typingEl = document.getElementById('chatTyping');
  const nameInput = document.getElementById('chatNameInput');
  const emailInput = document.getElementById('chatEmailInput');
  const startBtn = document.getElementById('chatStartBtn');
  const badge = document.getElementById('chatUnreadBadge');
  const closeBtn = document.getElementById('chatWindowClose');

  if (!toggle || !window_) return; // Widget not loaded

  // ─── Toggle Chat Window ─────────────────────────────────
  function openChat() {
    isOpen = true;
    window_.classList.add('open');
    toggle.classList.add('active');
    toggle.classList.remove('has-unread');
    if (badge) badge.style.display = 'none';

    if (!isInitialized) {
      preForm.style.display = 'flex';
      chatMain.style.display = 'none';
      nameInput?.focus();
    } else {
      preForm.style.display = 'none';
      chatMain.style.display = 'flex';
      input?.focus();
      scrollToBottom();
      // Resume polling for admin replies whenever the visitor reopens the chat
      startPolling();
    }
  }

  function closeChat() {
    isOpen = false;
    window_.classList.remove('open');
    toggle.classList.remove('active');
    if (pollTimer) {
      clearInterval(pollTimer);
      pollTimer = null;
    }
  }

  toggle.addEventListener('click', () => {
    if (isOpen) closeChat();
    else openChat();
  });

  if (closeBtn) {
    closeBtn.addEventListener('click', (e) => {
      e.stopPropagation();
      closeChat();
    });
  }

  // Close chat when user presses Escape
  document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape' && isOpen) closeChat();
  });

  // ─── Start Chat (Pre-form) ──────────────────────────────
  if (startBtn) {
    startBtn.addEventListener('click', startChat);
  }

  // Enter key in pre-form inputs (with Shift+Enter for newline)
  [nameInput, emailInput].forEach(el => {
    if (!el) return;
    el.addEventListener('keydown', (e) => {
      if (e.key === 'Enter') {
        e.preventDefault();
        startChat();
      }
    });
  });

  async function startChat() {
    const name = nameInput?.value?.trim() || '';
    const email = emailInput?.value?.trim() || '';

    startBtn.disabled = true;
    startBtn.textContent = 'Starting...';

    try {
      const formData = new FormData();
      if (name) formData.append('name', name);
      if (email) formData.append('email', email);

      const res = await fetch(`${BASE}/chat/init`, {
        method: 'POST',
        body: formData,
      });

      if (!res.ok) {
        throw new Error(`HTTP ${res.status}`);
      }

      const data = await res.json();

      if (data.success) {
        conversationId = data.conversation.id;
        lastMsgId = data.last_id;
        isInitialized = true;

        // Show chat interface
        preForm.style.display = 'none';
        chatMain.style.display = 'flex';

        // Render existing messages (returning visitor)
        if (data.messages && data.messages.length > 0) {
          renderMessages(data.messages);
        }

        // Add welcome message if new conversation
        if (!data.messages || data.messages.length === 0) {
          addMessage('admin', WELCOME_MESSAGE, formatTime(new Date()));
        }

        input?.focus();
        startPolling();
      } else {
        throw new Error(data.error || 'Unknown error');
      }
    } catch (err) {
      console.error('Chat init error:', err);
      startBtn.disabled = false;
      startBtn.textContent = 'Start Chat';
      // Show a small error notice above the form
      const notice = document.createElement('p');
      notice.style.cssText = 'color:#FF4757; font-size:12px; text-align:center; margin:0;';
      notice.textContent = 'Could not start chat. Please try again.';
      const existing = preForm.querySelector('.chat-error-notice');
      if (existing) existing.remove();
      notice.classList.add('chat-error-notice');
      preForm.appendChild(notice);
    }
  }

  // ─── Send Message ───────────────────────────────────────
  if (sendBtn) {
    sendBtn.addEventListener('click', sendMessage);
  }

  if (input) {
    input.addEventListener('keydown', (e) => {
      if (e.key === 'Enter' && !e.shiftKey) {
        e.preventDefault();
        sendMessage();
      }
    });
  }

  async function sendMessage() {
    const message = input?.value?.trim();
    if (!message || !conversationId) return;

    // Show message immediately
    addMessage('visitor', message, formatTime(new Date()));
    input.value = '';
    input.style.height = 'auto';
    scrollToBottom();

    try {
      const formData = new FormData();
      formData.append('conversation_id', conversationId.toString());
      formData.append('message', message);

      const res = await fetch(`${BASE}/chat/send`, {
        method: 'POST',
        body: formData,
      });

      const data = await res.json();

      if (data.success) {
        lastMsgId = data.message_id;
      }
    } catch (err) {
      console.error('Chat send error:', err);
    }
  }

  // ─── Poll for New Messages ──────────────────────────────
  function startPolling() {
    if (pollTimer) clearInterval(pollTimer);

    pollTimer = setInterval(async () => {
      if (!conversationId || !isOpen) return;

      try {
        const res = await fetch(
          `${BASE}/chat/poll?conversation_id=${conversationId}&after_id=${lastMsgId}`
        );
        const data = await res.json();

        if (data.success && data.messages && data.messages.length > 0) {
          // Show typing indicator briefly
          showTyping();
          await new Promise(r => setTimeout(r, 500));
          hideTyping();

          renderMessages(data.messages);
          lastMsgId = data.last_id;
          scrollToBottom();

          // If chat is not open, show badge
          if (!isOpen) {
            toggle.classList.add('has-unread');
            if (badge) {
              const count = (parseInt(badge.textContent) || 0) + data.messages.length;
              badge.textContent = count;
              badge.style.display = 'flex';
            }
          }
        }
      } catch (err) {
        // Silently ignore polling errors
      }
    }, 4000);
  }

  // ─── Render Messages ────────────────────────────────────
  function renderMessages(messages) {
    messages.forEach(msg => {
      const existing = body?.querySelector(`[data-msg-id="${msg.id}"]`);
      if (existing) return; // Don't duplicate

      addMessage(
        msg.sender_type,
        escapeHtml(msg.message),
        formatTime(msg.created_at)
      );
    });
  }

  function addMessage(type, text, time) {
    if (!body) return;

    const div = document.createElement('div');
    div.className = `chat-msg ${type}`;
    div.innerHTML = `
      <div>${text}</div>
      <span class="chat-msg-time">${time}</span>
    `;

    // Insert before typing indicator
    if (typingEl) {
      body.insertBefore(div, typingEl);
    } else {
      body.appendChild(div);
    }

    scrollToBottom();
  }

  // ─── Typing Indicator ───────────────────────────────────
  function showTyping() {
    if (typingEl) typingEl.classList.add('visible');
  }

  function hideTyping() {
    if (typingEl) typingEl.classList.remove('visible');
  }

  // ─── Utilities ──────────────────────────────────────────
  function scrollToBottom() {
    requestAnimationFrame(() => {
      if (body) body.scrollTop = body.scrollHeight;
    });
  }

  function formatTime(dateStr) {
    const d = new Date(dateStr);
    return d.toLocaleTimeString('en-IN', { hour: '2-digit', minute: '2-digit', hour12: true });
  }

  function escapeHtml(str) {
    const div = document.createElement('div');
    div.textContent = str;
    return div.innerHTML;
  }

  // ─── Auto-resize textarea ───────────────────────────────
  if (input) {
    input.addEventListener('input', () => {
      input.style.height = 'auto';
      input.style.height = Math.min(input.scrollHeight, 80) + 'px';
    });
  }

})();
