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

import MediaImage from "./ui/MediaImage";
import ActionIcon from "./ui/ActionIcon";
import RichText from "./ui/RichText";
import Btn from "./ui/Btn";
import Facts from "./ui/Facts";
import FloorPlans from "./ui/FloorPlans";
import Gallery from "./ui/Gallery";
import ProjectNav from "./ui/ProjectNav";

/**
 * The project detail page, both compositions.
 *
 * `projects/show-full.blade.php` and `projects/show.blade.php`, translated. All
 * of the content derivation those templates did inline — extracting action
 * buttons from the body, lifting a feature strip out of `<h5>` runs, splitting
 * the body at the luxury heading, grouping floor plans into tabs — happens in
 * the backend's ProjectPagePayload now. This renders the result.
 *
 * Which composition a project uses is decided from its content, not from an id,
 * so new and re-imported records cannot fall back into empty bands.
 */
export default function ProjectPage({
  data,
  meta,
  ctx,
  full,
  PageHero,
}: {
  data: any;
  meta: any;
  ctx: RenderContext;
  full: boolean;
  PageHero: (props: any) => React.ReactNode;
}) {
  const p = data.project;
  const t = ctx.t;
  const compact = Boolean(p.compactLayout);

  if (!full) {
    return <SimpleProject data={data} meta={meta} ctx={ctx} PageHero={PageHero} />;
  }

  const hasOverviewActions =
    p.brochureUrl || p.videoUrl || p.mapLinkUrl || p.virtualTourUrl || (p.overviewActions ?? []).length > 0;

  return (
    <div
      // `--project-accent` was a body style attribute on the Blade layout.
      style={{ ["--project-accent" as any]: p.accentColor }}
      data-project={p.slug ?? undefined}
    >
      <PageHero
        title={p.title}
        crumbs={meta.breadcrumbs}
        t={t}
        className={compact ? "page-hero--published-compact" : ""}
      />

      {/*
        The wide photograph the page opens with, between the title band and the
        logo. Only some projects have one — Green Fields and Aurora Villas go
        straight from the title to the logo on the published site — so it is
        omitted rather than reserving empty height when `cover` is null.
      */}
      {p.cover ? (
        <section className="project-cover-section">
          <div className="container project-cover">
            <MediaImage image={p.cover} alt={p.title} eager />
          </div>
        </section>
      ) : null}

      {p.logo ? (
        <section
          className={`project-logo-stage${compact ? " project-logo-stage--published-compact" : ""}`}
        >
          <MediaImage image={{ ...p.logo, width: 300, height: 300 }} alt={p.title} eager />
        </section>
      ) : null}

      <section
        className={`project-overview-section${compact ? " project-overview-section--published-compact" : ""}`}
      >
        {/*
          .project-intro carries the photograph off .project-intro__image::before
          and the whole column layout off .project-intro__copy. Rendering a bare
          img and a bare div loses both.
        */}
        <div
          className={[
            "container",
            "project-intro",
            compact ? "project-intro--published-compact" : "",
            compact && p.overviewHasProse ? "project-intro--with-prose" : "",
          ]
            .filter(Boolean)
            .join(" ")}
        >
          {compact ? (
            <div className="project-intro__media">
              {p.hero ? (
                <div className="project-intro__image">
                  <MediaImage image={p.hero} alt={p.title} eager />
                </div>
              ) : null}

              {hasOverviewActions ? (
                <div className="project-overview-actions">
                  {p.brochureUrl ? (
                    // target=_blank so the brochure opens in a tab to be read
                    // rather than going straight to the downloads folder.
                    <Btn
                      href={p.brochureUrl}
                      className="project-overview-action--brochure"
                      target="_blank"
                      rel="noopener"
                    >
                      <ActionIcon name="download" />
                      {t("projects.actions.brochure")}
                    </Btn>
                  ) : null}

                  {p.videoUrl ? (
                    <button className="btn project-overview-action--video" type="button" data-project-video-open>
                      <ActionIcon name="play" />
                      {t("projects.actions.watch_video")}
                    </button>
                  ) : null}

                  {p.mapLinkUrl ? (
                    <Btn
                      href={p.mapLinkUrl}
                      className="project-overview-action--map"
                      target="_blank"
                      rel="noopener noreferrer"
                    >
                      <ActionIcon name="pin" />
                      {t("projects.location_section")}
                    </Btn>
                  ) : null}

                  {/* Beside Location, the way the published site orders them:
                      Location, Interactive tours, Brochure. */}
                  {p.virtualTourUrl ? (
                    <Btn
                      href={p.virtualTourUrl}
                      className="project-overview-action--tour"
                      target="_blank"
                      rel="noopener noreferrer"
                    >
                      <ActionIcon name="globe" />
                      {t("projects.actions.virtual_tour")}
                    </Btn>
                  ) : null}

                  {(p.overviewActions ?? []).map((action: any, i: number) => (
                    <Btn
                      key={i}
                      href={action.url}
                      className={
                        action.isDocument
                          ? "project-overview-action--document"
                          : "project-overview-action--external"
                      }
                      target="_blank"
                      rel="noopener noreferrer"
                    >
                      <ActionIcon name={action.isDocument ? "download" : "globe"} />
                      {action.label}
                    </Btn>
                  ))}
                </div>
              ) : null}
            </div>
          ) : /*
              The column is half of a two-column grid, so an empty one is not
              nothing — it is 550px of reserved blank beside the copy. Two
              projects set overview_image_mode to `none` and both rendered
              exactly that. With the div gone the grid collapses to one column
              and the copy takes the width.
            */
          p.hero && p.overviewImageMode !== "none" ? (
            <div className="project-intro__media">
              <div
                className={`project-intro__image${
                  p.overviewImageMode === "portrait" ? " project-intro__image--portrait" : ""
                }`}
              >
                <MediaImage image={p.hero} alt={p.title} eager />
              </div>
            </div>
          ) : null}

          <div className="project-intro__copy">
            {compact ? (
              <>
                {p.overviewHasHeading ? (
                  <RichText html={p.overviewBody} className="article-prose project-intro__body" />
                ) : (
                  <>
                    <h2>{p.tagline || p.title}</h2>
                    {p.overviewHasProse ? (
                      <RichText html={p.overviewBody} className="article-prose project-intro__body" />
                    ) : null}
                  </>
                )}
                {!p.overviewHasProse && p.summary ? <p>{p.summary}</p> : null}
              </>
            ) : (
              <>
                <h2>{p.tagline || p.title}</h2>
                {p.summary ? <p>{p.summary}</p> : null}
              </>
            )}

            <Facts facts={p.facts} />

            {!compact && p.tour360Url ? (
              <div className="project-intro-special-actions">
                <Btn href={p.tour360Url} target="_blank" rel="noopener noreferrer">
                  <ActionIcon name="globe" />
                  {t("projects.actions.tour_360")}
                </Btn>
              </div>
            ) : null}
          </div>
        </div>
      </section>

      {compact && (p.compactFeatures ?? []).length > 0 ? (
        <section className="project-compact-features">
          <div className="container project-compact-features__inner">
            {p.compactFeatures.map((feature: string, i: number) => (
              <span key={i}>{feature}</span>
            ))}
          </div>
        </section>
      ) : null}

      {!compact && ((p.distances ?? []).length > 0 || p.mapLinkUrl) ? (
        <section className="project-location-section">
          <div className="container location-grid">
            <div className="location-copy">
              {/* The project's own name, not the word "location" — which would
                  otherwise appear twice, here and on the button below. */}
              <h2 className="section-title">{p.title}</h2>
              {p.address ? <p>{p.address}</p> : null}
              {p.mapLinkUrl ? (
                <Btn href={p.mapLinkUrl} target="_blank" rel="noopener noreferrer">
                  <ActionIcon name="pin" />
                  {t("ui.view_on_map")}
                </Btn>
              ) : null}
            </div>

            {(p.distances ?? []).length > 0 ? (
              <div className="distances">
                {p.distances.map((distance: any, i: number) => (
                  <div key={i}>
                    <div className="distance-head">
                      <span>{distance.place}</span>
                      {distance.label ? <span>{distance.label}</span> : null}
                    </div>
                    {/* The bar is drawn from the same number the label states,
                        so the visual cannot contradict the fact. The duration
                        repeats inside for the narrow layout where the head
                        wraps. */}
                    <div className="distance-bar">
                      <i style={{ ["--progress" as any]: `${distance.percent}%` }}>
                        <span>{distance.label}</span>
                      </i>
                    </div>
                  </div>
                ))}
              </div>
            ) : null}
          </div>
        </section>
      ) : null}

      <FloorPlans groups={p.floorPlanGroups ?? []} />

      {p.editorialBody ? (
        <section className="project-editorial-section">
          <RichText
            html={p.editorialBody}
            className="container article-prose project-editorial-content"
          />
        </section>
      ) : null}

      {(p.features ?? []).length > 0 ? (
        <section
          className={`project-features-section${p.concept ? " project-features-section--concept" : ""}`}
        >
          <div className="container">
            <div className="project-features-layout">
              <div className="project-features-copy">
                {p.conceptKicker ? <p className="project-features-kicker">{p.conceptKicker}</p> : null}
                {p.featuresTitle ? <h2 className="section-title">{p.featuresTitle}</h2> : null}
                <div className="project-features-grid">
                  {p.features.map((feature: any, i: number) => (
                    <div className="project-feature" key={i}>
                      {feature.icon ? <MediaImage image={feature.icon} alt={feature.label} /> : null}
                      {feature.label ? <span>{feature.label}</span> : null}
                    </div>
                  ))}
                </div>
              </div>
              {p.concept ? (
                <div className="project-features-concept-image">
                  <MediaImage image={p.concept} alt={p.title} />
                </div>
              ) : null}
            </div>
          </div>
        </section>
      ) : null}

      {(p.guarantees ?? []).length > 0 ? (
        <section className="project-guarantees-section">
          <div className="container">
            <h2 className="section-title">{t("projects.guarantees")}</h2>
            <div className="project-guarantees-grid">
              {p.guarantees.map((guarantee: any, i: number) => (
                <div className="project-guarantee" key={i}>
                  {guarantee.icon ? <MediaImage image={guarantee.icon} alt="" /> : null}
                  {guarantee.years ? <strong>{guarantee.years}</strong> : null}
                  {guarantee.label ? <span>{guarantee.label}</span> : null}
                </div>
              ))}
            </div>
          </div>
        </section>
      ) : null}

      {/*
        The luxury band: the copy and its call to action on one side, the
        materials graphic on the other. `.luxury-grid` IS that two-column grid —
        rendering the image as a sibling below the copy instead, as an earlier
        pass did, made the section 535px taller than the design.

        `--single` collapses it to one column when there is no graphic, rather
        than leaving half the row reserved and empty.
      */}
      {!compact && (p.luxuryBody || p.luxury) ? (
        <section className="project-luxury-section">
          <div className={`container luxury-grid${p.luxury ? "" : " luxury-grid--single"}`}>
            <div>
              <RichText html={p.luxuryBody} className="article-prose" />

              {p.brochureUrl || (!compact && (p.videoUrl || p.virtualTourUrl)) ? (
                <div className="project-luxury-actions">
                  {/*
                      The brochure always; video and the tour only when the
                      overview row above did not already offer them.

                      That row renders for compact projects only, so on those
                      the same "Watch video" appeared twice — once before the
                      copy and once beneath the artwork, which is what the client
                      reported on First Projects Business. On the full layout
                      there is no overview row at all, and dropping them here
                      outright took Vega's video and tour off the page entirely.

                      .btn is load-bearing: without it the link rendered as a
                      loose line of text beside the circle.
                  */}
                  {p.brochureUrl ? (
                    <a
                      className="btn project-brochure"
                      href={p.brochureUrl}
                      target="_blank"
                      rel="noopener"
                    >
                      <ActionIcon name="download" />
                      {t("projects.actions.brochure")}
                    </a>
                  ) : null}
                  {!compact && p.videoUrl ? (
                    <button className="btn" type="button" data-project-video-open>
                      <ActionIcon name="play" />
                      {t("projects.actions.watch_video")}
                    </button>
                  ) : null}
                  {!compact && p.virtualTourUrl ? (
                    <a
                      className="btn"
                      href={p.virtualTourUrl}
                      target="_blank"
                      rel="noopener noreferrer"
                    >
                      <ActionIcon name="globe" />
                      {t("projects.actions.virtual_tour")}
                    </a>
                  ) : null}
                </div>
              ) : null}
            </div>

            {p.luxury ? (
              <div className="luxury-image">
                <MediaImage image={p.luxury} alt={p.title} />
              </div>
            ) : null}
          </div>
        </section>
      ) : null}

      {!compact && (p.bodyGallery ?? []).length > 0 ? (
        <section className="project-body-gallery-section" aria-label={t("projects.gallery")}>
          <div className="container">
            <div className="gallery-grid">
              {p.bodyGallery.map((image: any, i: number) => (
                <div className="gallery-item" key={i}>
                  <MediaImage image={image} />
                </div>
              ))}
            </div>
          </div>
        </section>
      ) : null}

      {(p.gallery ?? []).length > 0 ? (
        <section className="project-gallery-section" aria-label={t("projects.gallery")}>
          <div className="container">
            <Gallery
              items={p.gallery}
              name="project-gallery"
              alt={p.title}
              arrows="chevron"
              labels={{
                previous: t("ui.previous"),
                next: t("ui.next"),
                close: t("js.close_menu"),
              }}
            />
          </div>
        </section>
      ) : null}

      {p.mapEmbedUrl ? (
        <section className="project-map-section">
          <iframe
            className="map-frame"
            src={p.mapEmbedUrl}
            title={t("projects.location_section")}
            loading="lazy"
            referrerPolicy="no-referrer-when-downgrade"
            allowFullScreen
          />
        </section>
      ) : null}

      <ProjectNav previous={data.previousProject} next={data.nextProject} t={t} />
    </div>
  );
}

/**
 * The simple composition: hero, summary and facts, body, navigation.
 *
 * Four of the forty-three published projects use it.
 */
function SimpleProject({
  data,
  meta,
  ctx,
  PageHero,
}: {
  data: any;
  meta: any;
  ctx: RenderContext;
  PageHero: (props: any) => React.ReactNode;
}) {
  const p = data.project;

  return (
    <div style={{ ["--project-accent" as any]: p.accentColor }} data-project={p.slug ?? undefined}>
      <PageHero title={p.title} crumbs={meta.breadcrumbs} t={ctx.t} />

      {p.hero ? (
        <div className="variant-project-visual container">
          <MediaImage image={p.hero} alt={p.title} eager />
        </div>
      ) : null}

      <div className="container variant-project-summary">
        <h2>{p.title}</h2>
        {p.summaryText ? <p>{p.summaryText}</p> : null}
        <Facts facts={p.facts} />
      </div>

      {p.body ? (
        <section className="variant-project-copy lined">
          <div className="container">
            <RichText html={p.body} className="article-prose" />
            <button className="btn js-open-drawer" type="button" data-source-component="project-copy">
              {ctx.t("ui.register_interest")}
            </button>
          </div>
        </section>
      ) : null}

      <ProjectNav previous={data.previousProject} next={data.nextProject} t={ctx.t} />
    </div>
  );
}
