import { t } from "../config/site.js";
import { postLogout } from "../auth/session.js";
import { showToast } from "./toast.js";

/** @type {HTMLElement | null} */
let menuPanel = null;

/** @type {HTMLElement | null} */
let openTrigger = null;

/** @type {{ username?: string, coins?: number } | null} */
let menuUser = null;

let listenersBound = false;

const ICON_USER = `<svg fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/></svg>`;
const ICON_MARKET = `<svg fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 11V7a4 4 0 00-8 0v4M5 9h14l1 12H4L5 9z"/></svg>`;
const ICON_PROMO = `<svg fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 7h.01M7 3h5c.512 0 1.024.195 1.414.586l7 7a2 2 0 010 2.828l-7 7a2 2 0 01-2.828 0l-7-7A1.994 1.994 0 013 12V7a4 4 0 014-4z"/></svg>`;
const ICON_WHEEL = `<svg fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"/></svg>`;
const ICON_TELEGRAM = `<svg fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8"/></svg>`;
const ICON_LOGOUT = `<svg fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M17 16l4-4m0 0l-4-4m4 4H7m6 4v1a3 3 0 01-3 3H6a3 3 0 01-3-3V7a3 3 0 013-3h4a3 3 0 013 3v1"/></svg>`;

function escapeHtml(s) {
  return String(s)
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;");
}

function userInitial(username) {
  const u = String(username || "U").trim();
  if (!u) return "U";
  return u.slice(0, 1).toLocaleUpperCase("tr");
}

function navigate(path) {
  closeHeaderProfileMenu();
  const go = globalThis.__siteNavigateTo;
  if (typeof go === "function") go(path);
  else window.location.hash = path === "/" ? "#/" : `#${path}`;
}

function ensureMenuPanel() {
  if (menuPanel) return menuPanel;
  menuPanel = document.createElement("div");
  menuPanel.id = "header-profile-menu-panel";
  menuPanel.className = "header-profile-menu__panel";
  menuPanel.setAttribute("role", "menu");
  menuPanel.setAttribute("aria-label", t("headerProfileMenuAria"));
  menuPanel.hidden = true;
  document.body.appendChild(menuPanel);
  return menuPanel;
}

function renderMenuContent() {
  const panel = ensureMenuPanel();
  const name = menuUser?.username ? String(menuUser.username) : "—";
  const coins = Number(menuUser?.coins) || 0;
  panel.innerHTML = `
    <div class="header-profile-menu__head" data-profile-menu-head>
      <span class="header-profile-menu__avatar" aria-hidden="true">${escapeHtml(userInitial(name))}</span>
      <div class="header-profile-menu__meta">
        <span class="header-profile-menu__name">${escapeHtml(name)}</span>
        <span class="header-profile-menu__coins" title="${escapeHtml(t("headerCoinBalance"))}">
          <span aria-hidden="true">🪙</span>
          <span class="header-profile-menu__coins-val">${coins.toLocaleString()}</span>
        </span>
      </div>
    </div>
    <div class="header-profile-menu__list">
      <button type="button" class="header-profile-menu__item" role="menuitem" data-profile-menu-action="profile">
        ${ICON_USER}
        <span>${escapeHtml(t("headerProfile"))}</span>
      </button>
      <button type="button" class="header-profile-menu__item" role="menuitem" data-profile-menu-action="market">
        ${ICON_MARKET}
        <span>${escapeHtml(t("navMarket"))}</span>
      </button>
      <button type="button" class="header-profile-menu__item" role="menuitem" data-profile-menu-action="promo">
        ${ICON_PROMO}
        <span>${escapeHtml(t("navPromoCodes"))}</span>
      </button>
      <button type="button" class="header-profile-menu__item" role="menuitem" data-profile-menu-action="wheel">
        ${ICON_WHEEL}
        <span>${escapeHtml(t("navWheel"))}</span>
      </button>
      <button type="button" class="header-profile-menu__item" role="menuitem" data-profile-menu-action="telegram">
        ${ICON_TELEGRAM}
        <span>${escapeHtml(t("profileTabTelegram"))}</span>
      </button>
    </div>
    <div class="header-profile-menu__divider" role="separator"></div>
    <div class="header-profile-menu__list">
      <button type="button" class="header-profile-menu__item header-profile-menu__item--danger" role="menuitem" data-profile-menu-action="logout">
        ${ICON_LOGOUT}
        <span>${escapeHtml(t("profileLogout"))}</span>
      </button>
    </div>
  `;

  panel.querySelectorAll("[data-profile-menu-action]").forEach((btn) => {
    btn.addEventListener("click", () => {
      const action = btn.getAttribute("data-profile-menu-action");
      if (action === "profile") return navigate("/profil");
      if (action === "market") return navigate("/market");
      if (action === "promo") return navigate("/promosyon-kodlari");
      if (action === "wheel") return navigate("/sans-carki");
      if (action === "telegram") {
        try {
          sessionStorage.setItem("site_profile_tab", "telegram");
        } catch {
          /* ignore */
        }
        return navigate("/profil");
      }
      if (action === "logout") {
        void (async () => {
          closeHeaderProfileMenu();
          await postLogout();
          showToast(t("profileLogoutToast"), "info");
          await globalThis.__siteRefreshUser?.();
          navigate("/");
        })();
      }
    });
  });
}

function positionMenu(trigger) {
  if (!menuPanel || !(trigger instanceof HTMLElement)) return;
  const rect = trigger.getBoundingClientRect();
  const gap = 8;
  const panelW = menuPanel.offsetWidth || 280;
  const panelH = menuPanel.offsetHeight || 320;
  let top = rect.bottom + gap;
  let left = rect.right - panelW;

  if (left < 8) left = 8;
  if (left + panelW > window.innerWidth - 8) left = window.innerWidth - panelW - 8;
  if (top + panelH > window.innerHeight - 8) {
    top = rect.top - panelH - gap;
    menuPanel.style.transformOrigin = "bottom right";
  } else {
    menuPanel.style.transformOrigin = "top right";
  }

  menuPanel.style.top = `${Math.max(8, top)}px`;
  menuPanel.style.left = `${left}px`;
}

export function closeHeaderProfileMenu() {
  if (!menuPanel) return;
  menuPanel.classList.remove("is-open");
  menuPanel.hidden = true;
  openTrigger?.setAttribute("aria-expanded", "false");
  openTrigger = null;
}

export function openHeaderProfileMenu(trigger) {
  if (!(trigger instanceof HTMLElement)) return;
  if (openTrigger === trigger && menuPanel?.classList.contains("is-open")) {
    closeHeaderProfileMenu();
    return;
  }
  renderMenuContent();
  openTrigger = trigger;
  trigger.setAttribute("aria-expanded", "true");
  menuPanel.hidden = false;
  menuPanel.classList.add("is-open");
  requestAnimationFrame(() => positionMenu(trigger));
  menuPanel.querySelector("[data-profile-menu-action='profile']")?.focus();
}

export function updateHeaderProfileMenu(user) {
  menuUser = user;
  if (menuPanel?.classList.contains("is-open")) {
    renderMenuContent();
    if (openTrigger) positionMenu(openTrigger);
  }
}

function bindGlobalListeners() {
  if (listenersBound) return;
  listenersBound = true;

  document.addEventListener(
    "click",
    (e) => {
      if (!menuPanel?.classList.contains("is-open")) return;
      const t = e.target;
      if (t instanceof Node && (menuPanel.contains(t) || openTrigger?.contains(t))) return;
      closeHeaderProfileMenu();
    },
    true
  );

  document.addEventListener("keydown", (e) => {
    if (e.key === "Escape") closeHeaderProfileMenu();
  });

  window.addEventListener(
    "resize",
    () => {
      if (openTrigger && menuPanel?.classList.contains("is-open")) positionMenu(openTrigger);
    },
    { passive: true }
  );

  window.addEventListener("hashchange", () => closeHeaderProfileMenu());
}

export function bindHeaderProfileMenu(root) {
  bindGlobalListeners();
  ensureMenuPanel();

  root.querySelectorAll(".header-profile-menu__trigger:not([data-profile-menu-bound])").forEach((btn) => {
    btn.dataset.profileMenuBound = "1";
    btn.addEventListener("click", (e) => {
      e.preventDefault();
      e.stopPropagation();
      if (!menuUser) {
        globalThis.__siteOpenLogin?.();
        return;
      }
      openHeaderProfileMenu(btn);
    });
  });
}

export function profileMenuTriggerHtml(extraClass = "") {
  return `
    <button
      type="button"
      class="header-profile-menu__trigger 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("headerProfile"))}"
      aria-haspopup="menu"
      aria-expanded="false"
    >
      <svg class="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="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"/></svg>
    </button>
  `;
}
