---
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 (including subdirectories)
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`);
}

// Auto-derive vrSection from demo prop: "ButtonLoadingDemo" → "button-loading"
function toKebabCase(str: string): string {
  return str
    .replace(/Demo$/, "")
    .replace(/([a-z])([A-Z])/g, "$1-$2")
    .toLowerCase();
}

// Auto-derive vrTitle from demo prop: "ButtonLoadingDemo" → "Button Loading"
function toTitleCase(str: string): string {
  return str
    .replace(/Demo$/, "")
    .replace(/([a-z])([A-Z])/g, "$1 $2");
}

const resolvedVrSection = vrSection ?? (demo ? toKebabCase(demo) : undefined);
const resolvedVrTitle = vrTitle ?? (demo ? toTitleCase(demo) : undefined);

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

<div class="not-prose overflow-hidden rounded-lg">
  <ComponentPreview {...vrAttrs}>
    <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>
