import { escapeHtml } from "../utils/escape-html.js";
import { t, getSiteLocale } from "../config/site.js";
import { fetchUserNotifications, postUserNotificationsMarkRead } from "../auth/session.js";

let panelEl = null;
let backdropEl = null;
let listEl = null;
let isOpen = false;
let pollTimer = null;
let itemsCache = [];
let unreadCount = 0;

function setPanelOpen(open) {
  isOpen = open;
  globalThis.__siteNotificationsOpen = open;
  if (panelEl) {
    panelEl.hidden = !open;
    panelEl.classList.toggle("is-open", open);
    panelEl.setAttribute("aria-hidden", open ? "false" : "true");
  }
  if (backdropEl) {
    backdropEl.hidden = !open;
    backdropEl.classList.toggle("is-open", open);
    backdropEl.setAttribute("aria-hidden", open ? "false" : "true");
  }
  if (open) {
    document.body.classList.add("overflow-hidden");
    void loadAndRenderList();
  } else if (
    !globalThis.__siteAuthModalOpen &&
    !globalThis.__sitePromoModalOpen &&
    !globalThis.__siteGameSelectorModalOpen &&
    !globalThis.__siteNewsModalOpen
  ) {
    document.body.classList.remove("overflow-hidden");
  }
}

function formatNotifDate(ts) {
  if (!ts || !Number.isFinite(ts)) return "";
  try {
    const loc = getSiteLocale() === "en" ? "en-GB" : "tr-TR";
    return new Intl.DateTimeFormat(loc, {
      day: "2-digit",
      month: "short",
      hour: "2-digit",
      minute: "2-digit",
    }).format(new Date(ts * 1000));
  } catch {
    return "";
  }
}

function updateBadges() {
  const label = unreadCount > 99 ? "99+" : unreadCount > 0 ? String(unreadCount) : "";
  document.querySelectorAll("[data-notifications-badge]").forEach((el) => {
    if (label) {
      el.textContent = label;
      el.hidden = false;
    } else {
      el.textContent = "";
      el.hidden = true;
    }
  });
  document.querySelectorAll(".site-notifications-bell").forEach((btn) => {
    btn.setAttribute("aria-label", unreadCount > 0 ? t("notificationsAriaUnread").replace("{n}", String(unreadCount)) : t("notificationsAria"));
  });
}

function renderList() {
  if (!listEl) return;
  if (!itemsCache.length) {
    listEl.innerHTML = `<p class="site-notifications-panel__empty">${escapeHtml(t("notificationsEmpty"))}</p>`;
    return;
  }
  listEl.innerHTML = itemsCache
    .map((item) => {
      const unreadClass = item.read ? "" : " site-notifications-item--unread";
      const linkHint = item.linkUrl
        ? `<span class="site-notifications-item__meta">${escapeHtml(t("notificationsHasLink"))}</span>`
        : "";
      return `<button type="button" class="site-notifications-item${unreadClass}" data-notification-id="${item.id}" data-link-url="${escapeHtml(item.linkUrl || "")}">
        <p class="site-notifications-item__title">${escapeHtml(item.title)}</p>
        <p class="site-notifications-item__body">${escapeHtml(item.body)}</p>
        <span class="site-notifications-item__meta">${escapeHtml(formatNotifDate(item.createdAt))}</span>
        ${linkHint}
      </button>`;
    })
    .join("");
}

async function loadAndRenderList() {
  if (!listEl) return;
  listEl.innerHTML = `<p class="site-notifications-panel__loading">${escapeHtml(t("notificationsLoading"))}</p>`;
  const res = await fetchUserNotifications();
  if (!res.ok) {
    listEl.innerHTML = `<p class="site-notifications-panel__empty">${escapeHtml(t("notificationsLoadError"))}</p>`;
    return;
  }
  itemsCache = Array.isArray(res.data.items) ? res.data.items : [];
  unreadCount = Number(res.data.unreadCount) || 0;
  updateBadges();
  renderList();
}

export async function refreshSiteNotificationsBadge() {
  const bells = document.querySelectorAll(".site-notifications-bell");
  if (!bells.length) return;
  const res = await fetchUserNotifications();
  if (!res.ok) return;
  itemsCache = Array.isArray(res.data.items) ? res.data.items : [];
  unreadCount = Number(res.data.unreadCount) || 0;
  if (isOpen) renderList();
  else updateBadges();
}

function navigateLink(linkUrl) {
  const link = String(linkUrl || "").trim();
  if (!link) return;
  if (/^https?:\/\//i.test(link)) {
    window.open(link, "_blank", "noopener,noreferrer");
    return;
  }
  const path = link.startsWith("/") ? link : `/${link}`;
  const go = globalThis.__siteNavigateTo;
  if (typeof go === "function") go(path);
  else window.location.hash = path === "/" ? "#/" : `#${path}`;
}

async function onItemClick(id, linkUrl) {
  const nid = Number(id);
  if (nid > 0) {
    await postUserNotificationsMarkRead({ action: "mark_read", ids: [nid] });
    const item = itemsCache.find((x) => x.id === nid);
    if (item) item.read = true;
    unreadCount = itemsCache.filter((x) => !x.read).length;
    updateBadges();
    renderList();
  }
  setPanelOpen(false);
  if (linkUrl) navigateLink(linkUrl);
}

async function markAllRead() {
  await postUserNotificationsMarkRead({ action: "mark_read", markAll: true });
  itemsCache = itemsCache.map((x) => ({ ...x, read: true }));
  unreadCount = 0;
  updateBadges();
  renderList();
}

function startPolling() {
  stopPolling();
  pollTimer = window.setInterval(() => {
    if (document.hidden) return;
    void refreshSiteNotificationsBadge();
  }, 60000);
}

function stopPolling() {
  if (pollTimer) {
    clearInterval(pollTimer);
    pollTimer = null;
  }
}

function ensurePanelInBody() {
  if (!panelEl || !backdropEl) return;
  if (panelEl.parentElement !== document.body) {
    document.body.appendChild(backdropEl);
    document.body.appendChild(panelEl);
  }
}

export function mountSiteNotificationsRoot(root) {
  if (!root) return;
  if (root.dataset.mounted === "1") {
    panelEl = document.getElementById("site-notifications-panel");
    backdropEl = document.getElementById("site-notifications-backdrop");
    listEl = document.getElementById("site-notifications-list");
    ensurePanelInBody();
    bindPanelControls();
    return;
  }
  root.dataset.mounted = "1";
  root.innerHTML = `
    <div class="site-notifications-panel__backdrop" id="site-notifications-backdrop" hidden aria-hidden="true"></div>
    <div class="site-notifications-panel" id="site-notifications-panel" hidden role="dialog" aria-modal="true" aria-labelledby="site-notifications-title">
      <div class="site-notifications-panel__head">
        <h2 class="site-notifications-panel__title" id="site-notifications-title">${escapeHtml(t("notificationsTitle"))}</h2>
        <div class="site-notifications-panel__actions">
          <button type="button" class="site-notifications-panel__mark-all" id="site-notifications-mark-all">${escapeHtml(t("notificationsMarkAll"))}</button>
          <button type="button" class="site-notifications-panel__close" id="site-notifications-close" aria-label="${escapeHtml(t("notificationsClose"))}">
            <svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
          </button>
        </div>
      </div>
      <div class="site-notifications-panel__list" id="site-notifications-list" role="list"></div>
    </div>`;
  panelEl = root.querySelector("#site-notifications-panel");
  backdropEl = root.querySelector("#site-notifications-backdrop");
  listEl = root.querySelector("#site-notifications-list");
  ensurePanelInBody();
  bindPanelControls();
}

let panelControlsBound = false;

function bindPanelControls() {
  if (panelControlsBound) return;
  panelControlsBound = true;

  document.addEventListener("click", (ev) => {
    if (ev.target.closest("#site-notifications-close")) {
      ev.preventDefault();
      ev.stopPropagation();
      setPanelOpen(false);
      return;
    }
    if (ev.target.closest("#site-notifications-mark-all")) {
      ev.preventDefault();
      void markAllRead();
      return;
    }
    if (ev.target.closest("#site-notifications-backdrop")) {
      setPanelOpen(false);
      return;
    }
    const itemBtn = ev.target.closest("[data-notification-id]");
    if (itemBtn && ev.target.closest("#site-notifications-list")) {
      void onItemClick(itemBtn.getAttribute("data-notification-id"), itemBtn.getAttribute("data-link-url"));
    }
  });

  document.addEventListener("keydown", (ev) => {
    if (ev.key === "Escape" && isOpen) setPanelOpen(false);
  });
}

function onBellClick(ev) {
  if (
    ev.target.closest("#site-notifications-panel") ||
    ev.target.closest("#site-notifications-backdrop")
  ) {
    return;
  }
  const btn = ev.target.closest(".site-notifications-bell");
  if (!btn) return;
  ev.preventDefault();
  ev.stopPropagation();
  if (!panelEl) {
    const root = document.getElementById("notifications-root");
    if (root) mountSiteNotificationsRoot(root);
  }
  setPanelOpen(!isOpen);
}

let bellsDelegated = false;

export function bindSiteNotificationBells() {
  if (!bellsDelegated) {
    bellsDelegated = true;
    document.addEventListener("click", onBellClick);
  }
  document.querySelectorAll(".site-notifications-bell").forEach((btn) => {
    btn.type = "button";
  });
}

export function onSiteNotificationsUserChange(user) {
  if (user) {
    void refreshSiteNotificationsBadge();
    startPolling();
  } else {
    stopPolling();
    itemsCache = [];
    unreadCount = 0;
    updateBadges();
    setPanelOpen(false);
  }
}

const BELL_ICON_SVG = `<svg class="site-notifications-bell__icon h-5 w-5 xl:h-[1.35rem] xl:w-[1.35rem]" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14.857 17.082a23.848 23.848 0 005.454-1.31A8.967 8.967 0 0118 9.75v-.7V9A6 6 0 006 9v.75a8.967 8.967 0 01-2.312 6.022c1.733.64 3.56 1.085 5.455 1.31m5.714 0a24.255 24.255 0 01-5.714 0m5.714 0a3 3 0 11-5.714 0"/>
    </svg>`;

export function notificationsBellHtml(extraClass = "") {
  return `<button type="button" class="site-notifications-bell site-header__action-btn flex h-9 w-9 shrink-0 items-center justify-center xl:h-10 xl:w-10 ${extraClass}" aria-label="${escapeHtml(t("notificationsAria"))}">
    ${BELL_ICON_SVG}
    <span class="site-notifications-bell__badge" data-notifications-badge hidden aria-hidden="true"></span>
  </button>`;
}
