<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Eversync</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
    {% load static %}
    <link rel="icon" href="{% static 'favicon.ico' %}">
    <link rel="stylesheet" href="{% static 'index-style.css' %}" ">
    <link rel="stylesheet" href="{% static 'login-style.css' %}" />

    {% block scripts %}
        {% include "sentry_replay.html" %}
    {% endblock %}


    <style>
 .container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
  padding: 20px;
  box-sizing: border-box;
}

.welcome-box {
  flex: 0 0 100%;
  max-width: 400px;
  height: 600px;
  padding: 20px;
  border-radius: 8px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
}

@media (max-width: 700px) {
  .container {
    flex-direction: column;
    align-items: center;
    padding: 20px;
  }

  .welcome-box {
    width: 90vw;
    max-width: none;
    margin-bottom: 20px;
    padding: 15px;
  }

  .content-box {
    width: 100%;
  }
}
label[for="message-content"] {
  font-weight: 600;
  color: black;
}
.dark label[for="message-content"] {
  color: #e4e6eb;
}
textarea#message-content {
  background-color: white;
  color: black;
  border: 1px solid #666;
  width: 100%;
  padding: 10px;
  border-radius: 6px;
  resize: vertical;
  box-sizing: border-box;
  font-size: 14px;
}

.dark textarea#message-content {
  background-color: #2a2b2d;
  color: #e4e6eb;
  border: 1px solid #555;
}

.message-box {
  width: 100%;
  padding: 10px;
  border-radius: 6px;
  border: 1px solid #666;
  background-color: white;
  color: black;
  resize: vertical;
  box-sizing: border-box;
  font-size: 14px;
}

.dark .message-box {
  background-color: #2a2b2d;
  color: #e4e6eb;
  border: 1px solid #555;
}

.pinned-message {
    background-color: #ffeeba;
    padding: 10px;
    border-radius: 6px;
    margin-bottom: 15px;
    border: 1px solid #f0ad4e;
    color: #000;
}

.dark .pinned-message {
    background-color: #2d2a1e;
    border-color: #665c3d;
    color: #e4e6eb;
}

.dark .pinned-message strong {
    color: #e4e6eb;
}
    </style>
</head>
    
</head>
<body>
    <div class="header">
        <div class="header-content">
            <a href="/"><img src="{% static 'eversync2.png' %}" alt="Eversync Logo" style="height: 80px; margin-right: 10px; display: flex; align-items: center; gap: 5px;"></a>
            <a href="/" class="logo" >eversync</a>
            <div class="nav-links" style="position: relative;">
                <div class="dropdown">
                    <button class="dropdown-toggle" style="background: none; border: none; color: white; font-size: 16px; cursor: pointer;">
                        Welcome, {{ user.username }} <i class="fas fa-caret-down"></i>
                    </button>
                    <div class="dropdown-menu" style="display: none; position: absolute; right: 0; background-color: #333; border: 1px solid #444; border-radius: 4px; padding: 10px; width: 184px;">
                        
                        <form action="{% url 'manage' %}" method="post" style="margin: 0;">
                            {% csrf_token %}
                            <button type="submit" class="logout-button" style="background-color: transparent; color: white; border: none; cursor: pointer;">Manage Account</button>
                        </form>
                        
                        <form action="{% url 'logoutz' %}" method="post" style="margin: 0;">
                            {% csrf_token %}
                            <button type="submit" class="logout-button" style="background-color: transparent; color: white; border: none; cursor: pointer;">Log Out</button>
                        </form>
                        <button id="themeToggle" class="logout-button" style="background-color: transparent; color: white; border: none; cursor: pointer;">Toggle Dark Mode</button>
                        
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="container">
        <div class="welcome-box">
        <h2>Chat with {{ other_user.username }}</h2>
        {% if pinned_message %}
            <div class="pinned-message">
              📌 <strong>{{ pinned_message.sender.username }}</strong>: {{ pinned_message.content }}
            </div>
        {% endif %}

        <div id="chat-log" style="flex: 1; overflow-y: auto; border: 1px solid #ccc; padding: 10px; margin-bottom: 15px;">
        {% for msg in messages %}
            <div style="margin: 10px 0; text-align: {% if msg.sender == request.user %}right{% else %}left{% endif %};">
                <strong>{{ msg.sender.username }}</strong>: {{ msg.content }}<br>
                <small data-timestamp="{{ msg.timestamp|date:'c' }}"></small>
                {% if msg.sender == request.user %}
                    {% if msg.seen %}
                        <div style="font-size: 12px; color: #6c757d;">Seen</div>
                    {% else %}
                        <div style="font-size: 12px; color: #6c757d;">Delivered</div>
                    {% endif %}
                {% endif %}
                {% if msg.sender == request.user %}
                    <form action="/pin/{{ msg.id }}/" method="post" style="display:inline;">
                      {% csrf_token %}
                      <button type="submit" class="btn btn-sm" style="margin-left: 8px; background-color: #ffc107; color: black; border: none; padding: 2px 8px; border-radius: 4px; cursor: pointer;">
                        {% if msg.pinned %}Unpin{% else %}Pin{% endif %}
                      </button>
                    </form>
                    <form action="/delete/{{ msg.id }}/" method="post" style="display:inline;">
                        {% csrf_token %}
                        <button type="submit" class="btn btn-danger btn-sm" style="margin-top:5px; background-color: #dc3545; color: white; border: none; padding: 2px 8px; border-radius: 4px; cursor: pointer;">Delete</button>
                    </form>
                {% endif %}
            </div>
        {% endfor %}
        </div>

        <form id="chat-form" style="margin-top: 15px;">
            {% csrf_token %}
            <input type="hidden" id="receiver" name="receiver" value="{{ other_user.username }}">
        
            <label for="message-content">
                Your Message
            </label>
            <textarea
                name="content"
                id="message-content"
                rows="3"
                required
                class="message-box"
            ></textarea>
        
            <button
                class="login-button"
                type="submit"
                style="
                    margin-top: 10px;
                    padding: 10px 20px;
                    color: white;
                    border: none;
                    border-radius: 6px;
                    font-weight: bold;
                    cursor: pointer;
                    transition: background-color 0.3s ease;
                "
            >
                Send
            </button>
        </form>
        </div>
    </div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
  $('#chat-form').on('submit', function (e) {
    e.preventDefault();

    let content = $('#message-content').val().trim();
    let receiver = $('#receiver').val();
    let csrfToken = $('input[name="csrfmiddlewaretoken"]').val();

    if (!content) return;

    $.post('/send/', {
      receiver: receiver,
      content: content,
      csrfmiddlewaretoken: csrfToken
    }, function (response) {
      $('#message-content').val('');

      const now = new Date();

      const dateOptions = { year: 'numeric', month: 'long', day: 'numeric' };
      const timeOptions = { hour: 'numeric', minute: 'numeric', hour12: true };

      const messageId = response.message_id;

      const datePart = now.toLocaleDateString(undefined, dateOptions);
      let timePart = now.toLocaleTimeString(undefined, timeOptions)
        .replace('AM', 'a.m.')
        .replace('PM', 'p.m.');

      // Combine with a comma, no "at"
      const formattedDate = `${datePart}, ${timePart}`;



  $('#chat-log').append(`
    <div style="margin: 10px 0; text-align: right;">
      <strong>{{ request.user.username }}</strong>: ${content}<br>
      <small>${formattedDate}</small>
      <div style="font-size: 12px; color: #6c757d;">Delivered</div>
<form action="/pin/${messageId}/" method="post" style="display:inline;">
                      {% csrf_token %}
                      <button type="submit" class="btn btn-sm" style="margin-left: 8px; background-color: #ffc107; color: black; border: none; padding: 2px 8px; border-radius: 4px; cursor: pointer;">
                        {% if msg.pinned %}Unpin{% else %}Pin{% endif %}
                      </button>
                    </form>
      <form action="/delete/${messageId}/" method="post" style="display:inline;">
        <input type="hidden" name="csrfmiddlewaretoken" value="${csrfToken}">
        <button type="submit" class="btn btn-danger btn-sm" style="margin-top:5px; background-color: #dc3545; color: white; border: none; padding: 2px 8px; border-radius: 4px; cursor: pointer;">Delete</button>
      </form>
    
    
      </div>
  `);

      $('#chat-log').scrollTop($('#chat-log')[0].scrollHeight);
    }).fail(function (xhr) {
      alert('Error: ' + (xhr.responseJSON?.message || 'Something went wrong.'));
    });
  });

  // Scroll to bottom on load
  $(document).ready(function () {
    $('#chat-log').scrollTop($('#chat-log')[0].scrollHeight);
  });
</script>
    </div>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        const toggle = document.querySelector('.dropdown-toggle');
        const menu = document.querySelector('.dropdown-menu');
        toggle.addEventListener('click', function () {
            menu.style.display = menu.style.display === 'block' ? 'none' : 'block';
        });
    });

    document.querySelectorAll('small[data-timestamp]').forEach(el => {
  const serverTime = el.getAttribute('data-timestamp');
  if (serverTime) {
    const date = new Date(serverTime);
    const options = { 
      year: 'numeric', 
      month: 'long', 
      day: 'numeric',
      hour: 'numeric',
      minute: 'numeric',
      hour12: true
    };
    let formatted = date.toLocaleString(undefined, options)
      .replace('AM', 'a.m.')
      .replace('PM', 'p.m.');
    // Remove "at" if your locale adds it (some do)
    formatted = formatted.replace(/\s?at\s?/, ', ');
    el.textContent = formatted;
  }
});

const toggle = document.getElementById("themeToggle");
        const root = document.documentElement;

        if (localStorage.getItem("theme") === "dark") {
        root.classList.add("dark");
        }

        toggle.addEventListener("click", () => {
        root.classList.toggle("dark");
        if (root.classList.contains("dark")) {
            localStorage.setItem("theme", "dark");
        } else {
            localStorage.setItem("theme", "light");
        }
        });
</script>
<script>
  const messageBox = document.getElementById("message-content");
  const receiver = document.getElementById("receiver").value;
  const draftKey = `draft-${receiver}`;

  // Load draft on page load
  document.addEventListener("DOMContentLoaded", function () {
    const saved = localStorage.getItem(draftKey);
    if (saved) {
      messageBox.value = saved;
    }

    const chatLog = document.getElementById("chat-log");
    chatLog.scrollTop = chatLog.scrollHeight;
  });

  messageBox.addEventListener("input", () => {
    localStorage.setItem(draftKey, messageBox.value);
  });

  $('#chat-form').on('submit', function (e) {
    e.preventDefault();

    let content = messageBox.value.trim();
    let csrfToken = $('input[name="csrfmiddlewaretoken"]').val();

    if (!content) return;

  });
</script>
</body>
</html>
