<div id="hw-chat-widget" class="fixed bottom-6 right-6 z-50">
  <button id="hw-chat-toggle" class="bg-shining-green text-white px-4 py-3 rounded-full shadow-lg">Chat</button>
  <div id="hw-chat-panel" class="hidden w-96 max-w-full bg-white rounded-2xl shadow-2xl overflow-hidden mt-3">
    <div class="p-4 border-b flex items-center justify-between">
      <strong>A Taste of Africa — Assistant</strong>
      <button id="hw-chat-close" class="text-sm text-gray-500">Close</button>
    </div>
    <div id="hw-chat-messages" class="p-4 h-64 overflow-y-auto space-y-3 bg-[#f7faf7]"></div>
    <div class="p-4 border-t">
      <textarea id="hw-chat-input" rows="2" class="w-full p-3 border rounded-md" placeholder="Ask something about the marketplace or request a summary..."></textarea>
      <div class="mt-2 flex items-center gap-3">
        <label class="flex items-center gap-2 text-sm text-gray-500"><input type="checkbox" id="hw-chat-save" /> <span>Save conversation</span></label>
        <button id="hw-chat-history" class="text-sm text-gray-500 underline ml-auto">History</button>
        <div>
          <button id="hw-chat-send" class="bg-shining-green text-white px-4 py-2 rounded-md">Send</button>
        </div>
      </div>
      <div id="hw-chat-history-panel" class="hidden p-3 border-t bg-white max-h-56 overflow-y-auto"></div>
    </div>
  </div>
</div>

<script>
(function(){
  const toggle = document.getElementById('hw-chat-toggle');
  const panel = document.getElementById('hw-chat-panel');
  const closeBtn = document.getElementById('hw-chat-close');
  const send = document.getElementById('hw-chat-send');
  const input = document.getElementById('hw-chat-input');
  const msgs = document.getElementById('hw-chat-messages');

  function appendMessage(text, cls) {
    const d = document.createElement('div');
    d.className = cls + ' p-3 rounded-md';
    d.textContent = text;
    msgs.appendChild(d);
    msgs.scrollTop = msgs.scrollHeight;
  }

  toggle.addEventListener('click', () => panel.classList.toggle('hidden'));
  closeBtn.addEventListener('click', () => panel.classList.add('hidden'));

  // History panel toggle
  document.getElementById('hw-chat-history').addEventListener('click', async () => {
    const hpanel = document.getElementById('hw-chat-history-panel');
    if (!hpanel.classList.contains('hidden')) { hpanel.classList.add('hidden'); return; }
    hpanel.innerHTML = 'Loading...';
    hpanel.classList.remove('hidden');
    try {
      const res = await fetch('/files/atasteofafricanmarketplace/api/ai/conversations.php', { credentials: 'include' });
      const data = await res.json();
      if (!res.ok) { hpanel.innerHTML = '<div class="text-sm text-red-500">Error loading history</div>'; return; }
      if (!data.conversations || data.conversations.length === 0) { hpanel.innerHTML = '<div class="text-sm text-gray-500">No saved conversations</div>'; return; }
      hpanel.innerHTML = data.conversations.map(c => `
        <div class="p-2 border-b text-sm flex items-start justify-between" data-id="${c.id}">
          <div class="flex-1">
            <strong>${escapeHtml(c.title||'Untitled')}</strong>
            <div class="text-xs text-gray-400">${c.created_at}</div>
          </div>
          <div class="ml-3 flex gap-2">
            <button class="hw-conv-view text-xs text-blue-500">View</button>
            <button class="hw-conv-rename text-xs text-gray-600">Rename</button>
            <button class="hw-conv-delete text-xs text-red-500">Delete</button>
          </div>
        </div>
      `).join('');

      // attach delegated listeners
      hpanel.querySelectorAll('.hw-conv-view').forEach(b => b.addEventListener('click', async (ev) => {
        const id = ev.target.closest('[data-id]').dataset.id;
        const r = await fetch('/files/atasteofafricanmarketplace/api/ai/conversations.php?id='+encodeURIComponent(id), { credentials: 'include' });
        const d = await r.json();
        if (!r.ok) { alert(d.message || 'Failed to load'); return; }
        // render messages in main panel
        msgs.innerHTML = '';
        (d.conversation.messages || []).forEach(m => appendMessage(`${m.role}: ${m.content}`, 'bg-white'));
        hpanel.classList.add('hidden');
      }));

      hpanel.querySelectorAll('.hw-conv-rename').forEach(b => b.addEventListener('click', async (ev) => {
        const row = ev.target.closest('[data-id]');
        const id = row.dataset.id;
        const current = row.querySelector('strong').textContent || 'Untitled';
        const title = prompt('Rename conversation', current);
        if (title === null) return;
        const res2 = await fetch('/files/atasteofafricanmarketplace/api/ai/conversations.php?id='+encodeURIComponent(id), {
          method: 'PATCH',
          credentials: 'include',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ title })
        });
        const j2 = await res2.json();
        if (!res2.ok) { alert(j2.message || 'Rename failed'); return; }
        // refresh list
        document.getElementById('hw-chat-history').click();
      }));

      hpanel.querySelectorAll('.hw-conv-delete').forEach(b => b.addEventListener('click', async (ev) => {
        const id = ev.target.closest('[data-id]').dataset.id;
        if (!confirm('Delete this conversation? This cannot be undone.')) return;
        const res3 = await fetch('/files/atasteofafricanmarketplace/api/ai/conversations.php?id='+encodeURIComponent(id), { method: 'DELETE', credentials: 'include' });
        const j3 = await res3.json();
        if (!res3.ok) { alert(j3.message || 'Delete failed'); return; }
        // refresh list
        document.getElementById('hw-chat-history').click();
      }));

    appendMessage(text, 'bg-white text-right');
    input.value = '';
    appendMessage('...', 'bg-gray-100');

    const save = document.getElementById('hw-chat-save').checked;
    const messagesPayload = [{ role: 'user', content: text }];

    try {
      const res = await fetch('/files/atasteofafricanmarketplace/api/ai/chat.php', {
        method: 'POST', headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({ message: text })
      });
      const data = await res.json();
      // remove last loading message
      const last = msgs.lastChild;
      if (last && last.textContent === '...') last.remove();
      if (!res.ok) {
        appendMessage(data.message || 'Error from server', 'bg-red-100 text-red-700');
      } else {
        appendMessage(data.message || data?.message || 'No response', 'bg-gray-50');
        // if user opted to save conversation, POST to conversations endpoint
        if (save) {
          try {
            await fetch('/files/atasteofafricanmarketplace/api/ai/conversations.php', {
              method: 'POST', headers: { 'Content-Type': 'application/json' },
              credentials: 'include',
              body: JSON.stringify({ consent: true, title: text.slice(0,80), messages: messagesPayload.concat([{ role: 'assistant', content: data.message || data?.message || '' }]) })
            });
          } catch (e) {
            console.warn('Failed to save conversation', e);
          }
        }
      }
    } catch (e) {
      appendMessage('Network error', 'bg-red-100 text-red-700');
    }
  });
})();
</script>