import type { ReactNode } from "react";
import { ChevronRightIcon } from "lucide-react";

import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible";
import { cn } from "@/lib/utils";

/**
 * A labelled, bordered box that renders a component, with an optional collapsible code snippet.
 * `bare` removes the inner padding (tables, full-width screens). `className` styles the preview area.
 */
export function Example({
  title,
  description,
  code,
  bare = false,
  className,
  children,
}: {
  title: string;
  description?: string;
  code?: string;
  bare?: boolean;
  className?: string;
  children: ReactNode;
}) {
  return (
    <figure className="overflow-hidden rounded-lg border border-border bg-card">
      <figcaption className="flex items-baseline justify-between gap-4 border-b border-border bg-muted/50 px-4 py-2">
        <span className="text-xs font-medium text-foreground">{title}</span>
        {description ? <span className="truncate text-xs text-muted-foreground">{description}</span> : null}
      </figcaption>
      {/* The app's canvas behind every preview (foundations: content sits on white surfaces on bg-canvas), so a component without its own surface shows here as it would in the app */}
      <div className={cn("bg-[var(--color-bg-canvas)]", bare ? "" : "p-4", className)}>{children}</div>
      {code ? (
        <Collapsible className="border-t border-border">
          <CollapsibleTrigger className="group flex w-full cursor-pointer items-center gap-1 px-4 py-2 text-xs text-muted-foreground outline-none hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring">
            <ChevronRightIcon className="size-3.5 transition-transform group-data-[panel-open]:rotate-90" />
            Code
          </CollapsibleTrigger>
          <CollapsibleContent>
            <pre className="overflow-x-auto border-t border-border bg-muted px-4 py-3 font-mono text-xs leading-5 text-foreground">
              <code>{code}</code>
            </pre>
          </CollapsibleContent>
        </Collapsible>
      ) : null}
    </figure>
  );
}
