import { destroyHomeRecentWinners } from "./components/home-recent-winners.js";
import { destroyHomeEvents } from "./components/home-events.js";
import { destroyHomeTickets } from "./components/home-tickets.js";
import { destroyHomeYoutubeFeed } from "./components/home-youtube-feed.js";
import { destroyMarketPage } from "./views/market.js";
import { applyClientSeo } from "./utils/seo.js";
import { getRouteMeta } from "./constants/route-seo.js";

export { getRouteMeta };

export function normalizeHashToPath(hash) {
  let p = (hash || "").replace(/^#/, "").trim();
  if (!p || p === "/") return "/";
  if (!p.startsWith("/")) p = `/${p}`;
  const trimmed = p.replace(/\/+$/, "");
  return trimmed || "/";
}

export function normalizePathSegment(raw) {
  let p = (raw || "").trim();
  if (p.startsWith("#")) p = p.replace(/^#/, "").trim();
  if (!p || p === "/") return "/";
  if (!p.startsWith("/")) p = `/${p}`;
  const trimmed = p.replace(/\/+$/, "");
  return trimmed || "/";
}

export function getCurrentAppPath() {
  return normalizeHashToPath(window.location.hash || "#/");
}

const LEGACY_SPONSOR_PATHS = new Set([
  "/elit-siteler",
  "/tum-sponsorlar",
  "/vip-siteler",
  "/onerilen-siteler",
  "/guvenilir-siteler",
  "/vip-sponsorlar",
  "/sponsorlar",
  "/sponsorlar-grup",
]);

function redirectLegacySponsorPath(path) {
  return LEGACY_SPONSOR_PATHS.has(path) ? "/ana-sponsorlar" : path;
}

function migratePathnameToHash(routes) {
  let path = window.location.pathname.replace(/\/index\.html$/i, "") || "/";
  path = normalizePathSegment(path);
  path = redirectLegacySponsorPath(path);
  if (!path || path === "/") return;
  if (window.location.hash && window.location.hash.startsWith("#/")) return;
  if (!routes[path]) return;
  window.location.replace(`${window.location.origin}/#${path}`);
}

function prefersReducedMotion() {
  return window.matchMedia("(prefers-reduced-motion: reduce)").matches;
}

const ROUTE_LOADING_HTML = `<div class="route-loading flex min-h-[42vh] flex-col items-center justify-center gap-4 px-4 py-12" role="status" aria-live="polite" aria-busy="true">
  <div class="route-loading__spinner h-9 w-9 rounded-full border-2 border-white/[0.12] border-t-accent" aria-hidden="true"></div>
  <p class="text-sm text-slate-500">Yükleniyor…</p>
</div>`;

export function createRouter({ routes, outlet, onAfterNavigate }) {
  let navGeneration = 0;

  async function resolve() {
    if (!outlet) {
      console.error("[router] page-outlet bulunamadı.");
      return;
    }
    let path = normalizeHashToPath(window.location.hash);
    const legacySponsor = redirectLegacySponsorPath(path);
    if (legacySponsor !== path) {
      window.location.hash = `#${legacySponsor}`;
      return;
    }
    if (globalThis.__siteAuthGate === true && path !== "/profil") {
      window.location.hash = "#/profil";
      return;
    }
    if (!routes[path]) {
      window.location.hash = "#/";
      return;
    }
    const seq = ++navGeneration;
    destroyMarketPage();
    destroyHomeRecentWinners();
    destroyHomeEvents();
    destroyHomeTickets();
    destroyHomeYoutubeFeed();
    outlet.innerHTML = ROUTE_LOADING_HTML;
    outlet.classList.remove("page-outlet--enter");

    try {
      await routes[path](outlet);
    } catch (err) {
      console.error("[router] Rota yüklenemedi:", path, err);
      if (seq !== navGeneration) return;
      outlet.innerHTML =
        '<div class="rounded-2xl border border-red-500/25 bg-red-950/20 px-6 py-8 text-center text-sm text-red-200">Sayfa yüklenirken bir hata oluştu. Sayfayı yenileyip tekrar dene.</div>';
      return;
    }
    if (seq !== navGeneration) return;

    const meta = getRouteMeta(path);
    document.title = meta.title;
    applyClientSeo(path, meta);
    onAfterNavigate?.(path, meta.navId);

    outlet.classList.remove("page-outlet--enter");
    if (!prefersReducedMotion()) {
      void outlet.offsetWidth;
      outlet.classList.add("page-outlet--enter");
    }
    window.scrollTo({ top: 0, behavior: "auto" });
  }

  window.addEventListener("hashchange", () => void resolve());

  function start() {
    migratePathnameToHash(routes);
    if (!window.location.hash || window.location.hash === "#") {
      window.location.hash = "#/";
    }
    void resolve();
  }

  return { start, resolve };
}
