import type { ResolveResponse } from "@/lib/api";
import type { RenderContext } from "@/lib/i18n";

import { Sections } from "./sections";
import MediaImage from "./ui/MediaImage";
import RichText from "./ui/RichText";
import ProjectCard from "./ui/ProjectCard";
import ArticleCard from "./ui/ArticleCard";
import VideoEmbed from "./ui/VideoEmbed";
import Gallery from "./ui/Gallery";
import Btn from "./ui/Btn";
import Pagination from "./ui/Pagination";
import ProjectFilters from "./ProjectFilters";
import ProjectPage from "./ProjectPage";
import ProjectNav from "./ui/ProjectNav";

/**
 * Template dispatch.
 *
 * Driven by the `template` field the API returns, not by re-deriving
 * `Page::KEY_*` logic here. Which template a record uses — including the project
 * layout's full/simple split — is a backend decision, and duplicating it would
 * create a second place that could disagree about what a page is.
 */
export function renderTemplate(payload: ResolveResponse, ctx: RenderContext) {
  const data = payload.data;

  switch (payload.template) {
    case "home":
      return <Sections sections={data.page.sections} ctx={ctx} />;

    case "projects":
      return (
        <>
          <PageHero title={data.page.title} crumbs={payload.meta.breadcrumbs} t={ctx.t} />

          <section className="projects-page-section">
            <div className="container">
              {/* Filters and results are resolved server-side so they cannot
                  disagree. */}
              <ProjectFilters panel={data.filterPanel} />

              {/* One node for the enhanced filter to replace. Without scripting
                  this is an ordinary div and every link an ordinary page load. */}
              <div id="projects-results">
                {data.projects.items.length === 0 ? (
                  <div className="empty-state">
                    <h2>{ctx.t("ui.no_results_title")}</h2>
                    <p>{ctx.t("ui.no_results_body")}</p>
                    <Btn variant="fill" href={data.page.url ?? ctx.pageUrls.projects}>
                      {ctx.t("ui.clear_filters")}
                    </Btn>
                  </div>
                ) : (
                  <>
                    <div className="projects-grid">
                      {data.projects.items.map((project: any) => (
                        <ProjectCard key={project.id} project={project} />
                      ))}
                    </div>
                    <Pagination pagination={data.projects.pagination} label={ctx.t("ui.next")} />
                  </>
                )}
              </div>
            </div>
          </section>
        </>
      );

    case "posts-index":
      return (
        <>
          <PageHero title={data.page.title} crumbs={payload.meta.breadcrumbs} t={ctx.t} />

          <section className="section">
            <div className="container">
              {data.posts.items.length === 0 ? (
                <p className="empty-state">{ctx.t("ui.no_results_title")}</p>
              ) : (
                <>
                  <div
                    className={`articles-grid${data.postType === "news" ? " articles-grid--wide" : ""}`}
                  >
                    {data.posts.items.map((post: any) => (
                      <ArticleCard key={post.id} post={post} t={ctx.t} />
                    ))}
                  </div>
                  <Pagination pagination={data.posts.pagination} label={ctx.t("ui.next")} />
                </>
              )}
            </div>
          </section>
        </>
      );

    case "media":
      return (
        <>
          <PageHero title={data.page.title} crumbs={payload.meta.breadcrumbs} t={ctx.t} />

          <section className="section">
            <div className="container">
              <div className="videos-grid">
                {data.videos.map((video: any, i: number) => (
                  <VideoEmbed key={video.id} video={video} eager={i === 0} playLabel={ctx.t("ui.play")} />
                ))}
              </div>
            </div>
          </section>
        </>
      );

    case "project":
    case "project-full":
      return (
        <ProjectPage
          data={data}
          meta={payload.meta}
          ctx={ctx}
          full={payload.template === "project-full"}
          PageHero={PageHero}
        />
      );

    case "post":
      return <PostPage data={data} meta={payload.meta} ctx={ctx} />;

    case "service":
      return <ServicePage data={data} meta={payload.meta} ctx={ctx} />;

    case "show":
    default:
      return (
        <>
          <PageHero title={data.page.title} crumbs={payload.meta.breadcrumbs} t={ctx.t} />

          {/* The page's own artwork, not a block: it belongs to the page the way
              its title does, and the design places it before any band. */}
          {data.page.hero ? (
            <section className="about-hero" aria-label={data.page.title}>
              <MediaImage image={data.page.hero} alt={data.page.hero.alt || ""} eager />
            </section>
          ) : null}

          {data.page.intro ? (
            <section className="section section--tight">
              <div className="container">
                <RichText html={data.page.intro} className="article-prose" />
              </div>
            </section>
          ) : null}

          <Sections sections={data.page?.sections ?? []} ctx={ctx} />
        </>
      );
  }
}

/**
 * The page hero doubles as the breadcrumb rail and is display:none below 768px
 * by design.
 *
 * Because of that the breadcrumb *schema* is emitted from SeoManager and not
 * inferred from this markup — the structured data must survive on mobile even
 * though the visible trail does not.
 */
export function PageHero({
  title,
  crumbs,
  t,
  className,
}: {
  title: string;
  crumbs: Array<{ title: string; url: string | null }>;
  t: RenderContext["t"];
  className?: string;
}) {
  return (
    <section className={["page-hero", "lined", className].filter(Boolean).join(" ")}>
      <div className="container">
        <h1>{title}</h1>

        {crumbs.length > 1 ? (
          <nav className="breadcrumbs" aria-label={t("ui.breadcrumb")}>
            {crumbs.map((crumb, index) => (
              <span key={index} style={{ display: "contents" }}>
                {crumb.url ? (
                  <a href={crumb.url}>{crumb.title}</a>
                ) : (
                  <span aria-current="page">{crumb.title}</span>
                )}
                {index < crumbs.length - 1 ? " - " : null}
              </span>
            ))}
          </nav>
        ) : null}
      </div>
    </section>
  );
}

function PostPage({ data, meta, ctx }: { data: any; meta: any; ctx: RenderContext }) {
  const post = data.post;

  return (
    <article className="article-page">
      <PageHero title={post.title} crumbs={meta.breadcrumbs} t={ctx.t} />

      <div className="container">
        {post.cover ? <MediaImage image={post.cover} eager className="article-cover" /> : null}

        {post.publishedAtFormatted ? (
          <div className="article-meta">
            <time dateTime={post.publishedAt?.slice(0, 10)}>{post.publishedAtFormatted}</time>
          </div>
        ) : null}

        {post.lead ? <p className="article-lead">{post.lead}</p> : null}

        <RichText html={post.body} className="article-prose" />
      </div>

      {post.gallery?.length ? (
        <Gallery
          items={post.gallery}
          name="post-gallery"
          alt={post.title}
          labels={{ previous: ctx.t("ui.previous"), next: ctx.t("ui.next"), close: ctx.t("js.close_menu") }}
        />
      ) : null}

      <ProjectNav previous={data.previous} next={data.next} t={ctx.t} />
    </article>
  );
}

function ServicePage({ data, meta, ctx }: { data: any; meta: any; ctx: RenderContext }) {
  const service = data.service;

  return (
    <article className="service-page">
      <PageHero title={service.title} crumbs={meta.breadcrumbs} t={ctx.t} />

      {service.image ? <MediaImage image={service.image} eager /> : null}

      <div className="container">
        {service.summary ? <p className="article-lead">{service.summary}</p> : null}
        <RichText html={service.body} className="article-prose" />
      </div>

      {service.faqs?.length ? (
        <section className="section section--tight">
          <div className="container">
            <div className="accordion" data-accordion>
              {service.faqs.map((faq: any, index: number) => (
                <div key={index} style={{ display: "contents" }}>
                  <h3 className="accordion__title">
                    <button type="button" aria-expanded={index === 0}>
                      {faq.question}
                    </button>
                  </h3>
                  <div className="accordion__panel">
                    <div className="accordion__panel-inner">
                      <RichText html={faq.answer} className={undefined} />
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>
        </section>
      ) : null}
    </article>
  );
}
