import "./_load";
import { getSection } from "./registry";
import { getSchema } from "./schemas";
import { SectionFallback } from "./SectionFallback";

export interface RenderableSection {
  layout: string;
  data: unknown;
}

interface PageRendererProps {
  sections: RenderableSection[];
}

export function PageRenderer({ sections }: PageRendererProps) {
  return (
    <>
      {sections.map((section, index) => {
        const Component = getSection(section.layout);
        const schema = getSchema(section.layout);

        if (!Component) {
          return (
            <SectionFallback
              key={`${section.layout}-${index}`}
              layout={section.layout}
              reason="Layout not registered in components registry."
            />
          );
        }

        let parsed: unknown = section.data;
        if (schema) {
          const result = schema.safeParse(section.data);
          if (!result.success) {
            return (
              <SectionFallback
                key={`${section.layout}-${index}`}
                layout={section.layout}
                reason={`Schema validation failed: ${result.error.issues[0]?.message ?? "unknown"}`}
              />
            );
          }
          parsed = result.data;
        }

        return <Component key={`${section.layout}-${index}`} data={parsed} />;
      })}
    </>
  );
}
