import { SITE_BRAND_NAME } from "../constants/brand.js";
import { t, getSiteLocale, getSiteLogoUrl, isGamdomTurnuvaEnabled } from "../config/site.js";
import { fetchDailyBonusStatus, postDailyBonusClaim, notifyApiFailure } from "../auth/session.js";
import { destroyLottieIcons, mountLottieIcons } from "../utils/lottie-icon.js";
import { showToast } from "./toast.js";

const PROMO_LOTTIE_SRC = "assets/lottie/promo-code.json?v=3";
const WHEEL_LOTTIE_SRC = "assets/lottie/wheel.json?v=1";
const DAILY_LOTTIE_SRC = "assets/lottie/daily-bonus.json?v=2";
const PROMO_ICON_SRC = "assets/icons/promo-code.svg?v=3";
const WHEEL_ICON_SRC = "assets/icons/wheel.svg?v=1";
const DAILY_ICON_SRC = "assets/icons/daily-bonus.svg?v=2";
const GAMES_LOTTIE_SRC = "assets/lottie/games.json?v=3";
const GAMES_ICON_SRC = "assets/icons/games.svg?v=4";

function sidebarLottieIconHtml(lottieSrc, fallbackSrc) {
  return `<span class="lottie-icon-host" data-lottie-src="${lottieSrc}" data-lottie-fallback="${fallbackSrc}"></span>`;
}

function navIconSvg(paths, color = "currentColor") {
  return `<svg class="h-[1.15rem] w-[1.15rem] sm:h-5 sm:w-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2" aria-hidden="true">${paths}</svg>`;
}

const NAV = [
  {
    id: "home",
    path: "/",
    labelKey: "navHome",
    icon: navIconSvg(
      '<path stroke-linecap="round" stroke-linejoin="round" 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.75M8.25 21h8.25" />'
    ),
  },
  {
    id: "market",
    path: "/market",
    labelKey: "navMarket",
    icon: navIconSvg(
      '<path stroke-linecap="round" stroke-linejoin="round" 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.007zM8.625 10.5a.375.375 0 11-.75 0 .375.375 0 01.75 0zm7.5 0a.375.375 0 11-.75 0 .375.375 0 01.75 0z" />'
    ),
  },
  {
    id: "leaderboard",
    path: "/liderlik",
    labelKey: "navLeaderboard",
    icon: navIconSvg(
      '<path stroke-linecap="round" stroke-linejoin="round" d="M16.5 18.75h-9m9 0a3 3 0 01-3 3h-3a3 3 0 01-3-3m9 0v-3.375c0-.621-.503-1.125-1.125-1.125h-.871M7.5 18.75v-3.375c0-.621.504-1.125 1.125-1.125h.872m5.007 0H9.497m5.007 0a7.454 7.454 0 01-.982-3.172M9.497 14.25a7.454 7.454 0 00.981-3.172M5.25 4.236c-.982.143-1.854.631-2.463 1.355m12.726 0c.608-.724 1.48-1.212 2.462-1.355M5.25 4.236V4.5c0 2.108.966 3.99 2.48 5.228M5.25 4.236V2.721C7.456 2.41 9.71 2.25 12 2.25c2.291 0 4.545.16 6.75.47v1.516M18.75 4.236c.982.143 1.854.631 2.463 1.355M18.75 4.236V4.5c0 2.108-.966 3.99-2.48 5.228M18.75 4.236V2.721c-2.206-.31-4.46-.47-6.75-.47-2.29 0-4.544.16-6.75.47v1.516" />'
    ),
  },
  {
    id: "gamdom-turnuva",
    path: "/gamdom-cevrim-turnuvasi",
    labelKey: "navGamdomTurnuva",
    icon: navIconSvg(
      '<path stroke-linecap="round" stroke-linejoin="round" d="M14.25 6.087c0-.355.186-.676.401-.959.221-.29.349-.634.349-1.003 0-1.036-1.007-1.875-2.25-1.875s-2.25.84-2.25 1.875c0 .369.128.713.349 1.003.215.283.401.604.401.959v0M14.25 6.087c0 .355-.186.676-.401.959a1.72 1.72 0 01-.349 1.003c0 1.036 1.007 1.875 2.25 1.875s2.25-.84 2.25-1.875a1.72 1.72 0 00-.349-1.003 1.72 1.72 0 01-.401-.959v0M4.5 15.75h15M9 12.75h6" />' +
        '<path stroke-linecap="round" stroke-linejoin="round" d="M6.75 15.75v1.125A2.25 2.25 0 009 19.125h6a2.25 2.25 0 002.25-2.25V15.75" />'
    ),
  },
  {
    id: "wheel",
    path: "/sans-carki",
    labelKey: "navWheel",
    icon: navIconSvg(
      '<path stroke-linecap="round" stroke-linejoin="round" d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M4.031 9.865a8.25 8.25 0 0113.803-3.7l3.181 3.182m0-4.991v4.99" />'
    ),
  },
  {
    id: "games",
    path: "/oyunlar",
    labelKey: "navGames",
    icon: navIconSvg(
      '<path stroke-linecap="round" stroke-linejoin="round" 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.25m0-9v9" />'
    ),
  },
  {
    id: "game-selector",
    path: "/oyun-secici",
    labelKey: "navGameSelector",
    icon: navIconSvg(
      '<path stroke-linecap="round" stroke-linejoin="round" d="M14.25 6.087c0-.355.186-.676.401-.959.221-.29.349-.634.349-1.003 0-1.036-1.007-1.875-2.25-1.875s-2.25.84-2.25 1.875c0 .369.128.713.349 1.003.215.283.401.604.401.959v0M14.25 6.087c0 .355-.186.676-.401.959a1.72 1.72 0 01-.349 1.003c0 1.036 1.007 1.875 2.25 1.875s2.25-.84 2.25-1.875a1.72 1.72 0 00-.349-1.003 1.72 1.72 0 01-.401-.959v0M4.5 15.75h15M9 12.75h6" />' +
        '<path stroke-linecap="round" stroke-linejoin="round" d="M6.75 15.75v1.125A2.25 2.25 0 009 19.125h6a2.25 2.25 0 002.25-2.25V15.75" />'
    ),
  },
  {
    id: "special-odds",
    path: "/ozel-oranlar",
    labelKey: "navSpecialOdds",
    icon: navIconSvg(
      '<path stroke-linecap="round" stroke-linejoin="round" d="M12 2a10 10 0 100 20 10 10 0 000-20z" />' +
        '<path stroke-linecap="round" stroke-linejoin="round" d="M12 7.2l2.4 1.7.8 3-1.7 2.6h-5l-1.7-2.6.8-3 2.4-1.7z" />'
    ),
  },
  {
    id: "complaints",
    path: "/sikayet-oneri",
    labelKey: "navComplaints",
    icon: navIconSvg(
      '<path stroke-linecap="round" stroke-linejoin="round" d="M20.25 8.511c.884.284 1.5 1.128 1.5 2.097v4.286c0 1.136-.847 2.1-1.98 2.193-.34.027-.68.052-1.02.072v3.091a.75.75 0 01-1.133.634l-3.786-2.027a.75.75 0 00-.633 0L8.25 21.016a.75.75 0 01-1.134-.634v-3.09c-.34-.02-.68-.045-1.02-.072-1.133-.093-1.98-1.057-1.98-2.193V10.61c0-.969.616-1.813 1.5-2.097V6.75A2.25 2.25 0 014.5 4.5h15a2.25 2.25 0 012.25 2.25v1.761z" />'
    ),
  },
  {
    id: "affiliate",
    path: "/affiliate-gecis",
    labelKey: "navAffiliate",
    icon: navIconSvg(
      '<path stroke-linecap="round" stroke-linejoin="round" d="M13.19 8.688a4.5 4.5 0 011.242 7.244l-4.5 4.5a4.5 4.5 0 01-6.364-6.364l1.757-1.757m13.35-.622l1.757-1.757a4.5 4.5 0 00-6.364-6.364l-4.5 4.5a4.5 4.5 0 001.242 7.244" />'
    ),
  },
  {
    id: "ana-sponsors",
    path: "/ana-sponsorlar",
    labelKey: "navAnaSponsors",
    icon: navIconSvg(
      '<path stroke-linecap="round" stroke-linejoin="round" d="M3.75 6A2.25 2.25 0 016 3.75h2.25A2.25 2.25 0 0110.5 6v2.25a2.25 2.25 0 01-2.25 2.25H6a2.25 2.25 0 01-2.25-2.25V6zM3.75 15.75A2.25 2.25 0 016 13.5h2.25a2.25 2.25 0 012.25 2.25V18a2.25 2.25 0 01-2.25 2.25H6A2.25 2.25 0 013.75 18v-2.25zM13.5 6a2.25 2.25 0 012.25-2.25H18A2.25 2.25 0 0120.25 6v2.25A2.25 2.25 0 0118 10.5h-2.25a2.25 2.25 0 01-2.25-2.25V6zM13.5 15.75a2.25 2.25 0 012.25-2.25H18a2.25 2.25 0 012.25 2.25V18A2.25 2.25 0 0118 20.25h-2.25A2.25 2.25 0 0113.5 18v-2.25z" />'
    ),
  },
  {
    id: "bonuses",
    path: "/bonuslar",
    labelKey: "navBonuses",
    icon: navIconSvg(
      '<path stroke-linecap="round" stroke-linejoin="round" d="M21 11.25v8.25a1.5 1.5 0 01-1.5 1.5H5.25a1.5 1.5 0 01-1.5-1.5v-8.25M12 4.875A2.625 2.625 0 109.375 7.5H12m0 0V2.25m0 5.25h2.625A2.625 2.625 0 1117.625 7.5H12m0 0v6.75m0-3v3.75m-8.25-3h16.5" />'
    ),
  },
  {
    id: "promo-codes",
    path: "/promosyon-kodlari",
    labelKey: "navPromoCodes",
    icon: navIconSvg(
      '<path stroke-linecap="round" stroke-linejoin="round" d="M20.59 13.41l-7.17 7.17a2 2 0 01-2.83 0L2 12V2h10l8.59 8.59a2 2 0 010 2.82z" />' +
        '<path stroke-linecap="round" stroke-linejoin="round" d="M7 7h.01" />'
    ),
  },
  {
    id: "events",
    path: "/etkinlikler",
    labelKey: "navEvents",
    icon: navIconSvg(
      '<path stroke-linecap="round" stroke-linejoin="round" d="M6.75 3v2.25M17.25 3v2.25M3 18.75V7.5a2.25 2.25 0 012.25-2.25h13.5A2.25 2.25 0 0121 7.5v11.25m-18 0A2.25 2.25 0 005.25 21h13.5A2.25 2.25 0 0021 18.75m-18 0v-7.5A2.25 2.25 0 015.25 9h13.5A2.25 2.25 0 0121 11.25v7.5" />'
    ),
  },
  {
    id: "news",
    path: "/haberler",
    labelKey: "navNews",
    icon: navIconSvg(
      '<path stroke-linecap="round" stroke-linejoin="round" d="M12 7.5H8.25A2.25 2.25 0 006 5.25v-4.5A2.25 2.25 0 018.25 3h7.5A2.25 2.25 0 0118 5.25v4.5A2.25 2.25 0 0115.75 12H12m-7.5 4.5h7.5m-7.5 3H12M9 6h6m-3 3v6.75" />'
    ),
  },
  {
    id: "tickets",
    path: "/biletler",
    labelKey: "navTickets",
    icon: navIconSvg(
      '<path stroke-linecap="round" stroke-linejoin="round" d="M16.5 6v.75m0 3v.75m0 3v.75m0 3V18m-9-5.25h5.25M7.5 15h7.5m-7.5 3h7.5m3-9H6.75a2.25 2.25 0 00-2.25 2.25v10.5A2.25 2.25 0 006.75 21h10.5a2.25 2.25 0 002.25-2.25V9.75A2.25 2.25 0 0017.25 7.5z" />'
    ),
  },
  {
    id: "contact",
    path: "/iletisim",
    labelKey: "navContact",
    icon: navIconSvg(
      '<path stroke-linecap="round" stroke-linejoin="round" d="M21.75 6.75v10.5a2.25 2.25 0 01-2.25 2.25h-15a2.25 2.25 0 01-2.25-2.25V6.75m19.5 0A2.25 2.25 0 0019.5 4.5h-15a2.25 2.25 0 00-2.25 2.25m19.5 0v.243a2.25 2.25 0 01-1.07 1.916l-7.5 4.615a2.25 2.25 0 01-2.36 0L3.32 8.91a2.25 2.25 0 01-1.07-1.916V6.75" />'
    ),
  },
];

const NAV_SECTIONS = [
  { titleKey: "sectionQuickAccess", ids: ["home", "market", "games", "game-selector"] },
  {
    titleKey: "sectionExplore",
    ids: [
      "ana-sponsors",
      "bonuses",
      "promo-codes",
      "events",
      "news",
      "tickets",
      "leaderboard",
      "gamdom-turnuva",
      "wheel",
      "special-odds",
    ],
  },
  { titleKey: "sectionSupport", ids: ["complaints", "affiliate", "contact"] },
];

function navHref(path) {
  return path === "/" ? "#/" : `#${path}`;
}

export async function refreshSidebarDailyBonus(root) {
  const btn = root?.querySelector("#sidebar-daily-bonus");
  if (!btn || !(btn instanceof HTMLButtonElement)) return;

  btn.classList.remove("is-ready");
  btn.disabled = false;
  delete btn.dataset.guest;

  const res = await fetchDailyBonusStatus();
  if (!res.ok || !res.data) {
    btn.disabled = true;
    btn.title = "";
    return;
  }
  const d = res.data;
  if (!d.authenticated) {
    btn.dataset.guest = "1";
    btn.title = t("dailyBonusNeedLogin");
    return;
  }
  if (d.can_claim) {
    btn.classList.add("is-ready");
    btn.title = t("sidebarDailyBonusTitle");
    return;
  }
  btn.disabled = true;
  btn.title = t("dailyBonusAlready");
}

function syncSidebarCollapseToggleIcon() {
  const btn = document.getElementById("sidebar-toggle-desktop");
  if (!btn) return;
  const collapsed = document.body.classList.contains("sidebar-collapsed");
  btn.style.transform = collapsed ? "rotate(180deg)" : "rotate(0deg)";
  btn.style.transition = "transform .2s ease";
}

/** Call after renderHeader so #sidebar-toggle-desktop exists. */
export function bindSidebarDesktopToggle() {
  const btn = document.getElementById("sidebar-toggle-desktop");
  if (!btn) return;
  const prev = globalThis.__siteSidebarCollapseClick;
  if (typeof prev === "function") btn.removeEventListener("click", prev);
  const onClick = () => {
    if (!window.matchMedia("(min-width: 1024px)").matches) return;
    document.body.classList.toggle("sidebar-collapsed");
    syncSidebarCollapseToggleIcon();
    globalThis.__siteSyncSearchPaletteGeometry?.();
  };
  globalThis.__siteSidebarCollapseClick = onClick;
  btn.addEventListener("click", onClick);
  syncSidebarCollapseToggleIcon();
}

export function updateSidebarActive(root, activeId) {
  root.querySelectorAll("a.sidebar-link").forEach((a) => {
    const id = a.dataset.nav;
    const on = id === activeId;
    a.setAttribute("aria-current", on ? "page" : "false");
    a.className = `sidebar-link group relative flex items-center gap-2.5 rounded-xl border-l-[3px] px-3.5 py-2.5 text-sm font-medium transition-colors duration-150 ${
      on
        ? "border-l-[#ff1e1e] border-y-transparent border-r-transparent bg-[rgba(255,30,30,0.12)] text-white ring-0"
        : "border-l-transparent border-y-transparent border-r-transparent text-slate-400"
    }`;
    const wrap = a.querySelector("span.nav-icon-wrap");
    if (wrap) {
      wrap.className = `nav-icon-wrap flex h-8.5 w-8.5 shrink-0 items-center justify-center rounded-xl ring-1 transition-colors duration-150 ${
        on
          ? "bg-[#ff1e1e]/20 text-white ring-[rgba(255,30,30,0.35)] shadow-none"
          : "bg-[#1e2739] text-slate-500 ring-[rgba(255,255,255,0.06)]"
      }`;
    }
  });
}

export function renderSidebar(root) {
  destroyLottieIcons(root);
  const logoSrc = getSiteLogoUrl();
  const itemMap = Object.fromEntries(NAV.map((n) => [n.id, n]));
  const hideNavIds = new Set();
  if (!isGamdomTurnuvaEnabled()) hideNavIds.add("gamdom-turnuva");

  const groupedItems = NAV_SECTIONS.map((section) => {
    const list = section.ids
      .filter((id) => !hideNavIds.has(id))
      .map((id) => itemMap[id])
      .filter(Boolean)
      .map(
        (item) => `
      <li>
        <a href="${navHref(item.path)}"
           data-nav="${item.id}"
           aria-current="false"
           class="k-nav__item sidebar-link group relative flex items-center gap-2.5 rounded-xl border border-transparent px-3.5 py-2.5 text-sm font-medium text-slate-400 transition-colors duration-150">
          <span class="nav-icon-wrap flex h-8.5 w-8.5 shrink-0 items-center justify-center rounded-xl bg-[#1e2739] text-slate-500 ring-1 ring-[rgba(255,255,255,0.06)] transition-colors duration-150">
            ${item.icon}
          </span>
          <span class="min-w-0 flex-1 leading-snug">${t(item.labelKey)}</span>
        </a>
      </li>`
      )
      .join("");
    return `
      <div class="px-1 pb-1 pt-2 first:pt-0">
        <p class="mb-2 px-3 text-[11px] font-semibold uppercase tracking-[.11em] text-slate-500">${t(section.titleKey)}</p>
        <ul class="space-y-1.5">${list}</ul>
      </div>
    `;
  }).join("");

  const localeCode = getSiteLocale() === "en" ? "EN" : "TR";

  const quickPromo = t("quickPromoCode");
  const quickGames = t("quickGames");
  const quickWheel = t("quickWheel");
  const quickDaily = t("sidebarDailyBonus");
  const quickLottieIcon = (lottieSrc, fallbackSrc) =>
    `<span class="sidebar-quick-tile__icon" aria-hidden="true">${sidebarLottieIconHtml(lottieSrc, fallbackSrc)}</span>`;
  const quickTileBody = (title, hint) =>
    `<span class="sidebar-quick-tile__body"><span class="sidebar-quick-tile__title">${title}</span><span class="sidebar-quick-tile__hint">${hint}</span></span>`;

  const quickButtons = `
    <div class="sidebar-quick-panel site-sidebar__quick" role="group" aria-label="${t("sectionQuickAccess")}">
      <div class="sidebar-quick-grid">
        <button type="button" id="sidebar-quick-promo" class="sidebar-quick-tile sidebar-quick-tile--promo" aria-label="${quickPromo}" title="${quickPromo}">
          ${quickLottieIcon(PROMO_LOTTIE_SRC, PROMO_ICON_SRC)}
          ${quickTileBody(quickPromo, t("quickPromoHint"))}
        </button>
        <a href="#/oyunlar" class="sidebar-quick-tile sidebar-quick-tile--games" aria-label="${quickGames}" title="${quickGames}">
          ${quickLottieIcon(GAMES_LOTTIE_SRC, GAMES_ICON_SRC)}
          ${quickTileBody(quickGames, t("quickGamesHint"))}
        </a>
        <a href="#/sans-carki" class="sidebar-quick-tile sidebar-quick-tile--wheel" aria-label="${quickWheel}" title="${quickWheel}">
          ${quickLottieIcon(WHEEL_LOTTIE_SRC, WHEEL_ICON_SRC)}
          ${quickTileBody(quickWheel, t("quickWheelHint"))}
        </a>
        <button type="button" id="sidebar-daily-bonus" class="sidebar-quick-tile sidebar-quick-tile--daily" aria-label="${quickDaily}" title="${t("sidebarDailyBonusTitle")}">
          ${quickLottieIcon(DAILY_LOTTIE_SRC, DAILY_ICON_SRC)}
          ${quickTileBody(quickDaily, t("sidebarDailyBonusHint"))}
        </button>
      </div>
    </div>
  `;

  root.innerHTML = `
    <aside class="k-sidebar site-sidebar sidebar-shell fixed inset-0 z-[60] flex w-full -translate-x-full flex-col overflow-hidden border-r border-[rgba(22,119,255,0.2)] bg-[#181f2e] shadow-[0_20px_60px_-28px_rgba(0,0,0,0.75)] backdrop-blur-xl transition-transform lg:bottom-0 lg:left-0 lg:right-auto lg:top-[4.5rem] lg:z-40 lg:h-[calc(100dvh-4.5rem)] lg:max-h-[calc(100dvh-4.5rem)] lg:w-[268px] lg:translate-x-0" id="sidebar" aria-label="${t("sidebarAria")}">
      <div class="site-sidebar__scroll sidebar-scroll flex min-h-0 flex-1 flex-col overflow-y-auto overflow-x-hidden overscroll-contain">
        <div class="site-sidebar__head flex shrink-0 items-center gap-2 border-b border-[rgba(22,119,255,0.14)] px-3 sm:px-4 lg:hidden">
          <details id="sidebar-locale-details" class="group relative z-[100] shrink-0 lg:hidden [&_summary::-webkit-details-marker]:hidden">
            <summary
              class="flex h-10 min-w-[2.75rem] cursor-pointer list-none items-center justify-center gap-0.5 rounded-xl border border-[rgba(22,119,255,0.22)] bg-[#1e2739] px-2 text-[11px] font-bold uppercase tracking-wide text-slate-200 shadow-inner outline-none transition hover:border-[rgba(22,119,255,0.35)] hover:bg-[#252f44] hover:text-white focus-visible:ring-2 focus-visible:ring-accent/40"
              aria-label="${t("headerLangAria")}"
            >
              <span class="sidebar-locale-code">${localeCode}</span>
              <svg class="sidebar-locale-chevron h-3 w-3 shrink-0 text-slate-400 opacity-80 transition-transform duration-200 group-open:rotate-180" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"/></svg>
            </summary>
            <div
              class="sidebar-locale-menu absolute left-0 top-[calc(100%+0.35rem)] z-[111] min-w-[9rem] overflow-hidden rounded-xl border border-[rgba(22,119,255,0.2)] bg-[#1e2739] py-1 shadow-2xl ring-1 ring-black/50 backdrop-blur-md"
              role="group"
              aria-label="${t("headerLangAria")}"
            >
              <button type="button" data-locale-switch="tr" class="k-btn k-btn--ghost k-locale-btn flex w-full items-center px-3 py-2.5 text-left text-sm font-semibold uppercase tracking-wide text-slate-300 transition hover:bg-[#252f44] hover:text-white">TR</button>
              <button type="button" data-locale-switch="en" class="k-btn k-btn--ghost k-locale-btn flex w-full items-center px-3 py-2.5 text-left text-sm font-semibold uppercase tracking-wide text-slate-300 transition hover:bg-[#252f44] hover:text-white">EN</button>
            </div>
          </details>
          <a href="#/" class="site-sidebar__logo-link group min-w-0">
            <span class="site-sidebar__logo-box transition-transform duration-200 group-hover:scale-[1.02]">
              <img src="${logoSrc}" alt="${SITE_BRAND_NAME}" loading="eager" decoding="async" class="site-brand-logo site-brand-logo--sidebar" />
            </span>
          </a>
          <div class="site-sidebar__head-actions flex shrink-0 items-center gap-2">
            <button type="button" class="k-btn k-btn--icon btn-site-icon lg:!hidden" id="sidebar-close" aria-label="${t("sidebarClose")}">
            <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="M6 18L18 6M6 6l12 12"/></svg>
            </button>
          </div>
        </div>
        <nav class="site-sidebar__nav shrink-0 p-3.5" aria-label="${t("sidebarMainNav")}">
          ${quickButtons}
          ${groupedItems}
        </nav>
      </div>
    </aside>
    <div class="site-sidebar__backdrop fixed inset-0 z-[55] bg-[#181f2e]/75 opacity-0 pointer-events-none backdrop-blur-sm transition-opacity lg:hidden" id="sidebar-backdrop" aria-hidden="true"></div>
  `;

  const quickPanel = root.querySelector(".sidebar-quick-panel");
  if (quickPanel) mountLottieIcons(quickPanel);

  const sidebar = root.querySelector("#sidebar");
  const backdrop = root.querySelector("#sidebar-backdrop");
  const closeBtn = root.querySelector("#sidebar-close");
  function syncBottomNavHeight() {
    if (!window.matchMedia("(max-width: 1023px)").matches) return;
    const nav = document.querySelector(".site-bottom-nav");
    if (!nav) return;
    const h = Math.ceil(nav.getBoundingClientRect().height);
    if (h > 0) {
      document.documentElement.style.setProperty("--site-bottom-nav-h", `${h}px`);
    }
  }

  function openSidebar() {
    syncBottomNavHeight();
    sidebar.classList.remove("-translate-x-full");
    backdrop.classList.remove("opacity-0", "pointer-events-none");
    document.body.classList.add("overflow-hidden", "sidebar-open");
    requestAnimationFrame(syncBottomNavHeight);
  }

  function closeSidebar() {
    sidebar.classList.add("-translate-x-full");
    backdrop.classList.add("opacity-0", "pointer-events-none");
    document.body.classList.remove("overflow-hidden", "sidebar-open");
  }

  function setDesktopCollapsed(collapsed) {
    document.body.classList.toggle("sidebar-collapsed", !!collapsed);
    syncSidebarCollapseToggleIcon();
  }

  globalThis.__siteOpenSidebar = openSidebar;
  globalThis.__siteCloseSidebar = closeSidebar;

  closeBtn?.addEventListener("click", closeSidebar);
  backdrop?.addEventListener("click", closeSidebar);

  const localeDetails = root.querySelector("#sidebar-locale-details");
  if (localeDetails instanceof HTMLDetailsElement) {
    localeDetails.querySelectorAll("[data-locale-switch]").forEach((btn) => {
      btn.addEventListener("click", () => {
        localeDetails.open = false;
      });
    });
    if (globalThis.__sidebarLocaleOutsideClose) {
      document.removeEventListener("click", globalThis.__sidebarLocaleOutsideClose, true);
    }
    const onDocClick = (e) => {
      if (!localeDetails.open) return;
      const t = e.target;
      if (t instanceof Node && localeDetails.contains(t)) return;
      localeDetails.open = false;
    };
    globalThis.__sidebarLocaleOutsideClose = onDocClick;
    document.addEventListener("click", onDocClick, true);
  }
  root.querySelector("#sidebar-quick-promo")?.addEventListener("click", () => {
    globalThis.__siteOpenPromoModal?.();
    if (window.matchMedia("(max-width: 1023px)").matches) closeSidebar();
  });

  root.querySelector("#sidebar-daily-bonus")?.addEventListener("click", async () => {
    const btn = root.querySelector("#sidebar-daily-bonus");
    if (!btn || !(btn instanceof HTMLButtonElement)) return;
    if (btn.dataset.guest === "1") {
      showToast(t("dailyBonusNeedLogin"), "info");
      globalThis.__siteOpenLogin?.();
      if (window.matchMedia("(max-width: 1023px)").matches) closeSidebar();
      return;
    }
    if (btn.disabled) return;
    btn.disabled = true;
    const res = await postDailyBonusClaim();
    if (res.ok && res.data && typeof res.data.coins === "number") {
      const added = typeof res.data.added === "number" ? res.data.added : 25;
      const msg = t("dailyBonusSuccess")
        .replace("{n}", String(added))
        .replace("{coin}", t("marketCoinWord"));
      showToast(msg, "success");
      await globalThis.__siteRefreshUser?.();
      await refreshSidebarDailyBonus(root);
      if (window.matchMedia("(max-width: 1023px)").matches) closeSidebar();
      return;
    }
    if (res.data?.error === "already_claimed") {
      showToast(t("dailyBonusAlready"), "info");
      await refreshSidebarDailyBonus(root);
      return;
    }
    if (res.status === 401) {
      showToast(t("dailyBonusNeedLogin"), "info");
      globalThis.__siteOpenLogin?.();
    } else if (res.status === 0 || res.status >= 500) {
      notifyApiFailure();
    } else {
      showToast(t("dailyBonusError"), "error");
    }
    await refreshSidebarDailyBonus(root);
  });

  sidebar.querySelectorAll("a.sidebar-link, a.sidebar-quick").forEach((a) => {
    let prefetchDone = false;
    const warm = () => {
      if (prefetchDone) return;
      const href = a.getAttribute("href");
      if (!href?.startsWith("#/")) return;
      prefetchDone = true;
      const path = href.slice(1) || "/";
      globalThis.__sitePrefetchRoute?.(path);
      if (path === "/oyun-secici") {
        import("../utils/slot-games-cache.js")
          .then((m) => m.prefetchSlotGamesRoulette())
          .catch(() => {});
      }
    };
    a.addEventListener("pointerenter", warm, { passive: true });
    a.addEventListener("focus", warm);

    a.addEventListener("click", (e) => {
      const href = a.getAttribute("href");
      if (href && href.startsWith("#/")) {
        warm();
        e.preventDefault();
        const path = href.slice(1) || "/";
        const go = globalThis.__siteNavigateTo;
        if (typeof go === "function") go(path);
        else window.location.hash = href;
      }
      if (window.matchMedia("(max-width: 1023px)").matches) closeSidebar();
    });
  });
  globalThis.__siteSyncBottomNavHeight = syncBottomNavHeight;
  syncBottomNavHeight();
  window.addEventListener("resize", () => {
    syncBottomNavHeight();
    if (window.matchMedia("(min-width: 1024px)").matches) {
      backdrop.classList.add("opacity-0", "pointer-events-none");
      document.body.classList.remove("overflow-hidden", "sidebar-open");
      sidebar.classList.remove("-translate-x-full");
      setDesktopCollapsed(false);
    } else {
      sidebar.classList.add("-translate-x-full");
      document.body.classList.remove("sidebar-collapsed", "sidebar-open", "overflow-hidden");
      backdrop.classList.add("opacity-0", "pointer-events-none");
    }
  });

  if (window.matchMedia("(min-width: 1024px)").matches) {
    setDesktopCollapsed(false);
  }

  void refreshSidebarDailyBonus(root);
}
