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

const welcomeMessage = document.getElementById("welcomeMessage");
const logoutBtn = document.getElementById("logoutBtn");
const mobilePageNavToggle = document.getElementById("mobilePageNavToggle");
const messagesPageNav = document.getElementById("messagesPageNav");
const messageForm = document.getElementById("messageForm");
const messageInput = document.getElementById("messageInput");
const messageFormStatus = document.getElementById("messageFormStatus");
const messagesList = document.getElementById("messagesList");

let currentUser = null;
let mobileNavOpen = false;

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(",", "");
}

function showStatus(message, isError = false) {
  messageFormStatus.textContent = message;
  messageFormStatus.classList.remove("hidden", "error-text");
  messageFormStatus.classList.add(isError ? "error-text" : "helper-text");
}

function setMobileNavState(isOpen) {
  mobileNavOpen = Boolean(isOpen);
  if (!mobilePageNavToggle || !messagesPageNav) return;

  messagesPageNav.classList.toggle("page-nav-mobile-open", mobileNavOpen);
  mobilePageNavToggle.setAttribute("aria-expanded", mobileNavOpen ? "true" : "false");
}

function syncMobileHeader() {
  if (!mobilePageNavToggle || !messagesPageNav) return;

  const isMobile = window.innerWidth <= 860;
  mobilePageNavToggle.classList.toggle("hidden", !isMobile);

  if (isMobile) {
    messagesPageNav.classList.toggle("page-nav-mobile-open", mobileNavOpen);
    return;
  }

  messagesPageNav.classList.remove("page-nav-mobile-open");
  mobilePageNavToggle.setAttribute("aria-expanded", "false");
  mobileNavOpen = false;
}

function renderMessages(messages) {
  messagesList.innerHTML = "";

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

  [...messages].reverse().forEach((message) => {
    const item = document.createElement("article");
    const isOwnMessage = Number(message.userId || 0) === Number(currentUser?.id || 0);
    item.className = `message-item${isOwnMessage ? " message-item-own" : " message-item-other"}`;
    item.innerHTML = `
      <div class="message-item-top">
        <div class="message-item-meta">
          <strong>${escapeHtml(message.username)}</strong>
          <span>${escapeHtml(formatDateTime(message.createdAt))}</span>
        </div>
        ${
          currentUser?.role === "admin"
            ? `<button class="file-action-btn file-action-btn-danger" type="button" data-delete-message-id="${message.id}" aria-label="Mesajı sil">×</button>`
            : ""
        }
      </div>
      <p class="message-item-text">${escapeHtml(message.message)}</p>
    `;
    messagesList.appendChild(item);
  });

  window.requestAnimationFrame(() => {
    window.scrollTo({ top: document.body.scrollHeight, behavior: "smooth" });
  });

  messagesList.querySelectorAll("[data-delete-message-id]").forEach((button) => {
    button.addEventListener("click", async () => {
      const id = Number(button.dataset.deleteMessageId || 0);
      if (!id) return;

      const confirmed = window.confirm("Bu mesajı silmek istiyor musunuz?");
      if (!confirmed) return;

      try {
        await deleteMessage(id);
        await loadMessages();
      } catch (error) {
        window.alert(error.message);
      }
    });
  });
}

async function loadMessages() {
  const messages = await getMessages();
  renderMessages(messages);
}

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

  currentUser = session.user;
  welcomeMessage.textContent = `Hoş geldin ${session.user.username}`;

  logoutBtn?.addEventListener("click", async () => {
    try {
      await logout();
    } finally {
      window.location.replace("index.php");
    }
  });

  mobilePageNavToggle?.addEventListener("click", () => {
    setMobileNavState(!mobileNavOpen);
  });

  window.addEventListener("resize", syncMobileHeader);
  syncMobileHeader();

  messageForm.addEventListener("submit", async (event) => {
    event.preventDefault();
    const message = messageInput.value.trim();
    if (!message) {
      showStatus("Mesaj boş olamaz.", true);
      return;
    }

    try {
      await postMessage(message);
      messageInput.value = "";
      showStatus("Mesaj gönderildi.");
      await loadMessages();
    } catch (error) {
      showStatus(error.message, true);
    }
  });

  await loadMessages();
  await initMessageWidget();
  window.setInterval(() => {
    loadMessages().catch(() => {});
  }, 15000);
}

init();
