import { compileMDXContent, type TableOfContentsItem } from '@/lib/docs/mdx'
import { mdxComponents } from './mdx'

/**
 * MDX Renderer Component
 * 
 * Server component that compiles and renders MDX content with all custom components.
 */

interface MDXRendererProps {
  /** Raw MDX source content */
  source: string
  /** Optional additional components to include */
  components?: Record<string, React.ComponentType<unknown>>
  /** Optional scope variables available in MDX */
  scope?: Record<string, unknown>
  /** Callback to receive table of contents */
  onTocGenerated?: (toc: TableOfContentsItem[]) => void
}

export async function MDXRenderer({
  source,
  components: additionalComponents = {},
  scope = {},
}: MDXRendererProps) {
  const { content, frontmatter, headings } = await compileMDXContent(source, {
    components: {
      ...mdxComponents,
      ...additionalComponents,
    } as Record<string, React.ComponentType<unknown>>,
    scope,
  })
  
  return (
    <article className="prose prose-slate dark:prose-invert max-w-none">
      {/* Title from frontmatter */}
      {frontmatter.title && (
        <header className="mb-8 not-prose">
          <h1 className="text-3xl font-bold text-foreground mb-2">
            {frontmatter.title}
          </h1>
          {frontmatter.description && (
            <p className="text-lg text-muted-foreground">
              {frontmatter.description}
            </p>
          )}
        </header>
      )}
      
      {/* MDX Content */}
      <div className="mdx-content">
        {content}
      </div>
      
      {/* Hidden data for client-side access */}
      <script
        type="application/json"
        id="mdx-frontmatter"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(frontmatter) }}
      />
      <script
        type="application/json"
        id="mdx-headings"
        dangerouslySetInnerHTML={{ __html: JSON.stringify(headings) }}
      />
    </article>
  )
}

/**
 * Table of Contents Component
 * 
 * Client component that renders a table of contents from headings
 */
export function TableOfContents({ headings }: { headings: TableOfContentsItem[] }) {
  if (headings.length === 0) return null
  
  return (
    <nav className="toc">
      <h4 className="text-sm font-semibold text-foreground mb-3">On this page</h4>
      <ul className="space-y-2 text-sm">
        {headings.map((heading) => (
          <li
            key={heading.id}
            style={{ paddingLeft: `${(heading.level - 1) * 12}px` }}
          >
            <a
              href={`#${heading.id}`}
              className="text-muted-foreground hover:text-foreground transition-colors"
            >
              {heading.title}
            </a>
          </li>
        ))}
      </ul>
    </nav>
  )
}

export type { TableOfContentsItem }
