<!DOCTYPE html>
<html lang="uz">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chat #{{ chat.id }} — AsakaBank Admin</title>
<style>
  * { box-sizing: border-box; margin: 0; padding: 0; }
  body { font-family: 'Segoe UI', sans-serif; background: #f0f2f5; color: #1a1a2e;
         display: flex; flex-direction: column; height: 100vh; }

  .topbar {
    background: #003580; color: #fff; padding: 14px 20px;
    display: flex; align-items: center; gap: 14px; flex-shrink: 0;
  }
  .topbar a { color: rgba(255,255,255,.7); text-decoration: none; font-size: 22px; }
  .topbar a:hover { color: #fff; }
  .topbar-info { flex: 1; }
  .topbar-name { font-weight: 700; font-size: 16px; }
  .topbar-sub  { font-size: 13px; color: rgba(255,255,255,.6); margin-top: 2px; }
  .badge {
    padding: 4px 12px; border-radius: 20px; font-size: 12px; font-weight: 600;
  }
  .badge.new    { background: #fdecea; color: #e74c3c; }
  .badge.active { background: #e8f8f0; color: #27ae60; }
  .badge.closed { background: #eee; color: #888; }

  .btn-close {
    background: #e74c3c; color: #fff; border: none; border-radius: 8px;
    padding: 8px 16px; font-size: 13px; font-weight: 600; cursor: pointer;
    transition: background .2s;
  }
  .btn-close:hover { background: #c0392b; }
  .btn-close:disabled { background: #ccc; cursor: not-allowed; }

  .messages {
    flex: 1; overflow-y: auto; padding: 20px;
    display: flex; flex-direction: column; gap: 10px;
  }

  .msg { display: flex; }
  .msg.user  { justify-content: flex-start; }
  .msg.staff { justify-content: flex-end; }

  .bubble {
    max-width: 70%; padding: 10px 14px; border-radius: 16px;
    font-size: 14px; line-height: 1.5;
  }
  .msg.user  .bubble { background: #fff; border-bottom-left-radius: 4px; box-shadow: 0 1px 3px rgba(0,0,0,.08); }
  .msg.staff .bubble { background: #003580; color: #fff; border-bottom-right-radius: 4px; }

  .msg-time { font-size: 11px; color: #aaa; margin-top: 4px; }
  .msg.staff .msg-time { text-align: right; }

  .compose {
    background: #fff; border-top: 1px solid #e8e8e8;
    padding: 14px 20px; display: flex; gap: 10px; flex-shrink: 0;
  }
  .compose textarea {
    flex: 1; border: 1.5px solid #ddd; border-radius: 10px;
    padding: 10px 14px; font-size: 14px; resize: none; outline: none;
    font-family: inherit; max-height: 120px;
    transition: border-color .2s;
  }
  .compose textarea:focus { border-color: #003580; }
  .compose textarea:disabled { background: #f5f5f5; color: #aaa; }
  .btn-send {
    background: #003580; color: #FFD700; border: none; border-radius: 10px;
    padding: 0 22px; font-size: 20px; cursor: pointer; transition: background .2s;
    flex-shrink: 0;
  }
  .btn-send:hover { background: #00256b; }
  .btn-send:disabled { background: #ccc; cursor: not-allowed; }

  .closed-notice {
    text-align: center; padding: 10px;
    color: #888; font-size: 13px; background: #f9f9f9;
    border-top: 1px solid #eee;
  }

  .empty-msg { text-align: center; color: #bbb; margin: auto; font-size: 15px; }
</style>
</head>
<body>

<div class="topbar">
  <a href="/">&#8592;</a>
  <div class="topbar-info">
    <div class="topbar-name">
      {{ chat.full_name or 'Noma\'lum' }}
      {% if chat.username %}<span style="font-weight:400;font-size:13px;opacity:.7"> @{{ chat.username }}</span>{% endif %}
    </div>
    <div class="topbar-sub">Chat #{{ chat.id }}</div>
  </div>
  <span class="badge {{ chat.status }}" id="statusBadge">
    {% if chat.status == 'new' %}Yangi
    {% elif chat.status == 'active' %}Aktiv
    {% else %}Tugatilgan{% endif %}
  </span>
  {% if chat.status != 'closed' %}
  <button class="btn-close" id="btnClose" onclick="closeChat()">✖ Tugatish</button>
  {% endif %}
</div>

<div class="messages" id="msgList">
  {% if not messages %}
  <div class="empty-msg">💬 Hali xabar yo'q</div>
  {% endif %}
  {% for m in messages %}
  <div class="msg {{ m.sender }}">
    <div>
      <div class="bubble">{{ m.text }}</div>
      <div class="msg-time">{{ m.created_at.strftime('%d.%m.%Y %H:%M') }}</div>
    </div>
  </div>
  {% endfor %}
</div>

{% if chat.status != 'closed' %}
<div class="compose">
  <textarea id="replyText" rows="2" placeholder="Javob yozing..." onkeydown="handleKey(event)"></textarea>
  <button class="btn-send" onclick="sendReply()">➤</button>
</div>
{% else %}
<div class="closed-notice">✅ Chat tugatilgan — yangi xabar yuborib bo'lmaydi</div>
{% endif %}

<script>
  const chatId = {{ chat.id }};
  const isClosed = {{ 'true' if chat.status == 'closed' else 'false' }};

  // Scroll to bottom on load
  const msgList = document.getElementById('msgList');
  msgList.scrollTop = msgList.scrollHeight;

  function handleKey(e) {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      sendReply();
    }
  }

  async function sendReply() {
    const ta = document.getElementById('replyText');
    const text = ta.value.trim();
    if (!text) return;

    ta.disabled = true;
    document.querySelector('.btn-send').disabled = true;

    try {
      const res = await fetch(`/api/reply/${chatId}`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ text }),
      });
      const data = await res.json();
      if (data.ok) {
        appendMessage('staff', text);
        ta.value = '';
        // Update status badge
        document.getElementById('statusBadge').textContent = 'Aktiv';
        document.getElementById('statusBadge').className = 'badge active';
      }
    } catch (e) {
      alert('Xato yuz berdi');
    }

    ta.disabled = false;
    document.querySelector('.btn-send').disabled = false;
    ta.focus();
  }

  async function closeChat() {
    if (!confirm('Chatni tugatmoqchimisiz?')) return;
    const btn = document.getElementById('btnClose');
    btn.disabled = true;
    try {
      const res = await fetch(`/api/close/${chatId}`, { method: 'POST' });
      const data = await res.json();
      if (data.ok) {
        document.getElementById('statusBadge').textContent = 'Tugatilgan';
        document.getElementById('statusBadge').className = 'badge closed';
        btn.remove();
        document.querySelector('.compose')?.remove();
        const notice = document.createElement('div');
        notice.className = 'closed-notice';
        notice.textContent = '✅ Chat tugatildi';
        document.body.appendChild(notice);
      }
    } catch (e) {
      alert('Xato yuz berdi');
      btn.disabled = false;
    }
  }

  function appendMessage(sender, text) {
    const now = new Date();
    const timeStr = now.toLocaleDateString('uz') + ' ' + now.toLocaleTimeString('uz', {hour:'2-digit',minute:'2-digit'});
    const div = document.createElement('div');
    div.className = `msg ${sender}`;
    div.innerHTML = `<div><div class="bubble">${escHtml(text)}</div><div class="msg-time">${timeStr}</div></div>`;
    msgList.appendChild(div);
    msgList.scrollTop = msgList.scrollHeight;
  }

  function escHtml(s) {
    return s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;');
  }

  // Poll for new user messages every 5 seconds
  if (!isClosed) {
    let lastCount = {{ messages | length }};
    setInterval(async () => {
      try {
        const res = await fetch(`/api/chat/${chatId}/messages`);
        const msgs = await res.json();
        if (msgs.length > lastCount) {
          for (let i = lastCount; i < msgs.length; i++) {
            const m = msgs[i];
            if (m.sender === 'user') appendMessage('user', m.text);
          }
          lastCount = msgs.length;
        }
      } catch {}
    }, 5000);
  }
</script>
</body>
</html>
