import type { StoreSiteBlock } from "@alqove/api-client";
import { ContactBlock } from "./blocks/contact-block";
import { CtaBlock } from "./blocks/cta-block";
import { FaqBlock } from "./blocks/faq-block";
import { GalleryBlock } from "./blocks/gallery-block";
import { HeroBlock } from "./blocks/hero-block";
import { HoursBlock } from "./blocks/hours-block";
import { MapBlock } from "./blocks/map-block";
import { ProductsBlock } from "./blocks/products-block";
import { RichTextBlock } from "./blocks/rich-text-block";
import { blockKey } from "./block-key";
import type { StorefrontRenderContext } from "./links";
import type { StorefrontProduct } from "./products";

interface BlockRendererProps {
  blocks: StoreSiteBlock[] | null | undefined;
  ctx: StorefrontRenderContext;
  /** Listings for each `products` block, keyed by block id. */
  productsByBlock?: Record<string, StorefrontProduct[]>;
}

/**
 * Renders a page's ordered blocks. Every block component is synchronous and
 * client-safe, so the same renderer drives the public server-rendered page and
 * the seller's live editor preview.
 *
 * A block whose `type` this build doesn't know is skipped rather than throwing,
 * so the API can ship a new block type before the web tier has a renderer for
 * it without breaking live storefronts.
 */
export function BlockRenderer({ blocks, ctx, productsByBlock = {} }: BlockRendererProps) {
  return (
    <>
      {(blocks ?? []).map((block, index) => {
        const key = blockKey(block, index);

        switch (block.type) {
          case "hero":
            return <HeroBlock key={key} block={block} ctx={ctx} />;
          case "rich_text":
            return <RichTextBlock key={key} block={block} />;
          case "products":
            return (
              <ProductsBlock
                key={key}
                block={block}
                ctx={ctx}
                products={productsByBlock[key] ?? []}
              />
            );
          case "hours":
            return <HoursBlock key={key} block={block} ctx={ctx} />;
          case "map":
            return <MapBlock key={key} block={block} ctx={ctx} />;
          case "contact":
            return <ContactBlock key={key} block={block} ctx={ctx} />;
          case "gallery":
            return <GalleryBlock key={key} block={block} />;
          case "cta":
            return <CtaBlock key={key} block={block} ctx={ctx} />;
          case "faq":
            return <FaqBlock key={key} block={block} />;
          case "divider":
            return (
              <hr
                key={key}
                className="mx-auto max-w-6xl"
                style={{ borderColor: "var(--sf-border)" }}
              />
            );
          default:
            return null;
        }
      })}
    </>
  );
}
