{% extends 'chat/base.html' %}
{% block title %}#{{ channel.name }} — DiscordClone{% endblock %}
{% block body %}
{% with profile=request.user.profile %}
<div class="app-layout">
  <!-- Channel 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;">
      <div class="sidebar-section">Channels
        {% if profile.is_moderator %}<a href="{% url 'create_channel' %}" class="text-white" id="btn_create_ch"><i class="bi bi-plus-lg"></i></a>{% endif %}
      </div>
      {% for ch in all_channels %}
      <a href="{% url 'channel' ch.id %}" class="channel-item {% if ch.id == channel.id %}active{% endif %}" id="ch_{{ ch.id }}">
        <i class="bi bi-hash"></i>{{ ch.name }}
      </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;">
        <div style="font-size:.85rem;font-weight:600;">{{ request.user.username }}</div>
        <span class="role-badge role-{{ profile.role }}">{{ profile.role }}</span>
      </div>
      <a href="{% url 'profile' %}" class="text-secondary" id="btn_profile_ch"><i class="bi bi-gear"></i></a>
      {% if profile.is_admin %}<a href="{% url 'admin_panel' %}" class="text-warning ms-1" id="btn_admin_ch"><i class="bi bi-shield-check"></i></a>{% endif %}
      <a href="{% url 'logout' %}" class="text-secondary ms-1" id="btn_logout_ch"><i class="bi bi-box-arrow-right"></i></a>
    </div>
  </div>

  <!-- Main chat -->
  <div class="main-content">
    <div class="chat-header">
      <i class="bi bi-hash text-secondary"></i>
      <span>{{ channel.name }}</span>
      {% if channel.description %}<span style="color:var(--dc-muted);font-size:.8rem;font-weight:400;">— {{ channel.description }}</span>{% endif %}
      <span class="ms-auto" style="font-size:.75rem;color:var(--dc-muted);">{{ channel.members.count }} members</span>
    </div>

    <div class="messages-container" id="messages-container">
      {% for msg in messages %}
      {% if not msg.deleted %}
      <div class="message-group" id="msg_{{ 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" style="color:{% if msg.sender.profile.role == 'admin' %}var(--dc-admin){% elif msg.sender.profile.role == 'moderator' %}var(--dc-mod){% else %}#fff{% endif %};">
              {{ msg.sender.username }}
            </span>
            <span class="role-badge role-{{ msg.sender.profile.role }}">{{ msg.sender.profile.role|slice:":3" }}</span>
            <span class="msg-time">{{ msg.timestamp|date:"H:i" }}</span>
            <div class="msg-actions">
              {% if profile.is_moderator or msg.sender == request.user %}
              <a href="{% url 'delete_message' msg.id %}" class="btn btn-sm btn-danger py-0 px-1" style="font-size:.7rem;" id="del_msg_{{ msg.id }}" onclick="return confirm('Delete?')"><i class="bi bi-trash"></i></a>
              {% endif %}
            </div>
          </div>
          {% if msg.content %}<div class="msg-text">{{ msg.content }}</div>{% endif %}
          {% if msg.file %}
          <div class="msg-file">
            {% if msg.file.url|slice:"-4:" in ".jpg .png .gif .web" or msg.file.name|lower|slice:"-4:" in ".jpg,.png,.gif,.web" %}
            <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:"8:" }}</a>
            {% endif %}
          </div>
          {% endif %}
        </div>
      </div>
      {% endif %}
      {% endfor %}
    </div>

    <!-- File upload -->
    <div style="padding: 0 20px 4px;">
      <form method="post" enctype="multipart/form-data" id="file-upload-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_file_upload">
          <input type="text" name="content" class="form-control form-control-sm" placeholder="Caption (optional)" id="id_file_caption">
          <button type="submit" class="btn btn-sm btn-primary" id="btn_upload_file"><i class="bi bi-upload"></i> Upload</button>
        </div>
      </form>
    </div>

    <!-- Text input -->
    <div class="input-area">
      <div class="input-box">
        <button type="button" title="Attach file" onclick="document.getElementById('id_file_upload').click()"><i class="bi bi-plus-circle"></i></button>
        <input type="text" id="chat-input" placeholder="Message #{{ channel.name }}" autocomplete="off">
        <button type="button" id="send-btn" title="Send"><i class="bi bi-send"></i></button>
      </div>
    </div>
  </div>

  <!-- Members sidebar -->
  <div class="sidebar-users">
    <div class="sidebar-section">Members — {{ channel.members.count }}</div>
    <div style="flex:1;overflow-y:auto;padding:8px;">
      {% for member in channel.members.all %}
      <div class="channel-item" style="cursor:default;">
        <span {% if member.profile.online %}class="online-dot"{% else %}class="offline-dot"{% endif %}></span>
        <a href="{% url 'dm' member.username %}" class="text-decoration-none" style="color:inherit;">{{ member.username }}</a>
        <span class="role-badge role-{{ member.profile.role }} ms-auto">{{ member.profile.role|slice:":3" }}</span>
      </div>
      {% endfor %}
    </div>
  </div>
</div>
{% endwith %}
{% endblock %}

{% block scripts %}
<script>
const channelId = {{ channel.id }};
const username = "{{ request.user.username }}";
const userRole = "{{ request.user.profile.role }}";
const userAvatar = "{% if request.user.profile.avatar %}{{ request.user.profile.avatar.url }}{% endif %}";

const container = document.getElementById('messages-container');
const input = document.getElementById('chat-input');
const sendBtn = document.getElementById('send-btn');

// Scroll to bottom
container.scrollTop = container.scrollHeight;

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

ws.onopen = () => console.log('WS connected');
ws.onclose = () => console.log('WS closed');

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

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

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

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

  const roleColor = data.role === 'admin' ? 'var(--dc-admin)' : data.role === 'moderator' ? 'var(--dc-mod)' : '#fff';
  const roleShort = data.role.slice(0, 3);

  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_${data.message_id}`;
  div.innerHTML = `
    <div class="msg-avatar">${avatarHtml}</div>
    <div class="msg-body">
      <div class="msg-meta">
        <span class="msg-author" style="color:${roleColor};">${data.sender}</span>
        <span class="role-badge role-${data.role}">${roleShort}</span>
        <span class="msg-time">${data.timestamp}</span>
        <div class="msg-actions">
          ${(userRole === 'admin' || userRole === 'moderator' || data.sender === username) ?
            `<a href="/message/${data.message_id}/delete/" class="btn btn-sm btn-danger py-0 px-1" style="font-size:.7rem;" onclick="return confirm('Delete?')"><i class="bi bi-trash"></i></a>` : ''}
        </div>
      </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 %}
