/**
 * OffshoreAI Chat Widget
 * Drop-in floating chat untuk landing page offshoreai.biz.id
 * Pakai: <script src="chat-widget.js"></script> sebelum </body>
 * Set window.OFFSHOREAI_API_KEY = 'sk-ant-...' sebelum load script
 */
(function() {
'use strict';

// ── SYSTEM PROMPT ──
const SYSTEM = `Kamu adalah asisten AI untuk OffshoreAI (offshoreai.biz.id) — platform diagnostic berbasis AI yang melayani dua bidang utama:

**1. ICT & Network Solutions:**
- VSAT & Starlink diagnostic dan troubleshooting (marine/offshore)
- Optimasi jaringan dengan Mikrotik RouterOS, Cisco, dan router terkemuka lainnya
- Konfigurasi dan audit Firewall, NAT, load balancing, failover
- Integrasi dan troubleshooting IP Camera / CCTV / NVR
- Perangkat IoT dan PLC (Modbus, PROFIBUS, OPC-UA)
- Network security, bandwidth management, QoS

**2. Offshore Equipment Diagnostic:**
- Mooring Winch: Unidrive SP diagnostic (LIVE di mw.offshoreai.biz.id)
- Big Crane systems (coming soon)
- Tensioner machines: SAS, Remacut, Westech (coming soon)
- ECR Engine Control Room (coming soon)
- Predictive & preventive maintenance berbasis AI

**Platform yang sudah live:**
- Mooring Winch Diagnostic: https://mw.offshoreai.biz.id

**Cara kamu merespons:**
- Deteksi bahasa user dan balas dengan bahasa yang sama (Indonesia atau English)
- Untuk pertanyaan umum/bisnis: jelaskan layanan OffshoreAI dengan antusias dan profesional
- Untuk pertanyaan teknis ICT: berikan panduan troubleshooting yang konkret dan detail
- Untuk pertanyaan offshore equipment: jelaskan kemampuan diagnostic AI dan arahkan ke platform yang tersedia
- Selalu tawarkan bantuan lebih lanjut atau arahkan ke platform yang relevan
- Jawaban ringkas untuk pertanyaan umum, detail untuk pertanyaan teknis
- Jangan buat-buat informasi; jika tidak tahu, katakan dengan jujur`;

// ── INJECT STYLES ──
const style = document.createElement('style');
style.textContent = `
#oai-chat-btn {
  position: fixed; bottom: 28px; right: 28px; z-index: 9998;
  width: 58px; height: 58px; border-radius: 50%;
  background: linear-gradient(135deg, #0090c8, #00e5c0);
  border: none; cursor: pointer;
  box-shadow: 0 4px 24px rgba(0,200,255,0.35), 0 0 0 0 rgba(0,200,255,0.3);
  display: flex; align-items: center; justify-content: center;
  transition: transform .2s, box-shadow .2s;
  animation: oai-pulse 3s infinite;
}
#oai-chat-btn:hover { transform: scale(1.08); box-shadow: 0 6px 32px rgba(0,200,255,0.5); }
@keyframes oai-pulse {
  0%,100% { box-shadow: 0 4px 24px rgba(0,200,255,.35), 0 0 0 0 rgba(0,200,255,.3); }
  50% { box-shadow: 0 4px 24px rgba(0,200,255,.35), 0 0 0 10px rgba(0,200,255,0); }
}
#oai-chat-btn svg { width: 26px; height: 26px; }
#oai-chat-btn .oai-close { display: none; }
#oai-chat-btn.open .oai-open { display: none; }
#oai-chat-btn.open .oai-close { display: block; }

#oai-chat-window {
  position: fixed; bottom: 100px; right: 28px; z-index: 9999;
  width: 380px; height: 560px; max-height: calc(100vh - 120px);
  background: #050d18;
  border: 1px solid rgba(0,180,255,0.22);
  border-radius: 14px;
  display: flex; flex-direction: column;
  box-shadow: 0 24px 80px rgba(0,0,0,.7), 0 0 0 1px rgba(0,180,255,.05);
  transform: scale(.92) translateY(16px); opacity: 0; pointer-events: none;
  transition: transform .25s cubic-bezier(.34,1.56,.64,1), opacity .2s;
  font-family: 'DM Sans', -apple-system, sans-serif;
  overflow: hidden;
}
#oai-chat-window.open {
  transform: scale(1) translateY(0); opacity: 1; pointer-events: all;
}
@media (max-width: 440px) {
  #oai-chat-window { right: 10px; left: 10px; width: auto; bottom: 90px; }
  #oai-chat-btn { bottom: 18px; right: 18px; }
}

.oai-header {
  padding: 14px 16px; background: #081422;
  border-bottom: 1px solid rgba(0,180,255,.1);
  display: flex; align-items: center; gap: 10px; flex-shrink: 0;
  border-radius: 14px 14px 0 0;
}
.oai-header-icon {
  width: 34px; height: 34px; border-radius: 8px;
  background: linear-gradient(135deg,#0090c8,#00e5c0);
  display: flex; align-items: center; justify-content: center; flex-shrink: 0;
}
.oai-header-icon svg { width: 18px; height: 18px; stroke: #fff; fill: none; stroke-width: 2; }
.oai-header-title { font-size: 14px; font-weight: 600; color: #fff; line-height: 1.2; }
.oai-header-sub { font-size: 10px; color: #3a5570; font-family: 'JetBrains Mono', monospace; letter-spacing: .06em; margin-top: 1px; }
.oai-status { margin-left: auto; display: flex; align-items: center; gap: 5px; font-size: 10px; color: #6d90a8; }
.oai-dot { width: 7px; height: 7px; border-radius: 50%; background: #22c55e; box-shadow: 0 0 6px #22c55e; animation: oai-blink 2s infinite; }
@keyframes oai-blink { 0%,100%{opacity:1}50%{opacity:.4} }

.oai-messages {
  flex: 1; overflow-y: auto; padding: 16px 14px; display: flex; flex-direction: column; gap: 12px;
  scrollbar-width: thin; scrollbar-color: rgba(0,180,255,.15) transparent;
}
.oai-messages::-webkit-scrollbar { width: 4px; }
.oai-messages::-webkit-scrollbar-thumb { background: rgba(0,180,255,.15); border-radius: 4px; }

.oai-msg { display: flex; gap: 8px; align-items: flex-start; animation: oai-fadeup .3s ease; }
@keyframes oai-fadeup { from{opacity:0;transform:translateY(8px)} to{opacity:1;transform:translateY(0)} }
.oai-msg.user { flex-direction: row-reverse; }
.oai-avatar {
  width: 28px; height: 28px; border-radius: 7px; flex-shrink: 0;
  display: flex; align-items: center; justify-content: center; font-size: 13px;
}
.oai-msg.bot .oai-avatar { background: linear-gradient(135deg,#0090c8,#00e5c0); }
.oai-msg.bot .oai-avatar svg { width: 15px; height: 15px; stroke: #fff; fill: none; stroke-width: 2; }
.oai-msg.user .oai-avatar { background: #1a2235; font-size: 14px; }
.oai-bubble {
  max-width: 80%; padding: 10px 13px; border-radius: 10px;
  font-size: 13px; line-height: 1.65; color: #ccdde8;
}
.oai-msg.bot .oai-bubble { background: #0c1e35; border: 1px solid rgba(0,180,255,.1); border-radius: 3px 10px 10px 10px; }
.oai-msg.user .oai-bubble { background: #0090c8; color: #fff; border-radius: 10px 3px 10px 10px; }
.oai-bubble strong { color: #00c8ff; }
.oai-bubble a { color: #00e5c0; }
.oai-bubble code { background: rgba(0,180,255,.1); padding: 1px 5px; border-radius: 3px; font-family: monospace; font-size: 11px; color: #00c8ff; }
.oai-bubble p { margin-bottom: 6px; }
.oai-bubble p:last-child { margin-bottom: 0; }
.oai-bubble ul { padding-left: 16px; margin: 4px 0; }
.oai-bubble li { margin-bottom: 3px; }

.oai-typing { display: flex; align-items: center; gap: 4px; padding: 10px 13px; }
.oai-typing span { width: 6px; height: 6px; border-radius: 50%; background: #00c8ff; opacity: .4; animation: oai-typing .9s infinite; }
.oai-typing span:nth-child(2) { animation-delay: .2s; }
.oai-typing span:nth-child(3) { animation-delay: .4s; }
@keyframes oai-typing { 0%,60%,100%{opacity:.4;transform:translateY(0)} 30%{opacity:1;transform:translateY(-4px)} }

.oai-suggestions { padding: 0 14px 10px; display: flex; flex-wrap: wrap; gap: 6px; flex-shrink: 0; }
.oai-suggestion {
  font-size: 11px; padding: 5px 10px; border-radius: 14px;
  border: 1px solid rgba(0,180,255,.2); color: #6d90a8; background: transparent;
  cursor: pointer; transition: all .2s; white-space: nowrap;
  font-family: inherit;
}
.oai-suggestion:hover { border-color: #00c8ff; color: #00c8ff; background: rgba(0,200,255,.05); }

.oai-input-row {
  padding: 10px 12px 14px; display: flex; gap: 8px; align-items: flex-end;
  border-top: 1px solid rgba(0,180,255,.08); flex-shrink: 0;
  background: #050d18; border-radius: 0 0 14px 14px;
}
#oai-input {
  flex: 1; background: #0c1e35; border: 1px solid rgba(0,180,255,.15);
  border-radius: 8px; padding: 9px 12px; color: #ccdde8; font-size: 13px;
  font-family: inherit; resize: none; min-height: 38px; max-height: 100px;
  outline: none; transition: border-color .2s; line-height: 1.5;
  scrollbar-width: none;
}
#oai-input:focus { border-color: rgba(0,180,255,.35); }
#oai-input::placeholder { color: #3a5570; }
#oai-send {
  width: 38px; height: 38px; border-radius: 8px; flex-shrink: 0;
  background: linear-gradient(135deg,#0090c8,#00e5c0);
  border: none; cursor: pointer; display: flex; align-items: center; justify-content: center;
  transition: opacity .2s, transform .15s;
}
#oai-send:hover { opacity: .88; transform: scale(1.05); }
#oai-send:disabled { opacity: .4; cursor: not-allowed; transform: none; }
#oai-send svg { width: 16px; height: 16px; stroke: #fff; fill: none; stroke-width: 2.5; }
`;
document.head.appendChild(style);

// ── INJECT HTML ──
const btn = document.createElement('button');
btn.id = 'oai-chat-btn';
btn.setAttribute('aria-label', 'Open AI Chat');
btn.innerHTML = `
  <svg class="oai-open" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2">
    <path d="M21 15a2 2 0 01-2 2H7l-4 4V5a2 2 0 012-2h14a2 2 0 012 2z"/>
  </svg>
  <svg class="oai-close" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5">
    <line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/>
  </svg>`;
document.body.appendChild(btn);

const win = document.createElement('div');
win.id = 'oai-chat-window';
win.innerHTML = `
  <div class="oai-header">
    <div class="oai-header-icon">
      <svg viewBox="0 0 24 24"><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></svg>
    </div>
    <div>
      <div class="oai-header-title">OffshoreAI Assistant</div>
      <div class="oai-header-sub">ICT · OFFSHORE · DIAGNOSTIC</div>
    </div>
    <div class="oai-status"><div class="oai-dot"></div>Online</div>
  </div>
  <div class="oai-messages" id="oai-messages"></div>
  <div class="oai-suggestions" id="oai-suggestions">
    <button class="oai-suggestion">Apa itu OffshoreAI?</button>
    <button class="oai-suggestion">VSAT troubleshooting</button>
    <button class="oai-suggestion">Mikrotik optimization</button>
    <button class="oai-suggestion">Mooring winch diagnostic</button>
    <button class="oai-suggestion">What services do you offer?</button>
  </div>
  <div class="oai-input-row">
    <textarea id="oai-input" placeholder="Tanya tentang ICT atau offshore..." rows="1"></textarea>
    <button id="oai-send" disabled>
      <svg viewBox="0 0 24 24"><line x1="22" y1="2" x2="11" y2="13"/><polygon points="22 2 15 22 11 13 2 9 22 2"/></svg>
    </button>
  </div>`;
document.body.appendChild(win);

// ── STATE ──
const messages = [];
let isOpen = false;
let isThinking = false;

// ── HELPERS ──
function mdToHtml(text) {
  return text
    .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
    .replace(/\*(.*?)\*/g, '<em>$1</em>')
    .replace(/`(.*?)`/g, '<code>$1</code>')
    .replace(/\[([^\]]+)\]\((https?:\/\/[^\)]+)\)/g, '<a href="$2" target="_blank">$1</a>')
    .replace(/^### (.*)/gm, '<strong>$1</strong>')
    .replace(/^## (.*)/gm, '<strong>$1</strong>')
    .replace(/^- (.*)/gm, '<li>$1</li>')
    .replace(/(<li>.*<\/li>)/gs, '<ul>$1</ul>')
    .replace(/\n{2,}/g, '</p><p>')
    .replace(/\n/g, '<br>')
    .replace(/^(.+)/, '<p>$1</p>');
}

function scrollBottom() {
  const el = document.getElementById('oai-messages');
  if (el) el.scrollTop = el.scrollHeight;
}

function addMsg(role, text) {
  const el = document.getElementById('oai-messages');
  const div = document.createElement('div');
  div.className = `oai-msg ${role}`;
  const avatar = role === 'bot'
    ? `<div class="oai-avatar"><svg viewBox="0 0 24 24"><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></svg></div>`
    : `<div class="oai-avatar">👤</div>`;
  div.innerHTML = `${avatar}<div class="oai-bubble">${role === 'bot' ? mdToHtml(text) : text}</div>`;
  el.appendChild(div);
  scrollBottom();
  return div;
}

function showTyping() {
  const el = document.getElementById('oai-messages');
  const div = document.createElement('div');
  div.className = 'oai-msg bot'; div.id = 'oai-typing';
  div.innerHTML = `<div class="oai-avatar"><svg viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2"><path d="M12 2L2 7l10 5 10-5-10-5z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></svg></div><div class="oai-bubble oai-typing"><span></span><span></span><span></span></div>`;
  el.appendChild(div);
  scrollBottom();
}

function hideTyping() {
  const el = document.getElementById('oai-typing');
  if (el) el.remove();
}

// ── TOGGLE ──
btn.addEventListener('click', () => {
  isOpen = !isOpen;
  btn.classList.toggle('open', isOpen);
  win.classList.toggle('open', isOpen);
  if (isOpen && messages.length === 0) {
    setTimeout(() => {
      addMsg('bot', 'Halo! 👋 Saya asisten AI untuk **OffshoreAI**.\n\nSaya bisa membantu Anda tentang:\n- **ICT**: VSAT, Starlink, Mikrotik, Firewall, IP Camera, IoT/PLC\n- **Offshore**: Mooring winch diagnostic, crane, tensioner, ECR\n\nAda yang bisa saya bantu?');
    }, 200);
  }
  if (isOpen) setTimeout(() => document.getElementById('oai-input')?.focus(), 300);
});

// ── SUGGESTIONS ──
document.getElementById('oai-suggestions').addEventListener('click', (e) => {
  if (e.target.classList.contains('oai-suggestion')) {
    const text = e.target.textContent;
    document.getElementById('oai-suggestions').style.display = 'none';
    sendMessage(text);
  }
});

// ── INPUT ──
const input = document.getElementById('oai-input');
const sendBtn = document.getElementById('oai-send');

input.addEventListener('input', () => {
  sendBtn.disabled = !input.value.trim();
  input.style.height = 'auto';
  input.style.height = Math.min(input.scrollHeight, 100) + 'px';
});

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

sendBtn.addEventListener('click', doSend);

function doSend() {
  const text = input.value.trim();
  if (!text || isThinking) return;
  input.value = ''; input.style.height = 'auto'; sendBtn.disabled = true;
  sendMessage(text);
}

// ── SEND TO API ──
async function sendMessage(text) {
  document.getElementById('oai-suggestions').style.display = 'none';
  addMsg('user', text);
  messages.push({ role: 'user', content: text });
  isThinking = true;
  showTyping();

  const apiKey = window.OFFSHOREAI_API_KEY || '';
  if (!apiKey) {
    hideTyping();
    addMsg('bot', '⚠️ API key belum dikonfigurasi. Silakan hubungi admin.');
    isThinking = false;
    return;
  }

  try {
    const res = await fetch('https://api.anthropic.com/v1/messages', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'x-api-key': apiKey,
        'anthropic-version': '2023-06-01',
        'anthropic-dangerous-direct-browser-access': 'true'
      },
      body: JSON.stringify({
        model: 'claude-haiku-4-5-20251001',
        max_tokens: 1024,
        system: SYSTEM,
        messages: messages.slice(-10)
      })
    });

    const data = await res.json();
    hideTyping();

    if (data.content && data.content[0]) {
      const reply = data.content[0].text;
      messages.push({ role: 'assistant', content: reply });
      addMsg('bot', reply);
    } else {
      addMsg('bot', 'Maaf, terjadi kesalahan. Silakan coba lagi.');
    }
  } catch (err) {
    hideTyping();
    addMsg('bot', 'Koneksi bermasalah. Periksa jaringan Anda dan coba lagi.');
  }

  isThinking = false;
}

})();
