import { dataJsonUrl, getSiteLocale, t } from "../config/site.js";
import { getCurrentAppPath } from "../router.js";
import { escapeHtml } from "../utils/escape-html.js";

const SLUG_BY_PATH = {
  "/gizlilik-guvenlik": "privacy",
  "/kurallar-sartlar": "terms",
  "/cerez-politikasi": "cookies",
};

const LEGAL_PAGES = [
  { path: "/gizlilik-guvenlik", slug: "privacy", labelKey: "footerPrivacy", icon: "shield" },
  { path: "/kurallar-sartlar", slug: "terms", labelKey: "footerTerms", icon: "scale" },
  { path: "/cerez-politikasi", slug: "cookies", labelKey: "footerCookies", icon: "cookie" },
];

const ICONS = {
  shield: `<svg class="site-legal-hero__icon-svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.75" d="M9 12.75L11.25 15 15 9.75m-3-7.036A11.959 11.959 0 013.598 6 11.99 11.99 0 003 9.749c0 5.592 3.824 10.29 9 11.623 5.176-1.332 9-6.03 9-11.622 0-1.31-.21-2.571-.598-3.751h-.152c-3.196 0-6.1-1.248-8.25-3.285z"/></svg>`,
  scale: `<svg class="site-legal-hero__icon-svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.75" d="M12 3v17.25m0 0c-1.472 0-2.882.635-4.2 1.65M12 20.25c1.472 0 2.882.635 4.2 1.65M6.75 7.5h10.5M6.75 12h10.5m-10.5 4.5h10.5"/></svg>`,
  cookie: `<svg class="site-legal-hero__icon-svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.75" d="M12 8.25v-1.5m0 1.5c-1.355 0-2.697.056-4.024.166C6.845 8.51 6 9.473 6 10.608v2.513m6-4.87c1.355 0 2.697.055 4.024.165C17.155 8.51 18 9.473 18 10.608v2.513M12 8.25V6.375c0-1.036-.84-1.875-1.875-1.875h-.75A1.125 1.125 0 0010.125 5.25v1.5m0 0h3.75m-3.75 0h-3.75m9.75 9.75v1.5c0 1.036-.84 1.875-1.875 1.875h-.75a1.125 1.125 0 01-1.125-1.125v-1.5m0 0h3.75m-3.75 0h-3.75"/></svg>`,
  nav: `<svg class="site-legal-nav__icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"/></svg>`,
  contact: `<svg class="site-legal-cta__icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" 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>`,
};

let legalCache = null;

async function loadLegalPages() {
  if (legalCache) return legalCache;
  try {
    const r = await fetch(dataJsonUrl("legal-pages.json"), { cache: "no-store" });
    if (!r.ok) return null;
    const j = await r.json();
    legalCache = j && typeof j === "object" ? j : null;
    return legalCache;
  } catch {
    return null;
  }
}

function resolvePage(slug, locale) {
  const bucket = legalCache?.[slug];
  if (!bucket?.locales) return null;
  const loc = bucket.locales[locale] || bucket.locales.tr || bucket.locales.en;
  if (!loc) return null;

  let sections = [];
  if (Array.isArray(loc.sections) && loc.sections.length) {
    sections = loc.sections
      .map((s, i) => ({
        title: String(s?.title || "").trim() || t("legalSectionFallback").replace("{n}", String(i + 1)),
        body: String(s?.body || "").trim(),
      }))
      .filter((s) => s.body !== "");
  } else if (Array.isArray(loc.paragraphs)) {
    sections = loc.paragraphs
      .map((p, i) => ({
        title: t("legalSectionFallback").replace("{n}", String(i + 1)),
        body: String(p).trim(),
      }))
      .filter((s) => s.body !== "");
  }

  return {
    title: String(loc.title || "").trim() || slug,
    intro: String(loc.intro || "").trim(),
    sections,
  };
}

function legalNavHtml(activePath) {
  const items = LEGAL_PAGES.map((p) => {
    const active = p.path === activePath;
    const cls = active ? "site-legal-nav__link site-legal-nav__link--active" : "site-legal-nav__link";
    const hash = p.path === "/" ? "#/" : `#${p.path}`;
    return `<a href="${hash}" class="${cls}" ${active ? 'aria-current="page"' : ""}>
      <span class="site-legal-nav__link-dot" aria-hidden="true"></span>
      <span>${escapeHtml(t(p.labelKey))}</span>
    </a>`;
  }).join("");

  return `
    <nav class="site-legal-nav" aria-label="${escapeHtml(t("footerLegalNav"))}">
      <p class="site-legal-nav__label">${ICONS.nav}<span>${escapeHtml(t("legalNavTitle"))}</span></p>
      <div class="site-legal-nav__links">${items}</div>
    </nav>`;
}

function sectionsHtml(sections) {
  return sections
    .map(
      (s, i) => `
      <section class="site-legal-section" id="legal-section-${i + 1}">
        <div class="site-legal-section__index" aria-hidden="true">${String(i + 1).padStart(2, "0")}</div>
        <div class="site-legal-section__content">
          <h2 class="site-legal-section__title">${escapeHtml(s.title)}</h2>
          <p class="site-legal-section__body">${escapeHtml(s.body)}</p>
        </div>
      </section>`,
    )
    .join("");
}

function pageMeta(path) {
  return LEGAL_PAGES.find((p) => p.path === path) || LEGAL_PAGES[0];
}

export async function renderLegalPage(outlet) {
  const path = getCurrentAppPath();
  const slug = SLUG_BY_PATH[path];
  if (!slug) {
    outlet.innerHTML = `<div class="site-legal-empty"><p>${escapeHtml(t("legalNotFound"))}</p></div>`;
    return;
  }

  await loadLegalPages();
  const locale = getSiteLocale();
  const page = resolvePage(slug, locale);
  if (!page || !page.sections.length) {
    outlet.innerHTML = `<div class="site-legal-empty"><p>${escapeHtml(t("legalNotFound"))}</p></div>`;
    return;
  }

  const meta = pageMeta(path);
  const icon = ICONS[meta.icon] || ICONS.shield;
  const slugClass = `site-legal-page--${slug}`;

  outlet.innerHTML = `
    <section class="site-legal-page relative w-full min-w-0 px-1 pb-6 ${slugClass}">
      <header class="site-legal-hero">
        <div class="site-legal-hero__glow" aria-hidden="true"></div>
        <div class="site-legal-hero__inner">
          <div class="site-legal-hero__icon-wrap" aria-hidden="true">${icon}</div>
          <div class="site-legal-hero__text">
            <span class="site-legal-hero__eyebrow">${escapeHtml(t("footerLegal"))}</span>
            <h1 class="site-legal-hero__title">${escapeHtml(page.title)}</h1>
            ${page.intro ? `<p class="site-legal-hero__intro">${escapeHtml(page.intro)}</p>` : ""}
          </div>
        </div>
      </header>

      <div class="site-legal-layout">
        <aside class="site-legal-layout__aside">
          ${legalNavHtml(path)}
          <div class="site-legal-toc site-legal-toc--desktop" aria-label="${escapeHtml(t("legalTocLabel"))}">
            <p class="site-legal-toc__label">${escapeHtml(t("legalTocLabel"))}</p>
            <ol class="site-legal-toc__list">
              ${page.sections
                .map(
                  (s, i) =>
                    `<li><a href="#legal-section-${i + 1}" class="site-legal-toc__link">${escapeHtml(s.title)}</a></li>`,
                )
                .join("")}
            </ol>
          </div>
        </aside>

        <div class="site-legal-layout__main">
          <div class="site-legal-sections site-scrollbar">
            ${sectionsHtml(page.sections)}
          </div>

          <aside class="site-legal-cta">
            <div class="site-legal-cta__inner">
              <span class="site-legal-cta__icon-wrap" aria-hidden="true">${ICONS.contact}</span>
              <div class="site-legal-cta__text">
                <p class="site-legal-cta__title">${escapeHtml(t("legalContactTitle"))}</p>
                <p class="site-legal-cta__desc">${escapeHtml(t("legalContactDesc"))}</p>
              </div>
              <a href="#/iletisim" class="k-btn k-btn--primary site-legal-cta__btn">${escapeHtml(t("navContact"))}</a>
            </div>
          </aside>
        </div>
      </div>
    </section>
  `;
}
