import { getSession, getVisitReports, logout } from "./api.js";

const welcomeMessage = document.getElementById("welcomeMessage");
const logoutBtn = document.getElementById("logoutBtn");
const mobilePageNavToggle = document.getElementById("mobilePageNavToggle");
const visitsPageNav = document.getElementById("visitsPageNav");
const visitReportsInfo = document.getElementById("visitReportsInfo");
const visitReportsList = document.getElementById("visitReportsList");
const createVisitReportBtn = document.getElementById("createVisitReportBtn");

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"
  }).format(date).replaceAll(".", " / ");
}

function renderReports(reports) {
  visitReportsInfo.textContent = `${reports.length} vizit`;
  visitReportsList.innerHTML = "";

  if (!reports.length) {
    visitReportsList.innerHTML = '<p class="empty-state">Henüz vizit kaydı bulunmuyor.</p>';
    return;
  }

  reports.forEach((report) => {
    const item = document.createElement("article");
    item.className = "orders-list-item visit-report-card";
    item.innerHTML = `
      <button class="orders-list-open" type="button">
        Vizit • ${escapeHtml(formatDateTime(report.createdAt))}
        <small>Güncelleme: ${escapeHtml(formatDateTime(report.updatedAt))} • ${escapeHtml(report.updatedByUsername || "-")}</small>
      </button>
      <span class="orders-link-arrow" aria-hidden="true">→</span>
    `;
    item.querySelector(".orders-list-open")?.addEventListener("click", () => {
      window.location.href = `visit-detail.php?id=${encodeURIComponent(report.id)}`;
    });
    item.querySelector(".orders-link-arrow")?.addEventListener("click", () => {
      window.location.href = `visit-detail.php?id=${encodeURIComponent(report.id)}`;
    });
    visitReportsList.appendChild(item);
  });
}

function setMobileNavState(isOpen) {
  mobileNavOpen = Boolean(isOpen);
  visitsPageNav?.classList.toggle("page-nav-mobile-open", mobileNavOpen);
  mobilePageNavToggle?.setAttribute("aria-expanded", mobileNavOpen ? "true" : "false");
}

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

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

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

async function loadReports() {
  try {
    const reports = await getVisitReports();
    renderReports(reports);
  } catch (error) {
    visitReportsList.innerHTML = `<p class="error-text">${escapeHtml(error.message)}</p>`;
  }
}

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

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

  createVisitReportBtn?.addEventListener("click", () => {
    window.location.href = "visit-detail.php";
  });

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

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

  window.addEventListener("resize", syncMobileHeader);
  syncMobileHeader();
  await loadReports();
}

init();
