/* ============================================================================
   CA Automator — public landing-page chatbot widget.

   Talks only to /api/public/chat/* (server/site_chat.py) — no auth, no
   client data, ever. If the server reports the assistant isn't configured
   (no ANTHROPIC_API_KEY), the whole widget stays hidden rather than
   showing a broken chat button — same "blank until configured" convention
   as the payment gateways elsewhere in this app.
   ========================================================================= */
(function () {
  'use strict';

  const esc = s => String(s == null ? '' : s)
    .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');

  const SESSION_KEY = 'ca_chat_session';
  function sessionToken() {
    let t = localStorage.getItem(SESSION_KEY);
    if (!t) {
      t = (crypto.randomUUID ? crypto.randomUUID() : String(Date.now()) + Math.random()).replace(/-/g, '');
      localStorage.setItem(SESSION_KEY, t);
    }
    return t;
  }

  const GREETING = "Hi, I'm the CA Automator assistant. I can tell you about our services, help you " +
    "book a consultation, or point you to the right page — what can I help with?";

  let opened = false;
  let userTurns = 0;
  let sending = false;

  function addBubble(role, text) {
    const box = document.getElementById('chat-messages');
    if (!box) return;
    const div = document.createElement('div');
    div.className = 'chat-bubble chat-' + role;
    div.textContent = text;
    box.appendChild(div);
    box.scrollTop = box.scrollHeight;
  }

  function addTyping() {
    const box = document.getElementById('chat-messages');
    if (!box) return;
    const div = document.createElement('div');
    div.className = 'chat-bubble chat-assistant chat-typing';
    div.id = 'chat-typing-indicator';
    div.innerHTML = '<span></span><span></span><span></span>';
    box.appendChild(div);
    box.scrollTop = box.scrollHeight;
  }
  function removeTyping() {
    const el = document.getElementById('chat-typing-indicator');
    if (el) el.remove();
  }

  async function sendMessage(text) {
    text = text.trim();
    if (!text || sending) return;
    sending = true;
    addBubble('user', text);
    userTurns++;
    addTyping();
    try {
      const res = await fetch('/api/public/chat/message', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ session_token: sessionToken(), message: text })
      });
      const data = await res.json();
      removeTyping();
      if (!res.ok) {
        addBubble('assistant', data.error || "Sorry, something went wrong — please try the contact form instead.");
      } else {
        addBubble('assistant', data.reply);
      }
    } catch (e) {
      removeTyping();
      addBubble('assistant', "Sorry, I couldn't reach the server — please try again or use the contact form.");
    }
    sending = false;
    // After a couple of real exchanges, offer (never force) the lead form —
    // the form itself explains why before asking for anything.
    const form = document.getElementById('chat-lead-form');
    if (userTurns === 2 && form && form.hidden && !form.dataset.submitted) {
      form.hidden = false;
    }
  }

  function wireQuickActions() {
    document.querySelectorAll('[data-chat-goto]').forEach(btn => {
      btn.addEventListener('click', () => { location.href = btn.dataset.chatGoto; });
    });
  }

  function wireLeadForm() {
    const form = document.getElementById('chat-lead-form');
    if (!form) return;
    document.getElementById('chat-lead-skip').addEventListener('click', () => { form.hidden = true; });
    form.addEventListener('submit', async e => {
      e.preventDefault();
      const msgEl = document.getElementById('chat-lead-msg');
      const name = document.getElementById('chat-lead-name').value.trim();
      const email = document.getElementById('chat-lead-email').value.trim();
      const phone = document.getElementById('chat-lead-phone').value.trim();
      const company = document.getElementById('chat-lead-company').value.trim();
      if (!name || !email) { msgEl.textContent = 'Name and email are required.'; return; }
      msgEl.textContent = 'Sending…';
      try {
        const res = await fetch('/api/public/chat/lead', {
          method: 'POST', headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ session_token: sessionToken(), name, email, phone, company })
        });
        const data = await res.json();
        if (!res.ok) { msgEl.textContent = data.error || 'Something went wrong.'; return; }
        form.dataset.submitted = '1';
        form.hidden = true;
        addBubble('assistant', "Thanks, " + name.split(' ')[0] + " — our team has your details and will follow up shortly.");
      } catch (e) {
        msgEl.textContent = "Couldn't reach the server — please try again.";
      }
    });
  }

  function openPanel() {
    const panel = document.getElementById('chat-panel');
    const fab = document.getElementById('chat-fab');
    if (!panel) return;
    panel.hidden = false;
    fab.setAttribute('aria-expanded', 'true');
    document.getElementById('chat-fab-badge').hidden = true;
    if (!opened) {
      opened = true;
      addBubble('assistant', GREETING);
      document.getElementById('chat-input').focus();
    }
  }
  function closePanel() {
    const panel = document.getElementById('chat-panel');
    if (panel) panel.hidden = true;
    document.getElementById('chat-fab').setAttribute('aria-expanded', 'false');
  }

  function init() {
    fetch('/api/public/chat/status').then(r => r.json()).then(data => {
      if (!data.configured) return;   // stays hidden — no broken widget shown
      const widget = document.getElementById('chat-widget');
      if (widget) widget.hidden = false;

      document.getElementById('chat-fab').addEventListener('click', () => {
        const panel = document.getElementById('chat-panel');
        if (panel.hidden) openPanel(); else closePanel();
      });
      document.getElementById('chat-close').addEventListener('click', closePanel);
      document.getElementById('chat-input-row').addEventListener('submit', e => {
        e.preventDefault();
        const input = document.getElementById('chat-input');
        const text = input.value;
        input.value = '';
        sendMessage(text);
      });
      wireQuickActions();
      wireLeadForm();
    }).catch(() => { /* chatbot is optional — never block the landing page on it */ });
  }

  if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);
  else init();
})();
