// Yellow Stone Traders & General Supplies — floating AI chat widget
(function () {
  const SUGGESTIONS = [
    'What services do you offer?',
    'How do I request a quote?',
    'Do you supply mining equipment?',
    'Can you build a school or dispensary?'
  ];

  function el(tag, attrs = {}, html) {
    const node = document.createElement(tag);
    Object.entries(attrs).forEach(([k, v]) => node.setAttribute(k, v));
    if (html !== undefined) node.innerHTML = html;
    return node;
  }

  document.addEventListener('DOMContentLoaded', function () {
    const sessionKey = 'yst_chat_session';
    let sessionId = null;
    try { sessionId = sessionStorage.getItem(sessionKey); } catch (e) { /* ignore */ }
    let history = [];

    const launcher = el('button', { class: 'yst-chat-launcher', 'aria-label': 'Open chat with Yellow Stone Traders & General Supplies' }, `
      <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M21 12c0 4.4-4 8-9 8-1.2 0-2.4-.2-3.4-.6L3 20l1.1-4.2A7.6 7.6 0 013 12c0-4.4 4-8 9-8s9 3.6 9 8z"/></svg>
      <span class="dot"></span>
    `);

    const panel = el('div', { class: 'yst-chat-panel', role: 'dialog', 'aria-label': 'Chat with Yellow Stone Traders & General Supplies' }, `
      <div class="yst-chat-head">
        <img src="/assets/logo.jpg" alt="">
        <div><strong>Ask Yellow Stone</strong><span>Usually replies in seconds</span></div>
        <button class="yst-chat-close" aria-label="Close chat"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M6 6l12 12M18 6L6 18"/></svg></button>
      </div>
      <div class="yst-chat-body" id="yst-chat-body"></div>
      <div class="yst-chat-suggestions" id="yst-chat-suggestions"></div>
      <form class="yst-chat-form" id="yst-chat-form">
        <input type="text" id="yst-chat-input" placeholder="Type a message…" autocomplete="off">
        <button type="submit" aria-label="Send"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M22 2L11 13"/><path d="M22 2l-7 20-4-9-9-4 20-7z"/></svg></button>
      </form>
    `);

    document.body.appendChild(launcher);
    document.body.appendChild(panel);

    const body = panel.querySelector('#yst-chat-body');
    const form = panel.querySelector('#yst-chat-form');
    const input = panel.querySelector('#yst-chat-input');
    const suggestionsWrap = panel.querySelector('#yst-chat-suggestions');

    function addMessage(role, text) {
      const msg = el('div', { class: `yst-msg ${role === 'user' ? 'user' : 'bot'}` });
      msg.textContent = text;
      body.appendChild(msg);
      body.scrollTop = body.scrollHeight;
      return msg;
    }

    function addTyping() {
      const t = el('div', { class: 'yst-msg bot typing' }, '<span></span><span></span><span></span>');
      body.appendChild(t);
      body.scrollTop = body.scrollHeight;
      return t;
    }

    function renderSuggestions() {
      suggestionsWrap.innerHTML = '';
      SUGGESTIONS.forEach((s) => {
        const chip = el('button', { type: 'button', class: 'yst-chip' }, s);
        chip.addEventListener('click', () => sendMessage(s));
        suggestionsWrap.appendChild(chip);
      });
    }

    function openPanel() {
      panel.classList.add('open');
      if (!body.childElementCount) {
        addMessage('bot', "Hi! I'm the Yellow Stone Traders & General Supplies assistant. Ask me about our construction services, mining supply, or how to request a quote.");
        renderSuggestions();
      }
      input.focus();
    }
    function closePanel() { panel.classList.remove('open'); }

    launcher.addEventListener('click', () => {
      panel.classList.contains('open') ? closePanel() : openPanel();
    });
    panel.querySelector('.yst-chat-close').addEventListener('click', closePanel);

    async function sendMessage(text) {
      const trimmed = text.trim();
      if (!trimmed) return;
      suggestionsWrap.innerHTML = '';
      addMessage('user', trimmed);
      history.push({ role: 'user', content: trimmed });
      input.value = '';

      const typingEl = addTyping();
      try {
        const resp = await fetch('/api/chat', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ messages: history, sessionId })
        });
        const data = await resp.json();
        typingEl.remove();
        if (!resp.ok) throw new Error(data.error || 'Something went wrong.');
        if (data.sessionId) {
          sessionId = data.sessionId;
          try { sessionStorage.setItem(sessionKey, sessionId); } catch (e) { /* ignore */ }
        }
        addMessage('bot', data.reply);
        history.push({ role: 'assistant', content: data.reply });
      } catch (err) {
        typingEl.remove();
        addMessage('bot', "Sorry, I couldn't reach our assistant just now. Please email info@yst.co.tz or call +255 787 094 468.");
      }
    }

    form.addEventListener('submit', (e) => {
      e.preventDefault();
      sendMessage(input.value);
    });
  });
})();
