import { SOCIAL } from "../data/social.js";
import { SITE_BRAND_NAME } from "../constants/brand.js";
import { t, getSiteLogoUrl } from "../config/site.js";
import { themeToggleButtonHtml } from "../utils/theme.js";
import { notificationsBellHtml, bindSiteNotificationBells } from "./site-notifications.js";
import {
  bindHeaderProfileMenu,
  updateHeaderProfileMenu,
  profileMenuTriggerHtml,
} from "./header-profile-menu.js";

/** Mobil alt menü orta buton — ev ikonu, yükseltilmiş FAB (alt bar only) */
function bottomNavMenuIconSvg() {
  return `<span class="bottom-nav-center__icon" aria-hidden="true">
    <svg class="bottom-nav-menu-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" aria-hidden="true">
      <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.8" d="m2.25 12 8.954-8.955c.44-.439 1.152-.439 1.591 0L21.75 12M4.5 9.75v10.125c0 .621.504 1.125 1.125 1.125H9.75v-4.875c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125V21h4.125c.621 0 1.125-.504 1.125-1.125V9.75"/>
    </svg>
  </span>`;
}

export function updateHeaderAuth(user) {
  const guestEls = document.querySelectorAll('[data-auth-area="guest"]');
  const userEls = document.querySelectorAll('[data-auth-area="user"]');
  guestEls.forEach((el) => {
    const on = !user;
    el.classList.toggle("hidden", !on);
    if (!el.classList.contains("header-auth-guest-mobile")) {
      el.classList.toggle("flex", on);
    }
  });
  document.querySelectorAll(".header-mobile-notifications").forEach((el) => {
    const on = !!user;
    el.classList.toggle("hidden", !on);
    el.classList.toggle("flex", on);
  });

  userEls.forEach((el) => {
    const on = !!user;
    el.classList.toggle("hidden", !on);
    el.classList.toggle("flex", on);
    if (user) {
      el.querySelectorAll(".header-coins").forEach((n) => {
        n.textContent = String(user.coins);
      });
    }
  });
  document.querySelectorAll(".header-profile-menu__trigger").forEach((btn) => {
    if (user) {
      btn.setAttribute("aria-label", t("headerProfile"));
    } else {
      btn.setAttribute("aria-label", t("headerLogin"));
    }
    btn.removeAttribute("title");
  });
  updateHeaderProfileMenu(user);
}

export function renderHeader(root) {
  const logoSrc = getSiteLogoUrl();
  const socialCount = Math.max(1, SOCIAL.length);
  const links = SOCIAL.map(
    (s) => `
    <a href="${s.href}" class="k-link k-link--social btn-social-brand btn-social-brand--header min-w-0 w-full shrink-0 justify-center" rel="noopener noreferrer" target="_blank" aria-label="${s.name}">
      <svg class="h-3.5 w-3.5 shrink-0 sm:h-4 sm:w-4" viewBox="0 0 24 24" aria-hidden="true">${s.icon}</svg>
      <span class="min-w-0 truncate">${s.name}</span>
    </a>`
  ).join("");

  root.innerHTML = `
    <header class="k-header site-header site-header--unified">
      <div class="site-header__bar flex w-full min-w-0 flex-col gap-3 overflow-x-visible px-2 py-3 sm:px-6 sm:py-3.5 lg:grid lg:min-h-[4.5rem] lg:grid-cols-[268px_minmax(0,1fr)_auto] lg:items-stretch lg:gap-0 lg:overflow-x-clip lg:px-0 lg:py-0">
        <div class="site-header__brand hidden min-w-0 shrink-0 items-center gap-2 px-4 lg:flex lg:border-r">
          <button type="button" class="k-btn k-btn--icon btn-site-icon site-header__brand-toggle site-header__action-btn shrink-0" id="sidebar-toggle-desktop" aria-label="${t("sidebarCollapse")}" title="${t("sidebarCollapse")}">
            <svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 19l-7-7 7-7"/></svg>
          </button>
          <a href="#/" class="site-header__logo-link site-header__logo-link--desktop min-w-0 w-full" aria-label="${SITE_BRAND_NAME} ${t("headerHomePage")}">
            <span class="site-header__logo-box site-header__logo-box--desktop">
              <img src="${logoSrc}" alt="" decoding="async" fetchpriority="high" class="site-brand-logo site-brand-logo--header" />
            </span>
          </a>
        </div>
        <div class="site-header__mobile flex flex-col gap-2 lg:hidden">
          <div class="site-header__mobile-top relative z-20 w-full">
            <div class="site-header__mobile-start">
              <button type="button" class="k-btn k-btn--icon btn-site-icon site-header__mobile-btn js-menu-open flex h-10 w-10 shrink-0 items-center justify-center p-0" aria-label="${t("headerOpenMenu")}">
                <svg class="h-5 w-5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16"/></svg>
              </button>
              ${themeToggleButtonHtml(t("themeToggleAria"), "site-header__mobile-btn flex h-10 w-10 shrink-0 items-center justify-center p-0 lg:hidden")}
            </div>
            <div class="site-header__mobile-logo">
              <a href="#/" class="site-header__logo-link site-header__logo-link--mobile flex w-full items-center justify-center transition" aria-label="${SITE_BRAND_NAME} ${t("headerHomePage")}">
                <span class="site-header__logo-box site-header__logo-box--mobile">
                  <img src="${logoSrc}" alt="" decoding="async" fetchpriority="high" class="site-brand-logo site-brand-logo--header" />
                </span>
              </a>
            </div>
            <div class="site-header__mobile-end">
              <button type="button" id="site-search-trigger-mobile" class="k-btn k-btn--icon btn-site-icon site-header__mobile-btn flex h-10 w-10 shrink-0 items-center justify-center p-0" aria-label="${t("headerSearchSr")}">
                <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="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/></svg>
              </button>
              <div data-auth-area="user" class="hidden header-mobile-notifications flex h-10 items-center">
                ${notificationsBellHtml("site-header__mobile-btn flex h-10 w-10")}
              </div>
              <div class="header-profile-menu header-mobile-profile flex h-10 items-center">
                ${profileMenuTriggerHtml("k-btn k-btn--icon btn-site-icon site-header__mobile-btn header-mobile-profile-btn h-10 w-10 p-0")}
              </div>
            </div>
          </div>
          <div data-auth-area="guest" class="header-auth-guest-mobile hidden w-full grid grid-cols-2 gap-2">
            <button type="button" class="auth-open-login k-btn k-btn--secondary btn-site-secondary header-auth-btn">
              ${t("headerLogin")}
            </button>
            <button type="button" class="auth-open-register k-btn k-btn--primary btn-site-register header-auth-btn">
              ${t("headerRegister")}
            </button>
          </div>
          <div data-auth-area="user" class="hidden w-full min-w-0 flex-col gap-2">
            <div class="grid w-full min-w-0 grid-cols-2 gap-2">
              <button type="button" class="k-btn k-btn--ghost header-mobile-coin-btn inline-flex min-h-[2.75rem] items-center justify-center gap-1.5 rounded-xl border border-sky-500/30 bg-gradient-to-b from-sky-500/[0.15] to-sky-600/[0.08] px-2 py-2 text-sm font-semibold tabular-nums text-sky-50 shadow-[inset_0_1px_0_rgba(255,255,255,0.07)] ring-1 ring-white/[0.06] transition hover:border-sky-400/40 hover:from-sky-500/20 active:scale-[0.99]" title="${t("headerCoinBalance")}" aria-label="${t("headerCoinBalance")}">
                <span aria-hidden="true" class="text-base leading-none">🪙</span>
                <span class="header-coins min-w-[2ch] text-sm">0</span>
              </button>
              <button type="button" class="header-mobile-market-btn k-btn k-btn--secondary btn-site-secondary inline-flex min-h-[2.75rem] items-center justify-center gap-1.5 rounded-xl px-2 py-2 text-xs font-semibold sm:text-sm">
                <svg class="h-4 w-4 shrink-0 opacity-90" 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>
                ${t("navMarket")}
              </button>
            </div>
          </div>
        </div>
        <div class="site-header__mid hidden min-w-0 items-center gap-3 overflow-hidden lg:col-start-2 lg:flex lg:justify-start lg:gap-4 lg:px-5 xl:gap-5 xl:px-6">
        <div class="site-header__search hidden w-full max-w-[min(100%,calc(14rem-60px))] shrink-0 items-center gap-2 sm:gap-3 lg:flex lg:max-w-[calc(min(18rem,22vw)-30px)] xl:max-w-[calc(min(20rem,24vw)-30px)]">
          <div class="site-header__search-field relative min-w-0 w-full">
            <span class="sr-only">${t("headerSearchSr")}</span>
            <svg class="pointer-events-none absolute left-3 top-1/2 z-[1] h-4 w-4 -translate-y-1/2 text-slate-500" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z"/></svg>
            <button type="button" id="site-search-trigger" class="site-header__search-trigger k-btn k-btn--ghost k-search-trigger flex w-full min-w-0 items-center rounded-[0.875rem] py-2.5 pl-10 pr-3 text-left text-sm shadow-none ring-0 sm:py-3 sm:text-base lg:py-2 lg:text-xs xl:py-2.5 xl:text-sm">
              <span class="min-w-0 truncate">${t("headerSearchPlaceholder")}</span>
            </button>
          </div>
        </div>
        <div class="site-header__social hidden min-w-0 flex-1 flex-col items-center gap-1.5 lg:flex lg:justify-center lg:overflow-visible">
          <p class="site-header__social-label text-[10px] font-semibold uppercase tracking-[0.2em] text-slate-500 lg:sr-only">${t("headerSocial")}</p>
          <div class="site-header__social-wrap flex w-full min-w-0 justify-center rounded-xl border border-transparent bg-transparent px-2 py-1.5 sm:px-2.5">
            <div class="header-social-track site-header__social-track w-full max-w-full min-w-0" role="presentation">
              <nav class="header-social-track__inner" style="--social-count:${socialCount}" aria-label="${t("headerSocialNav")}">${links}</nav>
            </div>
          </div>
        </div>
        </div>
        <div class="site-header__toolbar hidden shrink-0 flex-nowrap items-center justify-end gap-1.5 self-center px-4 lg:flex lg:border-l lg:px-5 xl:gap-2 xl:pr-8">
          ${themeToggleButtonHtml(t("themeToggleAria"), "site-header__action-btn hidden h-9 w-9 shrink-0 items-center justify-center lg:inline-flex xl:h-10 xl:w-10")}
          <div class="site-header__lang mr-0.5 inline-flex items-center gap-1 xl:mr-1" role="group" aria-label="${t("headerLangAria")}">
            <button type="button" data-locale-switch="tr" class="site-header__action-btn site-header__locale-btn k-btn k-btn--ghost k-locale-btn flex h-9 w-9 shrink-0 items-center justify-center p-0 text-[11px] font-bold tracking-wide xl:h-10 xl:w-10">TR</button>
            <button type="button" data-locale-switch="en" class="site-header__action-btn site-header__locale-btn k-btn k-btn--ghost k-locale-btn flex h-9 w-9 shrink-0 items-center justify-center p-0 text-[11px] font-bold tracking-wide xl:h-10 xl:w-10">EN</button>
          </div>
          <div data-auth-area="user" class="hidden flex-nowrap items-center gap-1.5">
            ${notificationsBellHtml()}
          </div>
          <button type="button" class="site-header__action-btn site-chat-toggle flex h-9 w-9 shrink-0 items-center justify-center xl:h-10 xl:w-10" aria-label="${t("chatOpenAria")}">
            <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="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"/></svg>
          </button>
          <div data-auth-area="guest" class="hidden flex-nowrap items-center gap-1.5 xl:gap-2">
            <button type="button" class="auth-open-login k-btn k-btn--secondary btn-site-secondary header-auth-btn">
              ${t("headerLogin")}
            </button>
            <button type="button" class="auth-open-register k-btn k-btn--primary btn-site-register header-auth-btn">
              ${t("headerRegister")}
            </button>
          </div>
          <div data-auth-area="user" class="hidden flex-nowrap items-center gap-2 xl:gap-3">
            <div class="header-profile-menu shrink-0">
              ${profileMenuTriggerHtml("")}
            </div>
            <span class="site-header__coin-badge inline-flex items-center gap-2 rounded-xl px-3 py-1.5 text-xs font-semibold" title="${t("headerCoinBalance")}">
              <span class="select-none text-[10px] font-bold uppercase leading-none tracking-[0.12em] text-sky-200/80">${t("headerCoin")}</span>
              <span class="inline-flex items-center gap-1 tabular-nums text-sky-50">
                <span aria-hidden="true" class="text-sm opacity-90">🪙</span><span class="header-coins min-w-[1.25ch] text-sm">0</span>
              </span>
            </span>
          </div>
        </div>
      </div>
    </header>
    <nav class="k-bottom-nav site-bottom-nav fixed inset-x-0 bottom-0 z-[68] grid h-[72px] grid-cols-5 border-t border-[rgba(22,119,255,0.14)] bg-[#181f2e]/96 px-2 pb-[max(env(safe-area-inset-bottom),0.35rem)] pt-2 backdrop-blur-xl lg:hidden" aria-label="${t("bottomNavAria")}">
      <button type="button" class="k-nav__item bottom-nav-btn inline-flex flex-col items-center justify-center gap-1 rounded-xl text-slate-300 transition hover:bg-[#252f44] hover:text-white" data-bottom-nav="home" aria-label="${t("navHome")}">
        <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="1.8" d="m2.25 12 8.954-8.955c.44-.439 1.152-.439 1.591 0L21.75 12M4.5 9.75v10.125c0 .621.504 1.125 1.125 1.125H9.75v-4.875c0-.621.504-1.125 1.125-1.125h2.25c.621 0 1.125.504 1.125 1.125V21h4.125c.621 0 1.125-.504 1.125-1.125V9.75"/></svg>
        <span class="text-[11px] font-medium">${t("bottomNavHome")}</span>
      </button>
      <button type="button" class="k-nav__item bottom-nav-btn inline-flex flex-col items-center justify-center gap-1 rounded-xl text-slate-300 transition hover:bg-[#252f44] hover:text-white" data-bottom-nav="market" aria-label="${t("navMarket")}">
        <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="1.8" d="M15.75 10.5V6a3.75 3.75 0 10-7.5 0v4.5m11.356-1.993l1.263 12c.07.665-.45 1.243-1.119 1.243H4.25a1.125 1.125 0 01-1.12-1.243l1.264-12A1.125 1.125 0 015.513 7.5h12.974c.576 0 1.059.435 1.119 1.007z"/></svg>
        <span class="text-[11px] font-medium">${t("bottomNavMarket")}</span>
      </button>
      <button type="button" class="k-nav__item k-nav__item--center bottom-nav-center inline-flex flex-col items-center justify-center gap-1" data-bottom-nav="menu" aria-label="${t("bottomNavMenu")}">
        ${bottomNavMenuIconSvg()}
        <span class="bottom-nav-center__label text-[11px] font-medium">${t("bottomNavMenu")}</span>
      </button>
      <button type="button" class="k-nav__item bottom-nav-btn inline-flex flex-col items-center justify-center gap-1 rounded-xl text-slate-300 transition hover:bg-[#252f44] hover:text-white" data-bottom-nav="games" aria-label="${t("navGames")}">
        <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="1.8" d="M21 7.5l-9-5.25L3 7.5m18 0l-9 5.25m9-5.25v9l-9 5.25M3 7.5l9 5.25M3 7.5v9l9 5.25"/></svg>
        <span class="text-[11px] font-medium">${t("bottomNavGames")}</span>
      </button>
      <button type="button" class="k-nav__item bottom-nav-btn site-chat-toggle inline-flex flex-col items-center justify-center gap-1 rounded-xl text-slate-300 transition hover:bg-[#252f44] hover:text-white" aria-label="${t("chatOpenAria")}">
        <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="1.8" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"/></svg>
        <span class="text-[11px] font-medium">${t("bottomNavChat")}</span>
      </button>
    </nav>
  `;

  bindSiteNotificationBells();

  root.querySelectorAll(".js-menu-open").forEach((btn) => {
    btn.addEventListener("click", () => globalThis.__siteOpenSidebar?.());
  });

  bindHeaderProfileMenu(root);

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

  root.querySelector(".header-mobile-coin-btn")?.addEventListener("click", () => {
    navigateToPath("/profil");
  });

  root.querySelector(".header-mobile-market-btn")?.addEventListener("click", () => {
    navigateToPath("/market");
  });

  root.querySelectorAll("[data-bottom-nav]").forEach((btn) => {
    btn.addEventListener("click", () => {
      const target = btn.getAttribute("data-bottom-nav");
      if (target === "menu") {
        const sidebar = document.getElementById("sidebar");
        const isOpen =
          sidebar instanceof HTMLElement && !sidebar.classList.contains("-translate-x-full");
        if (isOpen) globalThis.__siteCloseSidebar?.();
        else globalThis.__siteOpenSidebar?.();
        return;
      }
      if (target === "home") return navigateToPath("/");
      if (target === "market") return navigateToPath("/market");
      if (target === "games") return navigateToPath("/oyunlar");
    });
  });

  globalThis.__siteSyncBottomNavHeight?.();
  requestAnimationFrame(() => globalThis.__siteSyncBottomNavHeight?.());
  const bottomNav = root.querySelector(".site-bottom-nav");
  if (bottomNav && !bottomNav.dataset.navHeightObserved && typeof ResizeObserver !== "undefined") {
    bottomNav.dataset.navHeightObserved = "1";
    const ro = new ResizeObserver(() => globalThis.__siteSyncBottomNavHeight?.());
    ro.observe(bottomNav);
  }
}
