"use client";
import { jsx, jsxs } from 'react/jsx-runtime';
import { useMemo, useState, useRef, useEffect } from 'react';
import { cn, slugify } from '../../../utils.mjs';
import { usePluginOverrides } from '@btst/stack/context';
import { BLOG_LOCALIZATION } from '../../localization/index.mjs';
import { Select, SelectTrigger, SelectValue, SelectContent, SelectItem } from '../../../../../../../ui/src/components/select.mjs';
import { TextAlignStart } from 'lucide-react';

function OnThisPage({ markdown, className }) {
  const { localization } = usePluginOverrides("blog", {
    localization: BLOG_LOCALIZATION
  });
  const headings = useMemo(() => extractHeadings(markdown), [markdown]);
  const activeId = useActiveHeading(headings);
  if (headings.length === 0) {
    return /* @__PURE__ */ jsx(
      "div",
      {
        className: cn(
          "sticky top-20 z-30 ml-auto hidden xl:flex w-44",
          className
        )
      }
    );
  }
  const handleClick = (id) => {
    const element = document.getElementById(id);
    if (element) {
      element.scrollIntoView({ behavior: "smooth", block: "start" });
    }
  };
  return /* @__PURE__ */ jsx(
    "nav",
    {
      className: cn(
        "sticky top-20 z-30 ml-auto hidden xl:flex w-44 flex-col gap-2 overflow-hidden pb-8",
        className
      ),
      "aria-label": "Table of contents",
      children: /* @__PURE__ */ jsx("div", { className: "overflow-y-auto px-2", children: /* @__PURE__ */ jsxs("div", { className: "flex flex-col gap-1 p-2 pt-0 text-sm", children: [
        /* @__PURE__ */ jsxs("p", { className: "flex items-center gap-2 font-semibold text-muted-foreground sticky top-0 h-6 text-xs", children: [
          /* @__PURE__ */ jsx(TextAlignStart, { className: "w-3 h-3" }),
          " ",
          localization.BLOG_POST_ON_THIS_PAGE
        ] }),
        headings.map(({ id, text, level }) => {
          const paddingLeft = level === 1 ? "0" : level === 2 ? "0.5rem" : level === 3 ? "1rem" : level === 4 ? "1.5rem" : level === 5 ? "2rem" : level === 6 ? "2.5rem" : "0";
          return /* @__PURE__ */ jsx(
            "a",
            {
              href: `#${id}`,
              onClick: (e) => {
                e.preventDefault();
                handleClick(id);
              },
              style: { paddingLeft },
              className: cn(
                "text-muted-foreground hover:text-foreground text-[0.8rem] no-underline transition-colors",
                activeId === id && "text-foreground"
              ),
              "data-active": activeId === id,
              "data-depth": level,
              children: text
            },
            id
          );
        })
      ] }) })
    }
  );
}
function OnThisPageSelect({ markdown, className }) {
  const { localization } = usePluginOverrides("blog", {
    localization: BLOG_LOCALIZATION
  });
  const headings = useMemo(() => extractHeadings(markdown), [markdown]);
  const initialValue = useMemo(() => headings[0]?.id ?? "", [headings]);
  const activeId = useActiveHeading(headings);
  const value = activeId || initialValue;
  if (headings.length === 0) {
    return null;
  }
  const handleValueChange = (id) => {
    const element = document.getElementById(id);
    if (element) {
      element.scrollIntoView({ behavior: "smooth", block: "start" });
    }
  };
  return /* @__PURE__ */ jsx(
    "div",
    {
      className: cn(
        "sticky z-30 w-full self-stretch xl:hidden bg-background/95 backdrop-blur supports-backdrop-filter:bg-background/60",
        className
      ),
      style: {
        top: "var(--navbar-height, 16px)"
      },
      children: /* @__PURE__ */ jsxs(Select, { value, onValueChange: handleValueChange, children: [
        /* @__PURE__ */ jsx(SelectTrigger, { className: "w-full", children: /* @__PURE__ */ jsx(SelectValue, { placeholder: localization.BLOG_POST_ON_THIS_PAGE }) }),
        /* @__PURE__ */ jsx(SelectContent, { children: headings.map(({ id, text, level }) => {
          const indent = level > 1 ? `${(level - 1) * 0.5}rem` : "0";
          return /* @__PURE__ */ jsx(SelectItem, { value: id, children: /* @__PURE__ */ jsx("span", { style: { paddingLeft: indent }, children: text }) }, id);
        }) })
      ] })
    }
  );
}
function extractHeadings(markdown) {
  const headings = [];
  const lines = markdown.split("\n");
  for (const line of lines) {
    const match = line.match(/^(#{1,6})\s+(.+)$/);
    if (match) {
      const level = match[1]?.length ?? 0;
      const text = match[2]?.trim() ?? "";
      const cleanText = text.replace(/\s*#+\s*$/, "").trim();
      const id = slugify(cleanText);
      if (id && cleanText) {
        headings.push({ id, text: cleanText, level });
      }
    }
  }
  return headings;
}
function useActiveHeading(headings, onActiveChange) {
  const [activeId, setActiveId] = useState("");
  const onActiveChangeRef = useRef(onActiveChange);
  useEffect(() => {
    onActiveChangeRef.current = onActiveChange;
  }, [onActiveChange]);
  useEffect(() => {
    if (headings.length === 0) return;
    const observer = new IntersectionObserver(
      (entries) => {
        for (const entry of entries) {
          if (entry.isIntersecting) {
            setActiveId(entry.target.id);
            onActiveChangeRef.current?.(entry.target.id);
            break;
          }
        }
      },
      {
        rootMargin: "-80px 0px -80% 0px",
        threshold: 0
      }
    );
    headings.forEach(({ id }) => {
      const element = document.getElementById(id);
      if (element) {
        observer.observe(element);
      }
    });
    return () => {
      observer.disconnect();
    };
  }, [headings]);
  return activeId;
}

export { OnThisPage, OnThisPageSelect };
