// Activates planned L3 hub cards when Iris has built the matching article.
// The planned card title is the contract; it slugifies the same way the taxonomy seeder does.

const HTB_SUPABASE_URL = "https://iuhdtrlnexzkvdvoatpk.supabase.co";
const HTB_SUPABASE_ANON_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6Iml1aGR0cmxuZXh6a3Zkdm9hdHBrIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzQzMDAzMTgsImV4cCI6MjA4OTg3NjMxOH0.fnlTZNdKwUZGukKka41GmQIZpC8eCi-RN7QvAFnLmEk";

function htbNormalizePath(slug) {
  if (!slug) return "/";
  const withLead = slug.startsWith("/") ? slug : `/${slug}`;
  return withLead.replace(/\/+$/g, "");
}

function htbHref(slug) {
  return `${htbNormalizePath(slug)}/`;
}

function htbCurrentLang() {
  const first = window.location.pathname.split("/").filter(Boolean)[0];
  return first || "en";
}

function htbSlugifyTitle(title) {
  return String(title || "")
    .toLowerCase()
    .normalize("NFKD")
    .replace(/[\u0300-\u036f]/g, "")
    .replace(/['']/g, "")
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-+|-+$/g, "")
    .slice(0, 60)
    .replace(/-+$/g, "");
}

function htbArticleSlug(basePath, titleOrSlug) {
  if (!titleOrSlug) return "";
  if (String(titleOrSlug).startsWith("/")) return htbNormalizePath(titleOrSlug);
  const base = `${htbNormalizePath(basePath || window.location.pathname)}/`;
  return htbNormalizePath(`${base}${htbSlugifyTitle(titleOrSlug)}`);
}

async function htbFetchBuiltArticle(slug, language) {
  const path = htbNormalizePath(slug);
  const params = new URLSearchParams({
    select: "slug,title,language",
    slug: `eq.${path}`,
    language: `eq.${language}`,
    property: "eq.beauty",
    limit: "1",
  });
  const res = await fetch(`${HTB_SUPABASE_URL}/rest/v1/pages?${params}`, {
    headers: {
      apikey: HTB_SUPABASE_ANON_KEY,
      Authorization: `Bearer ${HTB_SUPABASE_ANON_KEY}`,
    },
  });
  if (!res.ok) return null;
  const rows = await res.json();
  return rows[0] || null;
}

function useHubArticleLinks(items, options = {}) {
  const lang = options.language || htbCurrentLang();
  const basePath = options.basePath || window.location.pathname;
  const planned = React.useMemo(() => (items || []).map((item) => {
    const title = item.slug || item.t || item.title || item.h || item.name;
    const slug = item.href && item.href !== "#" ? item.href : htbArticleSlug(basePath, title);
    return { item, slug: htbNormalizePath(slug) };
  }), [JSON.stringify(items || []), basePath]);

  const [builtBySlug, setBuiltBySlug] = React.useState({});

  React.useEffect(() => {
    let cancelled = false;
    const uniqueSlugs = Array.from(new Set(planned.map((p) => p.slug).filter(Boolean)));
    if (!uniqueSlugs.length) {
      setBuiltBySlug({});
      return;
    }

    Promise.all(uniqueSlugs.map((slug) => htbFetchBuiltArticle(slug, lang)))
      .then((rows) => {
        if (cancelled) return;
        const next = {};
        rows.filter(Boolean).forEach((row) => {
          next[htbNormalizePath(row.slug)] = row;
        });
        setBuiltBySlug(next);
      })
      .catch(() => {
        if (!cancelled) setBuiltBySlug({});
      });

    return () => { cancelled = true; };
  }, [planned.map((p) => p.slug).join("|"), lang]);

  return planned.map(({ item, slug }) => {
    const row = builtBySlug[slug];
    return {
      ...item,
      plannedSlug: htbHref(slug),
      href: row ? htbHref(row.slug) : "#",
      isBuilt: Boolean(row),
      builtTitle: row?.title || item.title || item.t,
    };
  });
}

const htbBuiltArticleCache = new Map();

function htbCachedBuiltArticle(slug, language) {
  const key = `${language}:${htbNormalizePath(slug)}`;
  if (!htbBuiltArticleCache.has(key)) {
    htbBuiltArticleCache.set(key, htbFetchBuiltArticle(slug, language));
  }
  return htbBuiltArticleCache.get(key);
}

function htbTitleFromAnchor(anchor) {
  const titleNode = anchor.querySelector("h4, h3, .bp-body h4");
  return (titleNode?.textContent || "").trim();
}

async function htbHydratePlannedAnchor(anchor) {
  if (!anchor || anchor.dataset.htbHydrated === "true") return;
  if (anchor.getAttribute("href") !== "#") return;

  const title = htbTitleFromAnchor(anchor);
  if (!title) return;

  anchor.dataset.htbHydrated = "true";
  const slug = htbArticleSlug(window.location.pathname, title);
  anchor.dataset.plannedSlug = htbHref(slug);

  const row = await htbCachedBuiltArticle(slug, htbCurrentLang());
  if (!row) {
    anchor.classList.add("is-queued");
    return;
  }

  anchor.href = htbHref(row.slug);
  anchor.classList.remove("is-queued");
  anchor.classList.add("is-built");
}

function htbHydrateVisibleHubLinks() {
  document
    .querySelectorAll('a.lib-card[href="#"], a.tr-item[href="#"], a.bp-step[href="#"]')
    .forEach((anchor) => {
      htbHydratePlannedAnchor(anchor).catch(() => {});
    });
}

if (!window.__htbHubArticleLinkHydrator) {
  window.__htbHubArticleLinkHydrator = true;
  document.addEventListener("DOMContentLoaded", () => {
    htbHydrateVisibleHubLinks();
    const observer = new MutationObserver(htbHydrateVisibleHubLinks);
    observer.observe(document.body, { childList: true, subtree: true });
  });
}
