import { Fragment, type ReactNode } from "react";
import type { PageSection } from "@/app/(site)/_lib/pageContent";

/**
 * Where a section is rendered: the page's sections in display order and its index
 * among them. Used by designs where two CMS sections share one band (see `joined`).
 * `preview` is set in the admin's live preview.
 */
export type SectionContext = { sections: { key: string; content: unknown }[]; index: number; preview?: boolean };

/** Renders one section's content. Keyed by section key: the markup differs per page even for the same type. */
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type SectionRenderers = Record<string, (content: any, ctx?: SectionContext) => ReactNode>;

/** The section right after this one, when it has the given key. */
export function nextIs(ctx: SectionContext | undefined, key: string): { key: string; content: unknown } | undefined {
  const next = ctx?.sections[ctx.index + 1];
  return next?.key === key ? next : undefined;
}

/** True when the section right before this one has the given key. */
export const prevIs = (ctx: SectionContext | undefined, key: string) => ctx?.sections[ctx.index - 1]?.key === key;

/**
 * A section drawn inside the band of the section before it (the static markup has both
 * in one <section>). In the admin preview it keeps its own clickable area. A failure in
 * its content leaves it out instead of breaking the band.
 */
export function joined(key: string, render: () => ReactNode, ctx: SectionContext | undefined): ReactNode {
  let node: ReactNode;
  try {
    node = render();
  } catch (err) {
    console.warn(`[cms] ${key}: can't render the CMS content.`, err instanceof Error ? err.message : err);
    return null;
  }
  return ctx?.preview ? (
    <div data-s={key} style={{ display: "contents" }}>
      {node}
    </div>
  ) : (
    node
  );
}

/**
 * The sections of an inner page in display order.
 *
 * - CMS page available: its sections, in the CMS order. Hidden and unpublished sections
 *   are not in the response, so they are left out.
 * - No CMS page (API down, or nothing published yet): the built-in sections.
 *
 * A section whose content can't be rendered (unexpected shape) falls back to its
 * built-in version, so one bad section never takes the page down.
 */
export function renderSections(pageKey: string, data: { sections: PageSection[] } | null, defaults: PageSection[], renderers: SectionRenderers): ReactNode[] {
  const sections = data?.sections ?? defaults;
  return sections.map((s, index) => {
    const render = renderers[s.key];
    if (!render) return null;
    const ctx: SectionContext = { sections, index };
    let node: ReactNode;
    try {
      node = render(s.content, ctx);
    } catch (err) {
      console.warn(`[cms] ${pageKey}/${s.key}: can't render the CMS content, showing the built-in version.`, err instanceof Error ? err.message : err);
      const fallback = defaults.find((d) => d.key === s.key);
      try {
        node = fallback ? render(fallback.content, ctx) : null;
      } catch {
        node = null;
      }
    }
    return <Fragment key={s.key}>{node}</Fragment>;
  });
}
