<!DOCTYPE html>
<html lang="id">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
  <title>Live Chat - <%= settings.name %></title>
  
  <script src="https://cdn.tailwindcss.com"></script>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet">

  <style>
    html, body {
      margin: 0;
      padding: 0;
      height: 100%;
      width: 100%;
      overflow: hidden; 
      background-color: #f1f5f9; 
      touch-action: manipulation; 
      font-family: 'Poppins', sans-serif;
    }

    .font-sans {
      font-family: 'Poppins', sans-serif !important;
    }

    /* Warna khas Dashboard */
    :root {
      --blue-500: #3b82f6;
      --blue-50: #eff6ff;
    }
    .text-blue-500 { color: var(--blue-500); }
    .bg-blue-500 { background-color: var(--blue-500); }
    .hover\:bg-blue-600:hover { background-color: #2563eb; }
    .bg-blue-50 { background-color: var(--blue-50); }
    .border-blue-500 { border-color: var(--blue-500); }
    .ring-blue-500 { --tw-ring-color: var(--blue-500); }
    .focus\:border-blue-500:focus { border-color: var(--blue-500); }
    .focus\:ring-blue-500:focus { --tw-ring-color: var(--blue-500); }

    .chat-bubble-mine {
      background-color: var(--blue-500);
      color: #fff;
      border-radius: 2px 2px 0 2px;
    }
    
    .chat-bubble-other {
      background: #ffffff;
      color: #1e293b;
      border-radius: 2px 2px 2px 0;
    }
    
    .chat-image {
      max-width: 160px;
      max-height: 200px;
      border-radius: 2px;
      object-fit: cover;
      cursor: pointer;
      display: block;
      margin: 4px 0;
    }
    
    .send-btn:disabled {
      opacity: 0.6;
      pointer-events: none;
    }

    .modal-backdrop.hidden {
      opacity: 0;
      pointer-events: none;
    }
    .modal-backdrop {
      transition: opacity 0.2s ease;
      opacity: 1;
    }
    
    #chatMessages::-webkit-scrollbar {
      width: 4px;
    }
    #chatMessages::-webkit-scrollbar-thumb {
      background-color: #cbd5e1;
      border-radius: 10px;
    }

    .highlight-msg {
      animation: highlightAnim 1.5s ease-out;
    }
    @keyframes highlightAnim {
      0% { background-color: rgba(37, 99, 235, 0.15); }
      100% { background-color: transparent; }
    }
  </style>
</head>
<body class="bg-slate-100 text-slate-800 font-sans">

  <div class="fixed inset-0 flex flex-col w-full max-w-3xl mx-auto bg-white border-x border-[#dddddd] overflow-hidden">
    
    <!-- Header -->
    <div class="bg-blue-500 px-4 py-3 shrink-0 z-10 flex items-center gap-2">
      <a href="/dashboard" class="w-7 h-7 rounded-[2px] bg-white/15 hover:bg-white/25 flex items-center justify-center text-white transition-colors shrink-0">
        <i class="fas fa-arrow-left text-xs"></i>
      </a>
      
      <div class="flex-1 text-center min-w-0">
        <div class="flex items-center justify-center gap-2">
          <h1 class="text-base font-medium text-white leading-tight truncate">Live Chat <%= settings.name %></h1>
          
          <!-- Indikator online -->
          <span class="relative flex h-2.5 w-2.5 shrink-0">
            <span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-green-400 opacity-75"></span>
            <span class="relative inline-flex rounded-full h-2.5 w-2.5 bg-green-500"></span>
          </span>
        </div>
      </div>

      <% if (user && user.role === 'admin') { %>
        <button onclick="resetChat()" 
                class="w-7 h-7 rounded-[2px] bg-red-500/80 hover:bg-red-600 flex items-center justify-center text-white transition-colors shrink-0"
                title="Reset seluruh chat (hanya admin)">
          <i class="fas fa-trash-alt text-xs"></i>
        </button>
      <% } else { %>
        <div class="w-7 h-7 shrink-0"></div>
      <% } %>
    </div>

    <!-- Area Pesan -->
    <div id="chatMessages" class="flex-1 p-3 overflow-y-auto space-y-4 bg-[#f9f9f9]">
    </div>

    <!-- Input Area -->
    <div class="bg-white border-t border-[#dddddd] p-3 shrink-0 z-10 pb-safe relative">
      
      <div id="replyPreviewContainer" class="hidden relative mx-0 mb-2 p-2 bg-[#f9f9f9] border border-[#dddddd] rounded-[2px] border-l-4 flex flex-col">
        <div class="flex justify-between items-center mb-0.5">
          <span id="replyPreviewName" class="text-xs font-medium text-blue-500">Username</span>
          <button onclick="cancelReply()" type="button" class="text-gray-400 hover:text-[#dc2626] p-1 bg-white rounded-[2px] w-5 h-5 flex items-center justify-center border border-[#dddddd]">
            <i class="fas fa-times text-xs"></i>
          </button>
        </div>
        <span id="replyPreviewText" class="text-xs text-gray-500 truncate pr-4 font-medium">Membalas pesan...</span>
      </div>

      <div id="imagePreviewContainer" class="hidden relative inline-block mb-2 ml-0">
        <img id="imagePreview" src="" alt="Preview" class="h-16 w-16 object-cover rounded-[2px] border border-[#dddddd]" />
        <button onclick="removeImage()" type="button" class="absolute -top-1.5 -right-1.5 w-5 h-5 bg-[#dc2626] text-white rounded-[2px] flex items-center justify-center text-xs hover:bg-red-700">
          <i class="fas fa-times"></i>
        </button>
      </div>

      <form id="chatForm" class="flex items-center gap-2 w-full">
        <label for="imageInput" class="text-gray-400 hover:text-blue-500 cursor-pointer p-2 rounded-[2px] hover:bg-gray-100 transition-colors flex items-center justify-center">
          <i class="fas fa-image text-sm"></i>
        </label>
        <input type="file" id="imageInput" accept="image/*" class="hidden" />

        <div class="flex-1 relative">
          <input type="text" id="messageInput" placeholder="Tulis pesan..." autocomplete="off"
                 class="w-full bg-white border border-[#dddddd] rounded-[2px] px-3 py-2.5 text-xs font-medium text-gray-800 outline-none focus:border-blue-500 focus:ring-1 focus:ring-blue-500 placeholder:text-xs placeholder:font-medium placeholder:text-gray-400 transition-all">
        </div>

        <button type="submit" id="sendBtn"
                class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2.5 rounded-[2px] text-xs font-medium flex items-center justify-center transition-colors shrink-0">
          <i class="fas fa-paper-plane text-xs"></i>
        </button>
      </form>
    </div>
  </div>

  <!-- Modal Gambar -->
  <div id="imageModal" class="fixed inset-0 z-50 flex items-center justify-center hidden modal-backdrop bg-black/85">
    <div class="relative max-w-[90%] max-h-[90%] flex items-center justify-center p-2">
      <button id="closeModalBtn" class="absolute -top-3 -right-3 text-white bg-black/60 hover:bg-black/90 rounded-[2px] w-7 h-7 flex items-center justify-center text-xs z-10 transition-colors border border-white/20">
        <i class="fas fa-times"></i>
      </button>
      <img id="modalImage" src="" alt="Pratinjau Gambar Penuh" class="object-contain max-w-full max-h-full rounded-[2px] shadow-2xl">
    </div>
  </div>

  <script>
    const currentUser = <%- JSON.stringify(user) %>;

    const messagesContainer = document.getElementById('chatMessages');
    const messageInput = document.getElementById('messageInput');
    const chatForm = document.getElementById('chatForm');
    const imageInput = document.getElementById('imageInput');
    const imagePreview = document.getElementById('imagePreview');
    const imagePreviewContainer = document.getElementById('imagePreviewContainer');
    const sendBtn = document.getElementById('sendBtn');
    
    let displayedIds = new Set();
    let lastTimestamp = null;
    let lastRenderedDate = null;
    let isNearBottom = true;
    let uploadedImageUrl = null;
    let isFirstLoad = true;
    let replyingTo = null;

    function getAvatarColor(username) {
      let hash = 0;
      for (let i = 0; i < username.length; i++) {
        hash = username.charCodeAt(i) + ((hash << 5) - hash);
      }
      const colors = ['#3b82f6','#10b981','#f43f5e','#8b5cf6','#f59e0b','#06b6d4','#6366f1','#ec4899'];
      return colors[Math.abs(hash) % colors.length];
    }

    function formatTime(isoString) {
      const date = new Date(isoString);
      return date.toLocaleTimeString('id-ID', { hour: '2-digit', minute: '2-digit', hour12: false });
    }

    function initiateReply(msg) {
      replyingTo = {
        _id: msg._id,
        username: msg.username,
        message: msg.message,
        image: msg.image
      };
      const replyColor = msg.profileColor || getAvatarColor(msg.username);
      
      document.getElementById('replyPreviewName').textContent = msg.username;
      document.getElementById('replyPreviewName').style.color = replyColor;
      
      const replyPreviewContainer = document.getElementById('replyPreviewContainer');
      replyPreviewContainer.style.borderColor = replyColor;
      
      let previewTxt = '';
      if (msg.image && !msg.message) previewTxt = '📷 Gambar';
      else if (msg.image && msg.message) previewTxt = '📷 ' + msg.message;
      else previewTxt = msg.message;
      
      document.getElementById('replyPreviewText').textContent = previewTxt;
      replyPreviewContainer.classList.remove('hidden');
      messageInput.focus();
    }

    function cancelReply() {
      replyingTo = null;
      document.getElementById('replyPreviewContainer').classList.add('hidden');
    }

    function renderMessage(msg) {
      if (displayedIds.has(msg._id)) return;
      displayedIds.add(msg._id);

      const isMine = (msg.userId === currentUser._id);
      const isAdmin = msg.role === 'admin';
      const messageDate = new Date(msg.createdAt);

      const currentDateText = messageDate.toLocaleDateString('id-ID', { day: '2-digit', month: 'short', year: 'numeric' });
      if (!lastRenderedDate || currentDateText !== lastRenderedDate) {
        lastRenderedDate = currentDateText;
        const dateDivider = document.createElement('div');
        dateDivider.className = 'flex justify-center my-4';
        const dateBubble = document.createElement('div');
        dateBubble.className = 'bg-blue-50 text-blue-500 text-xs font-medium px-3 py-1.5 rounded-[2px] border border-[#dddddd]';
        dateBubble.textContent = currentDateText;
        dateDivider.appendChild(dateBubble);
        messagesContainer.appendChild(dateDivider);
      }

      const wrapper = document.createElement('div');
      wrapper.id = `msg-${msg._id}`;
      wrapper.className = `flex items-end gap-2 group p-1 ${isMine ? 'flex-row-reverse' : ''}`;

      // Avatar untuk pengguna lain
      if (!isMine) {
        const avatar = document.createElement('div');
        avatar.className = 'w-8 h-8 rounded-[2px] overflow-hidden flex items-center justify-center text-white font-bold text-xs shrink-0 relative';
        
        if (msg.profilePicture) {
          avatar.innerHTML = `<img src="${msg.profilePicture}" class="w-full h-full object-cover" alt="${msg.username}">`;
        } else {
          const color = msg.profileColor || getAvatarColor(msg.username);
          avatar.style.backgroundColor = color;
          avatar.textContent = msg.username.charAt(0).toUpperCase();
        }
        
        wrapper.appendChild(avatar);
      }

      // Bubble
      const bubble = document.createElement('div');
      bubble.className = `px-3 py-2 font-medium ${isMine ? 'chat-bubble-mine max-w-[80%]' : 'chat-bubble-other max-w-[75%] border border-[#dddddd]'}`;

      // Nama pengguna (hanya untuk pengguna lain)
      if (!isMine) {
        const nameEl = document.createElement('div');
        nameEl.className = `text-xs font-medium mb-1`;
        nameEl.style.color = msg.profileColor || getAvatarColor(msg.username);
        nameEl.innerHTML = msg.username;
        if (isAdmin) {
          nameEl.innerHTML += ' <span class="text-blue-500"><i class="fas fa-check-circle text-xs ml-0.5"></i></span>';
        }
        bubble.appendChild(nameEl);
      }

      // Kotak balasan (replyTo)
      if (msg.replyTo && (msg.replyTo.message || msg.replyTo.image)) {
        const repBoxColor = getAvatarColor(msg.replyTo.username);
        const replyBox = document.createElement('div');
        replyBox.className = `rounded-[2px] bg-black/5 p-1.5 mb-2 border-l-4 flex flex-col text-left cursor-pointer hover:bg-black/10 transition-colors`;
        replyBox.style.borderColor = repBoxColor;
        
        replyBox.onclick = () => {
           const target = document.getElementById(`msg-${msg.replyTo._id}`);
           if (target) {
              target.scrollIntoView({ behavior: 'smooth', block: 'center' });
              target.classList.add('highlight-msg');
              setTimeout(() => target.classList.remove('highlight-msg'), 1500);
           }
        };

        const repName = document.createElement('span');
        repName.className = 'font-medium text-xs leading-tight mb-0.5';
        repName.style.color = repBoxColor;
        repName.textContent = msg.replyTo.username;
        replyBox.appendChild(repName);

        let repTxtStr = '';
        if (msg.replyTo.image && !msg.replyTo.message) repTxtStr = '📷 Gambar';
        else if (msg.replyTo.image && msg.replyTo.message) repTxtStr = '📷 ' + msg.replyTo.message;
        else repTxtStr = msg.replyTo.message;

        const repTxt = document.createElement('span');
        repTxt.className = `text-xs truncate opacity-80 font-medium ${isMine ? 'text-white/80' : 'text-gray-600'}`;
        repTxt.textContent = repTxtStr;
        replyBox.appendChild(repTxt);

        bubble.appendChild(replyBox);
      }

      // Gambar
      if (msg.image) {
        const img = document.createElement('img');
        img.src = msg.image;
        img.className = 'chat-image border border-[#dddddd]';
        img.onclick = () => openImageModal(msg.image);
        img.onload = () => {
          if (isFirstLoad || isNearBottom) forceScrollToBottom();
        };
        bubble.appendChild(img);
      }

      // Teks pesan dan Waktu
      if (msg.message) {
        const contentWrapper = document.createElement('div');
        contentWrapper.className = `text-xs font-medium leading-snug break-words ${isMine ? 'text-white' : 'text-gray-800'}`;
        
        const messageSpan = document.createElement('span');
        messageSpan.className = 'whitespace-pre-wrap';
        messageSpan.textContent = msg.message;
        
        const timeSpan = document.createElement('span');
        timeSpan.className = `float-right text-[11px] font-medium ml-3 mt-1.5 ${isMine ? 'text-blue-100' : 'text-gray-400'}`;
        timeSpan.textContent = formatTime(msg.createdAt);

        contentWrapper.appendChild(messageSpan);
        contentWrapper.appendChild(timeSpan);
        
        const clearFix = document.createElement('div');
        clearFix.className = 'clear-both';
        contentWrapper.appendChild(clearFix);

        bubble.appendChild(contentWrapper);
      } else {
        const timeDiv = document.createElement('div');
        timeDiv.className = `text-xs font-medium text-right ${isMine ? 'text-blue-100' : 'text-gray-400'}`;
        timeDiv.textContent = formatTime(msg.createdAt);
        bubble.appendChild(timeDiv);
      }

      wrapper.appendChild(bubble);

      // Tombol reply
      const replyBtn = document.createElement('button');
      replyBtn.className = 'text-gray-300 hover:text-blue-500 hover:bg-gray-100 p-2 rounded-[2px] transition-all active:scale-95 shrink-0 opacity-50 hover:opacity-100';
      replyBtn.innerHTML = '<i class="fas fa-reply text-xs"></i>';
      replyBtn.onclick = () => initiateReply(msg);
      wrapper.appendChild(replyBtn);

      messagesContainer.appendChild(wrapper);
    }

    // ======================
    //  ROUTING GAMBAR BERBASIS HASH
    // ======================
    const imageModal = document.getElementById('imageModal');
    const modalImage = document.getElementById('modalImage');

    function openImageModal(imageUrl) {
      window.location.hash = '#image?url=' + encodeURIComponent(imageUrl);
    }

    function closeImageModal() {
      window.location.hash = '';
    }

    function handleHashChange() {
      const hash = window.location.hash;
      if (hash.startsWith('#image?url=')) {
        const urlParam = hash.substring('#image?url='.length);
        const imageUrl = decodeURIComponent(urlParam);
        modalImage.src = imageUrl;
        imageModal.classList.remove('hidden');
        imageModal.classList.remove('opacity-0');
      } else {
        imageModal.classList.add('opacity-0');
        setTimeout(() => {
          imageModal.classList.add('hidden');
          modalImage.src = '';
        }, 200);
      }
    }

    window.addEventListener('hashchange', handleHashChange);
    window.addEventListener('load', handleHashChange);

    document.getElementById('closeModalBtn').addEventListener('click', closeImageModal);
    imageModal.addEventListener('click', (e) => {
      if (e.target === imageModal || e.target.parentElement === imageModal) {
        closeImageModal();
      }
    });

    async function resetChat() {
      if (!confirm('⚠️ Anda yakin ingin menghapus SELURUH chat? Tindakan ini tidak dapat dibatalkan.')) return;
      
      try {
        const res = await fetch('/api/chat/reset', {
          method: 'POST', 
          credentials: 'include'
        });
        const data = await res.json();
        if (data.success) {
          messagesContainer.innerHTML = '';
          displayedIds.clear();
          lastTimestamp = null;
          lastRenderedDate = null;
          isFirstLoad = true;
          await fetchMessages();
        } else {
          alert(data.error || 'Gagal mereset chat.');
        }
      } catch (err) {
        alert('Gagal menghubungi server untuk reset chat.');
        console.error(err);
      }
    }

    function forceScrollToBottom() {
      messagesContainer.scrollTop = messagesContainer.scrollHeight;
    }
    function scrollToBottomIfNeeded() {
      if (isFirstLoad || isNearBottom) forceScrollToBottom();
    }
    messagesContainer.addEventListener('scroll', () => {
      const threshold = 100;
      isNearBottom = messagesContainer.scrollTop + messagesContainer.clientHeight >= messagesContainer.scrollHeight - threshold;
    });

    async function fetchMessages(since = null) {
      try {
        let url = '/api/chat/messages';
        if (since) url += `?since=${encodeURIComponent(new Date(since).toISOString())}`;
        const res = await fetch(url, { credentials: 'include' });
        const messages = await res.json();
        
        if (!Array.isArray(messages)) return;
        
        for (const msg of messages) {
          renderMessage(msg);
          const msgTime = new Date(msg.createdAt).getTime();
          if (!lastTimestamp || msgTime > lastTimestamp) lastTimestamp = msgTime;
        }

        if (messages.length > 0) scrollToBottomIfNeeded();

        if (isFirstLoad) {
          setTimeout(() => {
            forceScrollToBottom();
            messagesContainer.classList.add('scroll-smooth');
            isFirstLoad = false;
          }, 150);
        }
      } catch (err) {
        console.error('Gagal fetch chat:', err);
      }
    }

    imageInput.addEventListener('change', async (e) => {
      const file = e.target.files[0];
      if (!file) return;
      const formData = new FormData();
      formData.append('image', file);
      try {
        const res = await fetch('/api/chat/upload', { method: 'POST', body: formData, credentials: 'include' });
        const data = await res.json();
        if (data.success) {
          uploadedImageUrl = data.imageUrl;
          imagePreview.src = data.imageUrl;
          imagePreviewContainer.classList.remove('hidden');
        } else alert(data.error || 'Gagal upload gambar');
      } catch (err) {
        alert('Gagal upload gambar');
      }
      imageInput.value = '';
    });

    function removeImage() {
      uploadedImageUrl = null;
      imagePreviewContainer.classList.add('hidden');
      imagePreview.src = '';
    }

    chatForm.addEventListener('submit', async (e) => {
      e.preventDefault();
      const text = messageInput.value.trim();
      if (!text && !uploadedImageUrl) return;

      sendBtn.disabled = true;
      try {
        const res = await fetch('/api/chat/send', {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ 
            message: text, 
            image: uploadedImageUrl,
            replyTo: replyingTo
          }),
          credentials: 'include'
        });
        const data = await res.json();
        if (data.success && data.message) {
          renderMessage(data.message);
          forceScrollToBottom();
          messageInput.value = '';
          removeImage();
          cancelReply();
        }
      } catch (err) {
        alert('Gagal mengirim pesan');
      }
      sendBtn.disabled = false;
    });

    async function init() {
      await fetchMessages();
      setInterval(() => fetchMessages(lastTimestamp), 2000);
    }
    
    init();
  </script>
</body>
</html>