{% extends 'chat/base.html' %}
{% block title %}DM — {{ other.username }} — DiscordClone{% endblock %}
{% block body %}
{% with profile=request.user.profile %}
<div class="app-layout">
  <!-- Sidebar -->
  <div class="sidebar-channels">
    <div class="sidebar-header"><a href="{% url 'home' %}" class="text-white text-decoration-none"><i class="bi bi-arrow-left me-1"></i>DiscordClone</a></div>
    <div style="flex:1;overflow-y:auto;padding:8px;">
      <div class="sidebar-section">Direct Messages</div>
      {% for u in all_users %}
      <a href="{% url 'dm' u.username %}" class="channel-item {% if u.username == other.username %}active{% endif %}" id="dm_link_{{ u.id }}">
        <span {% if u.profile.online %}class="online-dot"{% else %}class="offline-dot"{% endif %}></span>
        {{ u.username }}
      </a>
      {% endfor %}
    </div>
    <div class="user-bar">
      <div class="user-avatar">
        {% if profile.avatar %}<img src="{{ profile.avatar.url }}" alt="av">{% else %}{{ request.user.username|first|upper }}{% endif %}
      </div>
      <div style="flex:1;min-width:0;font-size:.85rem;font-weight:600;">{{ request.user.username }}</div>
      <a href="{% url 'logout' %}" class="text-secondary" id="btn_logout_dm"><i class="bi bi-box-arrow-right"></i></a>
    </div>
  </div>

  <!-- DM chat -->
  <div class="main-content">
    <div class="chat-header">
      <i class="bi bi-person-fill text-secondary"></i>
      <span>{{ other.username }}</span>
      {% if other.profile.online %}<span class="online-dot ms-1"></span>{% endif %}
    </div>

    <div class="messages-container" id="messages-container">
      {% for msg in messages %}
      <div class="message-group" id="msg_dm_{{ msg.id }}">
        <div class="msg-avatar">
          {% if msg.sender.profile.avatar %}<img src="{{ msg.sender.profile.avatar.url }}" alt="av">{% else %}{{ msg.sender.username|first|upper }}{% endif %}
        </div>
        <div class="msg-body">
          <div class="msg-meta">
            <span class="msg-author">{{ msg.sender.username }}</span>
            <span class="msg-time">{{ msg.timestamp|date:"H:i" }}</span>
          </div>
          {% if msg.content %}<div class="msg-text">{{ msg.content }}</div>{% endif %}
          {% if msg.file %}
          <div class="msg-file">
            {% if ".jpg" in msg.file.name or ".png" in msg.file.name or ".gif" in msg.file.name or ".webp" in msg.file.name %}
            <img src="{{ msg.file.url }}" alt="image">
            {% elif ".mp3" in msg.file.name or ".wav" in msg.file.name or ".ogg" in msg.file.name %}
            <audio controls src="{{ msg.file.url }}"></audio>
            {% else %}
            <a href="{{ msg.file.url }}" target="_blank"><i class="bi bi-file-earmark"></i> {{ msg.file.name|slice:"11:" }}</a>
            {% endif %}
          </div>
          {% endif %}
        </div>
      </div>
      {% endfor %}
    </div>

    <!-- File upload -->
    <div style="padding: 0 20px 4px;">
      <form method="post" enctype="multipart/form-data" id="dm-file-form">
        {% csrf_token %}
        <div class="d-flex gap-2 align-items-center">
          <input type="file" name="file" class="form-control form-control-sm" accept="image/*,audio/*" style="max-width:260px;" id="id_dm_file">
          <input type="text" name="content" class="form-control form-control-sm" placeholder="Caption" id="id_dm_caption">
          <button type="submit" class="btn btn-sm btn-primary" id="btn_dm_upload"><i class="bi bi-upload"></i> Upload</button>
        </div>
      </form>
    </div>

    <div class="input-area">
      <div class="input-box">
        <input type="text" id="dm-input" placeholder="Message {{ other.username }}" autocomplete="off">
        <button type="button" id="dm-send-btn" title="Send"><i class="bi bi-send"></i></button>
      </div>
    </div>
  </div>
</div>
{% endwith %}
{% endblock %}

{% block scripts %}
<script>
const otherUsername = "{{ other.username }}";
const myUsername = "{{ request.user.username }}";
const container = document.getElementById('messages-container');
const input = document.getElementById('dm-input');
const sendBtn = document.getElementById('dm-send-btn');
const myAvatar = "{% if request.user.profile.avatar %}{{ request.user.profile.avatar.url }}{% endif %}";

container.scrollTop = container.scrollHeight;

const wsProto = location.protocol === 'https:' ? 'wss:' : 'ws:';
const ws = new WebSocket(`${wsProto}//${location.host}/ws/dm/${otherUsername}/`);

ws.onmessage = function(e) {
  const data = JSON.parse(e.data);
  appendDM(data);
};

function sendDM() {
  const msg = input.value.trim();
  if (!msg || ws.readyState !== WebSocket.OPEN) return;
  ws.send(JSON.stringify({ message: msg }));
  input.value = '';
}

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

function appendDM(data) {
  const avatarHtml = data.avatar ? `<img src="${data.avatar}" alt="av">` : data.sender[0].toUpperCase();

  let fileHtml = '';
  if (data.file_url) {
    const fileLower = data.file_name.toLowerCase();
    if (fileLower.endsWith('.jpg') || fileLower.endsWith('.png') || fileLower.endsWith('.gif') || fileLower.endsWith('.webp') || fileLower.endsWith('.jpeg')) {
      fileHtml = `<div class="msg-file"><img src="${data.file_url}" alt="image"></div>`;
    } else if (fileLower.endsWith('.mp3') || fileLower.endsWith('.wav') || fileLower.endsWith('.ogg')) {
      fileHtml = `<div class="msg-file"><audio controls src="${data.file_url}"></audio></div>`;
    } else {
      fileHtml = `<div class="msg-file"><a href="${data.file_url}" target="_blank"><i class="bi bi-file-earmark"></i> ${data.file_name.split('/').pop()}</a></div>`;
    }
  }

  const div = document.createElement('div');
  div.className = 'message-group';
  div.id = `msg_dm_${data.message_id}`;
  div.innerHTML = `
    <div class="msg-avatar">${avatarHtml}</div>
    <div class="msg-body">
      <div class="msg-meta">
        <span class="msg-author">${data.sender}</span>
        <span class="msg-time">${data.timestamp}</span>
      </div>
      ${data.message ? `<div class="msg-text">${escHtml(data.message)}</div>` : ''}
      ${fileHtml}
    </div>`;
  container.appendChild(div);
  container.scrollTop = container.scrollHeight;
}

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