import {
  renderSidebar,
  bindSidebarDesktopToggle,
  updateSidebarActive,
  refreshSidebarDailyBonus,
} from "./components/sidebar.js";
import { refreshHomeDailyBonus } from "./components/home-quick-actions.js";
import { renderHeader } from "./components/header.js";
import { renderPromoModal } from "./components/promo-modal.js";
import { renderGameSelectorModal } from "./components/game-selector-modal.js";
import { renderNewsModal } from "./components/news-modal.js";
import { renderAuthModals, bindAuthHeaderButtons } from "./components/auth-modals.js";
import { renderFooter } from "./components/footer.js";
import { initSearchPalette, remountSearchPaletteForLocale } from "./components/search-palette.js";
import { initSiteChat } from "./components/site-chat.js";
import { createRouter, getCurrentAppPath, getRouteMeta, normalizePathSegment } from "./router.js";
import { applyClientSeo } from "./utils/seo.js";
import { fetchSessionUser, apiUrl } from "./auth/session.js";
import { setAuthGate, authGateFlagsFromUser } from "./auth/auth-gate.js";
import { updateHeaderAuth } from "./components/header.js";
import {
  mountSiteNotificationsRoot,
  bindSiteNotificationBells,
  onSiteNotificationsUserChange,
  refreshSiteNotificationsBadge,
} from "./components/site-notifications.js";
import { debounce } from "./utils/debounce.js";
import { loadSocial } from "./data/social.js";
import {
  applySiteCustomCss,
  isSiteMaintenanceActive,
  loadSite,
  loadGamdomTurnuva,
  loadPopup,
  loadGamesCovers,
  showSitePopupIfNeeded,
  bindLocaleSwitcher,
  dataJsonUrl,
} from "./config/site.js";
import { mountSiteMaintenanceScreen } from "./components/site-maintenance.js";
import { initSiteTheme, bindThemeToggle, updateThemeToggleUi } from "./utils/theme.js";
import { prefetchSlotGamesRoulette } from "./utils/slot-games-cache.js";
import { fetchHomeCampaignEvents, fetchHomeTicketEvents } from "./utils/home-public-cache.js";
import { prefetchHomeYoutubeFeed } from "./components/home-youtube-feed.js";
import { renderHome } from "./views/home.js";
import {
  ensureTelegramWebAppScript,
  initTelegramMiniApp,
  isInsideTelegramMiniApp,
  mightNeedTelegramMiniApp,
} from "./utils/telegram-miniapp.js";

initSiteTheme();

function scheduleIdle(fn, timeoutMs = 4000) {
  if (typeof requestIdleCallback === "function") {
    requestIdleCallback(() => fn(), { timeout: timeoutMs });
  } else {
    setTimeout(fn, 120);
  }
}

scheduleIdle(() => printConsoleBanner());

function printConsoleBanner() {
  if (typeof console === "undefined" || typeof console.log !== "function") return;
  if (window.__alpingoBannerShown) return;
  window.__alpingoBannerShown = true;

  const banner = String.raw`
   █████╗ ██╗     ██████╗
  ██╔══██╗██║     ██╔══██╗
  ███████║██║     ██████╔╝
  ██╔══██║██║     ██╔═══╝
  ██║  ██║███████╗██║
  ╚═╝  ╚═╝╚══════╝╚═╝
`;

  const titleStyle = [
    "color: #69b1ff",
    "font-weight: 700",
    "font-family: 'JetBrains Mono', 'Fira Code', Consolas, monospace",
    "text-shadow: 0 0 12px rgba(22,119,255,0.55)",
    "padding: 4px 0",
  ].join(";");

  const tagStyle = [
    "background: #1677ff",
    "color: #ffffff",
    "font-weight: 800",
    "padding: 3px 10px",
    "border-radius: 999px",
    "letter-spacing: 0.18em",
    "font-family: 'Inter', sans-serif",
  ].join(";");

  const subtleStyle = "color:#94a3b8;font-family:'Inter',sans-serif;font-size:12px;";
  const linkStyle = "color:#dbeafe;font-weight:600;";

  try {
    console.log("%c" + banner, titleStyle);
    console.log(
      "%cALP%c  resmi yayıncı ve sosyal iş birlikleri platformu",
      tagStyle,
      subtleStyle
    );
    console.log(
      "%c→ %chttps://mocker27.com%c · Telegram: %c@AAlpinGO",
      subtleStyle,
      linkStyle,
      subtleStyle,
      linkStyle
    );
    console.log(
      "%c⚠ Buraya bir şey yapıştırma! Hesabın çalınabilir veya bilgilerin başkasıyla paylaşılır.",
      "color:#fbbf24;font-weight:700;font-family:'Inter',sans-serif;"
    );
  } catch {
    console.log("ALP — https://mocker27.com");
  }
}

function bootSecondaryData() {
  void Promise.allSettled([
    loadGamesCovers(),
    fetchHomeCampaignEvents(),
    fetchHomeTicketEvents(),
    prefetchHomeYoutubeFeed(),
    fetch(dataJsonUrl("sponsors.json"), { credentials: "omit", cache: "default" }),
  ]);
}

const routeLoaders = {
  "/": () => Promise.resolve(renderHome),
  "/ana-sponsorlar": () => import("./views/sponsors-all.js").then((m) => m.renderAllSponsorsPage),
  "/iletisim": () => import("./views/contact.js").then((m) => m.renderContactPage),
  "/gizlilik-guvenlik": () => import("./views/legal-page.js").then((m) => m.renderLegalPage),
  "/kurallar-sartlar": () => import("./views/legal-page.js").then((m) => m.renderLegalPage),
  "/cerez-politikasi": () => import("./views/legal-page.js").then((m) => m.renderLegalPage),
  "/market": () => import("./views/market.js").then((m) => m.renderMarketPage),
  "/bonuslar": () => import("./views/bonuses.js").then((m) => m.renderBonusesPage),
  "/promosyon-kodlari": () => import("./views/promo-codes.js").then((m) => m.renderPromoCodesPage),
  "/biletler": () => import("./views/tickets.js").then((m) => m.renderTicketsPage),
  "/etkinlikler": () => import("./views/events.js").then((m) => m.renderEventsPage),
  "/haberler": () => import("./views/news.js").then((m) => m.renderNewsPage),
  "/liderlik": () => import("./data/leaderboard.js").then((m) => m.renderLeaderboardPage),
  "/gamdom-cevrim-turnuvasi": () =>
    import("./data/gamdom-turnuva.js").then((m) => m.renderGamdomTurnuvaPage),
  "/sans-carki": () => import("./views/wheel.js").then((m) => m.renderWheelPage),
  "/profil": () => import("./views/profile.js").then((m) => m.renderProfile),
  "/sikayet-oneri": () => import("./views/complaints.js").then((m) => m.renderComplaintsPage),
  "/affiliate-gecis": () => import("./views/affiliate.js").then((m) => m.renderAffiliatePage),
  "/telegram-davet": () => import("./views/telegram-invite.js").then((m) => m.renderTelegramInvitePage),
  "/oyunlar": () => import("./views/games.js").then((m) => m.renderGamesPage),
  "/oyun-secici": () => import("./views/game-selector.js").then((m) => m.renderGameSelectorPage),
  "/oyunlar/blackjack": () => import("./views/blackjack.js").then((m) => m.renderBlackjackPage),
  "/oyunlar/slot": () => import("./views/slot.js").then((m) => m.renderSlotPage),
  "/oyunlar/rulet": () => import("./views/roulette.js").then((m) => m.renderRoulettePage),
  "/ozel-oranlar": () => import("./views/special-odds.js").then((m) => m.renderSpecialOddsPage),
};

globalThis.__sitePrefetchRoute = (path) => {
  const raw = String(path || "").trim() || "/";
  const key = raw.startsWith("/") ? raw : `/${raw}`;
  const load = routeLoaders[key];
  if (typeof load === "function") void load().catch(() => {});
};

const outlet = document.getElementById("page-outlet");
const sidebarRoot = document.getElementById("sidebar-root");
const headerRoot = document.getElementById("header-root");
const footerRoot = document.getElementById("footer-root");
const authModalsRoot = document.getElementById("auth-modals-root");
const promoModalRoot = document.getElementById("promo-modal-root");
const gameSelectorModalRoot = document.getElementById("game-selector-modal-root");
const newsModalRoot = document.getElementById("news-modal-root");
const notificationsRoot = document.getElementById("notifications-root");

const routes = Object.fromEntries(
  Object.entries(routeLoaders).map(([path, load]) => [
    path,
    async (el) => {
      const render = await load();
      return render(el);
    },
  ]),
);

const { start: startRouter, resolve: resolveRoute } = createRouter({
  routes,
  outlet,
  onAfterNavigate(_path, navId) {
    updateSidebarActive(sidebarRoot, navId);
  },
});

globalThis.__siteNavigateTo = (path) => {
  let p = normalizePathSegment(path);
  if (globalThis.__siteAuthGate === true && p !== "/profil") {
    p = "/profil";
  }
  const hash = p === "/" ? "#/" : `#${p}`;
  if (window.location.hash === hash) {
    void resolveRoute();
  } else {
    window.location.hash = hash;
  }
};

function warnIfFileProtocol() {
  if (location.protocol !== "file:") return;
  const bar = document.createElement("div");
  bar.setAttribute("role", "status");
  bar.className =
    "fixed inset-x-0 top-0 z-[200] border-b border-sky-500/40 bg-sky-950/95 px-4 py-3 text-center text-sm text-sky-100 shadow-lg backdrop-blur-sm";
  bar.innerHTML = `
    <strong class="font-semibold">Yerel API çalışmaz:</strong>
    Sayfa <code class="rounded bg-black/40 px-1.5 py-0.5 font-mono text-xs">file://</code> ile açılmış.
    Proje klasöründe <code class="rounded bg-black/40 px-1.5 py-0.5 font-mono text-xs">start-local.bat</code> çalıştırıp
    <a href="http://localhost:8080/" class="font-semibold text-sky-200 underline">http://localhost:8080/</a> adresini kullanın.
  `;
  document.body.prepend(bar);
}

const USER_CACHE_KEY = "mocker_user_cache_v1";

function loadCachedUser() {
  try {
    const raw = localStorage.getItem(USER_CACHE_KEY);
    if (!raw) return null;
    const parsed = JSON.parse(raw);
    if (!parsed || typeof parsed !== "object") return null;
    const username = String(parsed.username || "").trim();
    const coins = Number(parsed.coins);
    if (!username || !Number.isFinite(coins)) return null;
    return { username, coins };
  } catch {
    return null;
  }
}

function saveCachedUser(user) {
  try {
    if (!user) {
      localStorage.removeItem(USER_CACHE_KEY);
      return;
    }
    localStorage.setItem(USER_CACHE_KEY, JSON.stringify({ username: user.username, coins: Number(user.coins) || 0 }));
  } catch {

  }
}

async function boot() {
  warnIfFileProtocol();
  if (location.protocol === "file:") return;
  updateHeaderAuth(loadCachedUser());
  if (mightNeedTelegramMiniApp()) {
    try {
      await ensureTelegramWebAppScript();
      if (isInsideTelegramMiniApp()) await initTelegramMiniApp();
    } catch { /* noop */ }
  }
  const [sessionUser, siteResult, socialResult, gamdomResult] = await Promise.all([
    fetchSessionUser(),
    loadSite().then(
      () => ({ ok: true }),
      (err) => ({ ok: false, err }),
    ),
    loadSocial().then(
      () => ({ ok: true }),
      (err) => ({ ok: false, err }),
    ),
    loadGamdomTurnuva().then(
      () => ({ ok: true }),
      (err) => ({ ok: false, err }),
    ),
  ]);
  if (!siteResult.ok) console.error(siteResult.err);
  if (!socialResult.ok) console.error(socialResult.err);
  if (!gamdomResult.ok) console.error(gamdomResult.err);
  await loadPopup();
  saveCachedUser(sessionUser);
  setAuthGate(authGateFlagsFromUser(sessionUser));
  const activeUser = sessionUser ?? loadCachedUser();
  updateHeaderAuth(activeUser);
  onSiteNotificationsUserChange(sessionUser);
  if (sessionUser) void refreshSiteNotificationsBadge();
  bootSecondaryData();
  applySiteCustomCss();
  if (isSiteMaintenanceActive()) {
    mountSiteMaintenanceScreen();
    return;
  }
  if (globalThis.__siteAuthGate !== true) {
    showSitePopupIfNeeded();
  }
  if (promoModalRoot) renderPromoModal(promoModalRoot);
  if (gameSelectorModalRoot) renderGameSelectorModal(gameSelectorModalRoot);
  if (newsModalRoot) renderNewsModal(newsModalRoot);
  if (notificationsRoot) mountSiteNotificationsRoot(notificationsRoot);
  renderSidebar(sidebarRoot);
  renderHeader(headerRoot);
  bindSiteNotificationBells();
  bindSidebarDesktopToggle();
  initSearchPalette();
  bindLocaleSwitcher(headerRoot);
  bindLocaleSwitcher(sidebarRoot);
  bindThemeToggle(headerRoot);
  bindThemeToggle(sidebarRoot);
  window.addEventListener("mocker:theme", () => {
    updateThemeToggleUi(document);
  });
  window.addEventListener("mocker:locale", () => {
    const path = getCurrentAppPath();
    const meta = getRouteMeta(path);
    document.title = meta.title;
    applyClientSeo(path, meta);
    if (notificationsRoot) mountSiteNotificationsRoot(notificationsRoot);
    renderHeader(headerRoot);
    bindSiteNotificationBells();
    remountSearchPaletteForLocale();
    renderSidebar(sidebarRoot);
    bindSidebarDesktopToggle();
    bindLocaleSwitcher(headerRoot);
    bindLocaleSwitcher(sidebarRoot);
    bindThemeToggle(headerRoot);
    bindThemeToggle(sidebarRoot);
    updateSidebarActive(sidebarRoot, getRouteMeta(getCurrentAppPath()).navId);
    if (footerRoot) renderFooter(footerRoot);
    updateHeaderAuth(loadCachedUser());
    if (promoModalRoot) renderPromoModal(promoModalRoot);
    if (newsModalRoot) renderNewsModal(newsModalRoot);
    if (authModalsRoot) {
      renderAuthModals(authModalsRoot);
    }
    bindAuthHeaderButtons();
    void resolveRoute();
  });
  if (authModalsRoot) {
    renderAuthModals(authModalsRoot);
  }
  if (footerRoot) renderFooter(footerRoot);
  updateHeaderAuth(loadCachedUser());
  scheduleIdle(() => initSiteChat(), 6000);
  bindAuthHeaderButtons();
  let userRefreshReady = false;
  globalThis.__siteRefreshUser = async () => {
    const user = await fetchSessionUser();
    setAuthGate(authGateFlagsFromUser(user));
    updateHeaderAuth(user);
    onSiteNotificationsUserChange(user);
    if (user) void refreshSiteNotificationsBadge();
    void globalThis.__siteChatRefreshAuth?.();
    saveCachedUser(user);
    void refreshSidebarDailyBonus(sidebarRoot);
    void refreshHomeDailyBonus();
    if (userRefreshReady) {
      const path = getCurrentAppPath();
      if (path === "/market" && outlet) {
        const { renderMarketPage } = await import("./views/market.js");
        await renderMarketPage(outlet);
      }
      if (path === "/sans-carki" && outlet) {
        const { renderWheelPage } = await import("./views/wheel.js");
        await renderWheelPage(outlet);
      }
      if (path === "/sikayet-oneri" && outlet) {
        const { renderComplaintsPage } = await import("./views/complaints.js");
        await renderComplaintsPage(outlet);
      }
      if (path === "/affiliate-gecis" && outlet) {
        const { renderAffiliatePage } = await import("./views/affiliate.js");
        await renderAffiliatePage(outlet);
      }
      if (path === "/telegram-davet" && outlet) {
        const { renderTelegramInvitePage } = await import("./views/telegram-invite.js");
        await renderTelegramInvitePage(outlet);
      }
      if (path === "/ozel-oranlar" && outlet) {
        const { renderSpecialOddsPage } = await import("./views/special-odds.js");
        await renderSpecialOddsPage(outlet);
      }
      if (path === "/oyunlar" && outlet) {
        const { renderGamesPage } = await import("./views/games.js");
        await renderGamesPage(outlet);
      }
      if (path === "/oyunlar/blackjack" && outlet) {
        const { renderBlackjackPage } = await import("./views/blackjack.js");
        await renderBlackjackPage(outlet);
      }

    }
  };
  updateSidebarActive(sidebarRoot, getRouteMeta(getCurrentAppPath()).navId);
  startRouter();
  userRefreshReady = true;
  void globalThis.__siteRefreshUser();

  if (typeof requestIdleCallback === "function") {
    requestIdleCallback(
      () => {
        [
          "/market",
          "/bonuslar",
          "/promosyon-kodlari",
          "/biletler",
          "/etkinlikler",
          "/haberler",
          "/iletisim",
          "/liderlik",
          "/profil",
          "/oyunlar",
          "/oyunlar/blackjack",
          "/oyunlar/slot",
          "/oyunlar/rulet",
          "/oyun-secici",
        ].forEach(
          (p) => globalThis.__sitePrefetchRoute?.(p)
        );

        fetch(apiUrl("leaderboard.php"), { credentials: "omit", cache: "default" }).catch(() => {});

        fetch(dataJsonUrl("sponsors.json"), { credentials: "omit", cache: "default" }).catch(() => {});
        prefetchSlotGamesRoulette();
      },
      { timeout: 5000 }
    );
  } else {
    setTimeout(() => {
      ["/market", "/bonuslar", "/promosyon-kodlari", "/biletler", "/etkinlikler", "/iletisim", "/liderlik", "/profil"].forEach((p) =>
        globalThis.__sitePrefetchRoute?.(p)
      );
      fetch(apiUrl("leaderboard.php"), { credentials: "omit", cache: "default" }).catch(() => {});
      fetch(dataJsonUrl("sponsors.json"), { credentials: "omit", cache: "default" }).catch(() => {});
    }, 2500);
  }
}

function showBootError(err) {
  const msg = err && err.message ? String(err.message) : "Bilinmeyen hata";
  console.error("[boot]", err);
  const outlet = document.getElementById("page-outlet");
  const safeHtml = `<div class="rounded-2xl border border-red-500/30 bg-red-950/25 px-6 py-8 text-center text-sm text-red-100" role="alert">
    <p class="font-semibold text-red-50">Site başlatılamadı</p>
    <p class="mt-2 text-red-200/90">${msg.replace(/</g, "&lt;")}</p>
    <p class="mt-4 text-slate-400">Yerelde <code class="rounded bg-black/40 px-1">start-local.bat</code> ile veya <code class="rounded bg-black/40 px-1">php -S localhost:8080 router.php</code> sonra <a href="http://localhost:8080/" class="underline">http://localhost:8080/</a> kullanın.</p>
  </div>`;
  if (outlet) outlet.innerHTML = safeHtml;
  else {
    const bar = document.createElement("div");
    bar.setAttribute("role", "alert");
    bar.className =
      "fixed inset-x-0 top-0 z-[200] border-b border-red-500/40 bg-red-950/95 px-4 py-3 text-center text-sm text-red-100";
    bar.innerHTML = safeHtml;
    document.body.prepend(bar);
  }
}

boot().catch(showBootError);

setTimeout(function () {
  if (location.protocol === "file:") return;
  const outlet = document.getElementById("page-outlet");
  const sidebar = document.getElementById("sidebar-root");
  if (!outlet || outlet.innerHTML.trim() !== "") return;
  if (sidebar && sidebar.innerHTML.trim() !== "") return;
  showBootError(
    new Error(
      "JavaScript yüklenemedi veya sunucu yanıt vermiyor. index.html dosyasına çift tıklamayın; PHP sunucusu ile http://localhost:8080/ açın."
    )
  );
}, 8000);

document.addEventListener(
  "keydown",
  (e) => {
    if (
      globalThis.__siteAuthGate === true &&
      (e.metaKey || e.ctrlKey) &&
      (e.key === "k" || e.key === "K")
    ) {
      e.preventDefault();
      e.stopImmediatePropagation();
      return;
    }
    if (e.key !== "Escape") return;
    if (globalThis.__siteAuthModalOpen) {
      globalThis.__siteCloseAuthModals?.();
      return;
    }
    if (globalThis.__sitePromoModalOpen) {
      globalThis.__siteClosePromoModal?.();
      return;
    }
    if (globalThis.__siteNewsModalOpen) {
      globalThis.__siteCloseNewsModal?.();
      return;
    }
    globalThis.__siteCloseSidebar?.();
  },
  true
);

const backBtn = document.getElementById("back-to-top");
const toggleBack = debounce(() => {
  if (!backBtn) return;
  const show = window.scrollY >= 420;
  backBtn.classList.toggle("opacity-0", !show);
  backBtn.classList.toggle("pointer-events-none", !show);
  backBtn.classList.toggle("translate-y-3", !show);
}, 80);

window.addEventListener("scroll", toggleBack, { passive: true });
toggleBack();

backBtn?.addEventListener("click", () => {
  window.scrollTo({ top: 0, behavior: "smooth" });
});
