---
import { render } from "astro:content";
import { PageTitle } from "./PageTitle";
import { Navigation } from "./Navigation";
import { getNavigationLinks } from "../../utils/navigation";
import Pre from "../../components/markdown/Pre.astro";
import Blockquote from "../../components/markdown/Blockquote.astro";
import Code from "../../components/markdown/Code.astro";
import Table from "../../components/markdown/Table.astro";
import Thead from "../../components/markdown/Thead.astro";
import Tbody from "../../components/markdown/Tbody.astro";
import Tr from "../../components/markdown/Tr.astro";
import Th from "../../components/markdown/Th.astro";
import Td from "../../components/markdown/Td.astro";
import Img from "../../components/markdown/Img.astro";
import { Accordion } from "./Accordion";
import { AccordionGroup } from "./AccordionGroup";
import Callout from "./Callout.astro";
import Card from "./Card.astro";
import { Properties } from "./Properties";
import { ui } from "../../i18n/ui";

const { doc } = Astro.props;
const { Content } = await render(doc);

// Extract breadcrumb from the path
// doc.id format: "version/locale/...path" (e.g. "deco-studio/en/studio/overview")
const pathParts = doc.id.split("/").slice(2);
const locale = doc.id.split("/")[1] as keyof typeof ui;
const translations = ui[locale] || ui.en;

// Get translated breadcrumb if available
const breadcrumb =
  pathParts.length > 1
    ? translations[
        `sidebar.section.${pathParts[0]}` as keyof typeof translations
      ] || pathParts[0].charAt(0).toUpperCase() + pathParts[0].slice(1)
    : undefined;

// Generate markdown path for viewing raw file
const markdownPath = `/src/content/${doc.id}.mdx`;

// Get navigation links
const navigationLinks = await getNavigationLinks(doc.id, locale);

// Components mapping for custom markdown rendering
const components = {
  pre: Pre,
  blockquote: Blockquote,
  code: Code,
  table: Table,
  thead: Thead,
  tbody: Tbody,
  tr: Tr,
  th: Th,
  td: Td,
  img: Img,
  Accordion,
  AccordionGroup,
  Callout,
  Card,
  Properties,
};
---

<div
  class="flex flex-col box-border w-full relative grow mx-auto max-w-xl 2xl:max-w-3xl"
>
  <PageTitle
    client:load
    breadcrumb={breadcrumb}
    title={doc.data.title}
    description={doc.data.description}
    markdownPath={markdownPath}
  />

  <div class="prose max-w-none" id="rendered-content">
    <Content components={components} />
  </div>

  <div class="mt-8">
    <Navigation
      client:load
      previous={navigationLinks.previous}
      next={navigationLinks.next}
    />
  </div>
</div>

<script>
  function updateProseTheme() {
    const renderedContent = document.getElementById("rendered-content");
    if (!renderedContent) return;

    const isDark =
      document.documentElement.getAttribute("data-theme") === "dark";
    if (isDark) {
      renderedContent.classList.add("prose-invert");
    } else {
      renderedContent.classList.remove("prose-invert");
    }
  }

  function addHeadingLinks() {
    const content = document.getElementById("rendered-content");
    if (!content) return;

    const headings = content.querySelectorAll("h2, h3, h4, h5, h6");

    headings.forEach((heading) => {
      // Make heading relative positioned and add group class
      const headingElement = heading as HTMLElement;
      headingElement.style.position = "relative";
      headingElement.style.cursor = "pointer";
      headingElement.classList.add("group");

      // Create the link icon using the same SVG as the Icon component for "Link"
      const linkIcon = document.createElement("div");
      linkIcon.className =
        "absolute left-[-30px] top-1/2 -translate-y-1/2 opacity-0 group-hover:opacity-100 transition-opacity";
      linkIcon.innerHTML = `<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="#7F9300" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"></path><path d="M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.72-1.71"></path></svg>`;

      // Add click handler to the whole heading
      heading.addEventListener("click", async () => {
        const id =
          heading.id ||
          heading.textContent?.toLowerCase().replace(/[^a-z0-9]+/g, "-") ||
          "";
        if (!heading.id) {
          heading.id = id;
        }

        // Create the full URL with the hash
        const fullUrl = `${window.location.origin}${window.location.pathname}${window.location.search}#${id}`;

        try {
          // Copy the URL to clipboard
          await navigator.clipboard.writeText(fullUrl);
        } catch (err) {
          console.warn("Failed to copy URL to clipboard:", err);
        }

        window.location.hash = id;
      });

      headingElement.appendChild(linkIcon);
    });
  }

  // Run when the page loads
  document.addEventListener("DOMContentLoaded", () => {
    addHeadingLinks();
    updateProseTheme();
  });

  // Also run after a short delay to ensure content is rendered
  setTimeout(() => {
    addHeadingLinks();
    updateProseTheme();
  }, 100);

  // Watch for theme changes
  const observer = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
      if (
        mutation.type === "attributes" &&
        mutation.attributeName === "data-theme"
      ) {
        updateProseTheme();
      }
    });
  });

  // Start observing the document element for attribute changes
  observer.observe(document.documentElement, {
    attributes: true,
    attributeFilter: ["data-theme"],
  });
</script>
