---
import { render } from 'astro:content';

import VerticalSideBarLayout from '@layouts/VerticalSideBarLayout.astro';
import Admonition from '@components/MDX/Admonition';
import components from '@components/MDX/components';
import CopyAsMarkdown from '@components/CopyAsMarkdown';
import Badge from '@components/Badge.astro';
import { buildUrl } from '@utils/url-builder';
import { AlignLeftIcon, HistoryIcon } from 'lucide-react';
import { isEventCatalogChatEnabled, isResourceDocsEnabled } from '@utils/feature';
import { getIcon } from '@utils/badges';
import { collectionToResourceMap } from '@utils/collections/util';

import { Page } from './_index.data';

export const prerender = Page.prerender;
export const getStaticPaths = Page.getStaticPaths;

if (!isResourceDocsEnabled()) {
  return Astro.redirect(buildUrl('/docs/custom/feature'));
}

const props = await Page.getData(Astro);
const { Content, headings } = await render(props);

const title = props.data.title || props.data.id;
const pageTitle = `${title} | ${props.data.resourceId}`;
const versions = props.data.versions || [props.data.version];
const badges = (props.data.badges || []).map((badge: any) => ({
  ...badge,
  iconComponent: badge.icon ? getIcon(badge.icon) : null,
}));

const docsBasePath = `/docs/${props.data.resourceCollection}/${props.data.resourceId}/${props.data.resourceVersion}/${encodeURIComponent(props.data.type)}/${encodeURIComponent(props.data.id)}`;
const singularResourceName =
  collectionToResourceMap[props.data.resourceCollection as keyof typeof collectionToResourceMap] ??
  props.data.resourceCollection.slice(0, props.data.resourceCollection.length - 1);
const chatEnabled = isEventCatalogChatEnabled();
const chatQuery = `Tell me about the ${props.data.type} doc "${title}" for ${props.data.resourceId} (version ${props.data.version})`;

const pagefindAttributes =
  props.data.version === props.data.latestVersion
    ? {
        'data-pagefind-body': '',
        'data-pagefind-meta': `title:${pageTitle}`,
      }
    : {};
---

<VerticalSideBarLayout title={pageTitle} description={props.data.summary}>
  <main class="flex docs-layout min-h-full bg-[rgb(var(--ec-page-bg))]" {...pagefindAttributes}>
    <div class="flex docs-layout w-full">
      <div class="w-full lg:mr-2 pr-24 py-8 bg-[rgb(var(--ec-page-bg))]">
        <div class="border-b border-[rgb(var(--ec-page-border))] md:pb-2">
          <div>
            <div class="flex items-center">
              <div class="flex items-center gap-2">
                <h2 id="doc-page-header" class="text-2xl md:text-4xl font-bold text-[rgb(var(--ec-page-text))]">{title}</h2>
              </div>
            </div>
          </div>
          {
            props.data.summary && (
              <p class="text-base pt-2 text-[rgb(var(--ec-page-text-muted))] font-light">{props.data.summary}</p>
            )
          }
          {
            badges.length > 0 && (
              <div class="flex flex-wrap gap-1.5 py-3">
                {badges.map((badge: any) => <Badge badge={badge} />)}
              </div>
            )
          }
          <div class="pt-4">
            <CopyAsMarkdown
              client:only="react"
              variant="toolbar"
              schemas={[]}
              chatQuery={chatQuery}
              chatEnabled={chatEnabled}
              editUrl=""
              markdownDownloadEnabled={true}
              rssFeedEnabled={false}
              preferChatAsDefault={false}
            />
          </div>
        </div>
        <div data-pagefind-ignore>
          {
            props.data.version !== props.data.latestVersion && (
              <Admonition type="warning" title="New version found">
                <p>
                  You are looking at a previous version of the {singularResourceName} doc <strong>{title}</strong>.{' '}
                  <a class="underline block pt-2" href={buildUrl(`${docsBasePath}/${props.data.latestVersion}`)}>
                    The latest version of this doc is <span>v{props.data.latestVersion}</span> &rarr;
                  </a>
                </p>
              </Admonition>
            )
          }
        </div>
        <div class="prose py-4 max-w-none">
          <Content components={components(props)} />
        </div>
      </div>
      <aside
        class="hidden xl:block sticky top-[4rem] self-start w-[280px] max-h-[calc(100vh-4rem)] overflow-y-auto py-2 flex-shrink-0 pr-10 bg-[rgb(var(--ec-page-bg))]"
      >
        <div class="mt-8 space-y-8">
          <h3 class="text-xs text-[rgb(var(--ec-page-text))] font-semibold capitalize flex items-center gap-2 mb-4">
            <AlignLeftIcon className="w-4 h-4" />
            On this page
          </h3>
          <nav class="text-xs border-l border-[rgb(var(--ec-page-border))]">
            {
              headings.map((heading) => {
                const level = heading.depth > 2 ? heading.depth : 1;
                if (heading.depth > 3) {
                  return null;
                }
                return (
                  <a
                    href={`#${heading.slug}`}
                    class={`block py-1.5 pr-2.5 leading-5 text-[rgb(var(--ec-page-text-muted))] hover:border-[rgb(var(--ec-page-border))] hover:text-[rgb(var(--ec-page-text))] border-l-2 border-transparent -ml-px transition-all duration-200`}
                    style={`padding-left: ${level * 0.75}rem`}
                  >
                    {heading.text}
                  </a>
                );
              })
            }
          </nav>
          <div class="space-y-2 pb-4">
            <span class="text-xs text-[rgb(var(--ec-page-text))] font-semibold capitalize">Versions ({versions.length})</span>
            <ul role="list" class="space-y-2">
              {
                versions.map((version: string) => (
                  <li class="version-item rounded-md px-1 group w-full">
                    <a class="flex items-center space-x-2" href={buildUrl(`${docsBasePath}/${encodeURIComponent(version)}`)}>
                      <HistoryIcon
                        className="h-4 w-4 text-[rgb(var(--ec-page-text-muted))] group-hover:text-[rgb(var(--ec-accent-text))]"
                        strokeWidth={1}
                      />
                      <span
                        class={`font-light text-xs text-[rgb(var(--ec-page-text))] group-hover:text-[rgb(var(--ec-accent-text))] ${
                          version === props.data.version ? 'underline' : ''
                        }`}
                      >
                        {version === props.data.latestVersion ? `v${version} (latest)` : `v${version}`}
                      </span>
                    </a>
                  </li>
                ))
              }
            </ul>
            <div class="border-b border-[rgb(var(--ec-page-border))] pt-2"></div>
          </div>
        </div>
      </aside>
    </div>
  </main>
</VerticalSideBarLayout>

<style is:global>
  .docs-layout .prose {
    max-width: none;
    overflow: auto;
  }

  .toc-active-text {
    color: rgb(var(--ec-accent));
  }

  .toc-active-border {
    border-color: rgb(var(--ec-accent));
  }

  .version-item:hover {
    background: linear-gradient(to left, rgb(var(--ec-accent-gradient-from)), rgb(var(--ec-accent-gradient-to)));
  }
</style>

<script>
  // @ts-nocheck
  function setupObserver() {
    try {
      const observerOptions = {
        rootMargin: '0px 0px -40% 0px',
        threshold: 0.1,
      };

      let observerPaused = false;

      function highlightTocItem(id) {
        document.querySelectorAll('.active-toc-item').forEach((link) => {
          link.classList.remove('active-toc-item', 'toc-active-text', 'font-medium', 'toc-active-border');
          link.classList.add('border-transparent');
        });

        const tocLink = document.querySelector(`nav a[href="#${id}"]`);
        if (tocLink) {
          tocLink.classList.add('active-toc-item', 'toc-active-text', 'font-medium', 'toc-active-border');
          tocLink.classList.remove('border-transparent');

          setTimeout(() => {
            tocLink.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'nearest' });
          }, 10);
        }
      }

      const observer = new IntersectionObserver((entries) => {
        if (observerPaused) return;

        entries.forEach((entry) => {
          const id = entry.target.getAttribute('id');
          if (entry.isIntersecting && id) {
            highlightTocItem(id);
          }
        });
      }, observerOptions);

      const prose = document.querySelector('.prose');
      if (!prose) return;

      const headings = prose.querySelectorAll('h1[id], h2[id], h3[id]');

      if (headings.length > 0) {
        headings.forEach((heading) => observer.observe(heading));
      } else {
        const allHeadings = prose.querySelectorAll('h1, h2, h3');
        allHeadings.forEach((heading) => {
          if (!heading.id) {
            const text = heading.textContent || '';
            heading.id = text
              .toLowerCase()
              .replace(/[^\w\s-]/g, '')
              .replace(/\s+/g, '-');
          }
          observer.observe(heading);
        });
      }

      const tocLinks = document.querySelectorAll('nav a[href^="#"]');
      tocLinks.forEach((link) => {
        link.addEventListener('click', () => {
          const hrefAttr = link.getAttribute('href');
          if (!hrefAttr) return;

          const id = hrefAttr.substring(1);
          highlightTocItem(id);

          observerPaused = true;
          setTimeout(() => {
            observerPaused = false;
          }, 1000);
        });
      });
    } catch (error) {
      console.error('Error setting up TOC observer:', error);
    }
  }

  setupObserver();
  document.addEventListener('astro:page-load', setupObserver);
</script>
