---
import ComponentPreview from "./ComponentPreview.astro";
import CodeBlock from "./CodeBlock.astro";
import { extractDemoSnippet } from "~/lib/extract-demo-snippet";

// Import all demo source files as raw strings at build time
const demoSources = import.meta.glob("~/components/demos/*.tsx", {
  eager: true,
  query: "?raw",
  import: "default",
}) as Record<string, string>;

interface Props {
  /** Raw code string (legacy) */
  code?: string;
  /** Name of the demo function to extract, e.g. "InputBasicDemo". Auto-discovers the file. */
  demo?: string;
  lang?: "tsx" | "ts" | "jsx" | "js" | "bash" | "css";
  vrSection?: string;
  vrTitle?: string;
}

const { code, demo, lang = "tsx", vrSection, vrTitle } = Astro.props;

// Resolve the code snippet: either from the `code` prop (legacy) or auto-extracted from demo source
let resolvedCode = code ?? "";

if (demo) {
  // Scan all loaded sources for the function name
  let found = false;
  for (const [, source] of Object.entries(demoSources)) {
    if (source.includes(`function ${demo}`)) {
      resolvedCode = extractDemoSnippet(source, demo);
      found = true;
      break;
    }
  }
  if (!found) {
    resolvedCode = `// Could not find demo "${demo}" in any demo file`;
    console.warn(`[ComponentExample] Could not find demo "${demo}" in any demo file`);
  }
} else if (!code) {
  console.warn(`[ComponentExample] Missing both "code" and "demo" props`);
}

const vrAttrs = vrSection
  ? {
      "data-vr-demo": "",
      "data-vr-section": vrSection,
      "data-vr-title":
        vrTitle ||
        vrSection
          .replace(/-/g, " ")
          .replace(/\b\w/g, (c) => c.toUpperCase()),
    }
  : {};
---

<div class="not-prose overflow-hidden rounded-lg" {...vrAttrs}>
  <ComponentPreview>
    <slot />
  </ComponentPreview>
  <div class="component-example-code">
    <CodeBlock code={resolvedCode} lang={lang} />
  </div>
</div>

<style>
  .component-example-code :global(pre.astro-code) {
    border-radius: 0;
    border-bottom-left-radius: 0.5rem;
    border-bottom-right-radius: 0.5rem;
    border-top: 0;
  }
</style>
