import { getCheckedMessages, getSession, logout } from "./api.js";
import { initMessageWidget } from "./message-widget.js";

const welcomeMessage = document.getElementById("welcomeMessage");
const logoutBtn = document.getElementById("logoutBtn");
const checkedMessagesList = document.getElementById("checkedMessagesList");

function escapeHtml(value) {
  return String(value ?? "")
    .replaceAll("&", "&amp;")
    .replaceAll("<", "&lt;")
    .replaceAll(">", "&gt;")
    .replaceAll('"', "&quot;")
    .replaceAll("'", "&#39;");
}

function formatDateTime(value) {
  const date = new Date(String(value ?? "").replace(" ", "T"));
  if (Number.isNaN(date.getTime())) return value || "-";

  return new Intl.DateTimeFormat("tr-TR", {
    day: "2-digit",
    month: "2-digit",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit"
  }).format(date).replace(",", "");
}

async function loadCheckedMessages() {
  const messages = await getCheckedMessages();
  checkedMessagesList.innerHTML = "";

  if (!messages.length) {
    checkedMessagesList.innerHTML = '<p class="empty-state">Henüz checklenen mesaj yok.</p>';
    return;
  }

  messages.forEach((message) => {
    const item = document.createElement("article");
    item.className = "message-item message-item-other";
    item.innerHTML = `
      <div class="message-item-top">
        <div class="message-item-meta">
          <strong>${escapeHtml(message.username)}</strong>
          <span>Gönderim: ${escapeHtml(formatDateTime(message.createdAt))}</span>
          <span>Check: ${escapeHtml(formatDateTime(message.checkedAt))}</span>
        </div>
      </div>
      <p class="message-item-text">${escapeHtml(message.message)}</p>
    `;
    checkedMessagesList.appendChild(item);
  });
}

async function init() {
  const session = await getSession();
  if (!session.authenticated || session.user?.role !== "admin") {
    window.location.replace("index.php");
    return;
  }

  welcomeMessage.textContent = `Hoş geldin ${session.user.username}`;
  logoutBtn?.addEventListener("click", async () => {
    try {
      await logout();
    } finally {
      window.location.replace("index.php");
    }
  });

  await loadCheckedMessages();
  await initMessageWidget();
}

init();
