(function(){
  const root = document.getElementById('chat-widget-root') || document.body;
  const cfg = window.OPENAI_CHAT_WIDGET_CONFIG || {};
  const endpoint = cfg.endpoint || '/api/chat.php';
  const title = cfg.title || 'AI Assistant';
  const subtitle = cfg.subtitle || '';
  const btn = document.createElement('button');
  btn.id = 'ai-chat-toggle'; btn.innerText = '💬'; btn.title = 'Buka Chat AI';
  root.appendChild(btn);
  const panel = document.createElement('div');
  panel.id = 'ai-chat-panel';
  panel.innerHTML = `
    <div id="ai-chat-header">
      <div class="title">${escapeHtml(title)}</div>
      <div class="subtitle">${escapeHtml(subtitle)}</div>
    </div>
    <div id="ai-chat-body"></div>
    <div id="ai-chat-inputbar">
      <input id="ai-chat-input" type="text" placeholder="Tulis pesan dan Enter..." />
      <button id="ai-chat-send">Kirim</button>
    </div>`;
  root.appendChild(panel);
  const body = panel.querySelector('#ai-chat-body');
  const input = panel.querySelector('#ai-chat-input');
  const send = panel.querySelector('#ai-chat-send');
  btn.addEventListener('click', ()=>{
    const visible = panel.style.display === 'flex';
    panel.style.display = visible ? 'none' : 'flex';
    if (!visible) input.focus();
  });
  function addMessage(role, text){
    const m = document.createElement('div'); m.className='message '+role;
    const b = document.createElement('div'); b.className='bubble'; b.innerText=text;
    m.appendChild(b); body.appendChild(m); body.scrollTop = body.scrollHeight;
  }
  function setTyping(show){
    let el = document.getElementById('typing');
    if (show){ if(!el){ el=document.createElement('div'); el.id='typing'; el.textContent='Mengetik...'; body.appendChild(el);} }
    else { if(el) el.remove(); }
    body.scrollTop = body.scrollHeight;
  }
  async function sendMessage(){
    const text = input.value.trim(); if(!text) return;
    addMessage('user', text); input.value=''; setTyping(true);
    try{
      const res = await fetch(endpoint, { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({message:text}) });
      const data = await res.json(); setTyping(false);
      if(!data.ok){ addMessage('assistant', '⚠️ Terjadi kesalahan: '+(data.error||'Unknown error')); console.error(data.detail||data); return; }
      addMessage('assistant', data.message);
    }catch(e){ setTyping(false); addMessage('assistant','⚠️ Gagal terhubung ke server.'); console.error(e); }
  }
  input.addEventListener('keydown', e=>{ if(e.key==='Enter'){ e.preventDefault(); sendMessage(); }});
  send.addEventListener('click', sendMessage);
  function escapeHtml(str){ return String(str).replace(/[&<>"']/g, s=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[s])); }
})();