"use client";

// import BespokeLayout1 from "./BespokeLayout1";
import BespokeLayout2 from "./BespokeLayout2";
import BespokeLayout3 from "./BespokeLayout3";
import type { BespokePageData } from "@/utils/strapi";
import { getStrapiImageUrl } from "@/utils/getStrapiUrl";
import { getPrimaryTypeSlugForUrl } from "@/utils/propertyTypes";

interface BespokeContentProps {
  bespokeData?: BespokePageData | null;
}

const BespokeContent = ({ bespokeData }: BespokeContentProps) => {
  const projects = bespokeData?.projects || [];

  // Extract full URL from normalized Strapi image (url at top level or in data.attributes)
  const getImageUrl = (imageData: any): string | null => {
    if (!imageData) return null;
    const raw =
      typeof imageData === "string"
        ? imageData
        : imageData.url || imageData.data?.attributes?.url || imageData.attributes?.url;
    if (!raw) return null;
    return getStrapiImageUrl(raw) || null;
  };

  // Build srcSet from formats (URLs are already absolute from server normalizer)
  const getImageSrcSet = (imageData: any): string | undefined => {
    if (!imageData?.formats) return undefined;
    const parts: string[] = [];
    if (imageData.formats.large?.url) parts.push(`${imageData.formats.large.url} 1000w`);
    if (imageData.formats.medium?.url) parts.push(`${imageData.formats.medium.url} 750w`);
    if (imageData.formats.small?.url) parts.push(`${imageData.formats.small.url} 500w`);
    return parts.length > 0 ? parts.join(", ") : undefined;
  };

  // If no projects from Strapi, show nothing
  if (projects.length === 0) {
    return null;
  }

  return (
    <section className="w-full bg-white">
      {projects.map((project, index) => {
        // Use project-specific data or fallback to property data
        const title = project.title || project.property?.title || "";
        const address = project.address || project.property?.address || "";
        const tagline = project.tagline || "";

        // Build property details href when possible, otherwise leave undefined for graceful fallback
        const propertySlug = project.property?.slug;
        const typeSeg = project.property
          ? getPrimaryTypeSlugForUrl(project.property)
          : "";
        const href =
          typeSeg && propertySlug
            ? `/properties/${typeSeg}/${propertySlug}`
            : undefined;


        // Same order as FeaturedProperties: project image first, then property.cardImage
        const projectImages = project.images ?? (project.image ? [project.image] : []);
        const leftImageData =
          projectImages[0] ?? project.image ?? project.property?.cardImage;
        const rightImageData = projectImages[1] || project.property?.cardHoverImage;
        const singleImageData = projectImages[0] ?? project.image ?? project.property?.cardImage;

        const leftImageUrl = getImageUrl(leftImageData);
        const rightImageUrlRaw = rightImageData ? getImageUrl(rightImageData) : null;
        // Never use the same image for both slots – only set right when it's a different URL
        const rightImageUrl =
          rightImageUrlRaw && rightImageUrlRaw !== leftImageUrl
            ? rightImageUrlRaw
            : null;

        const singleImageUrl = getImageUrl(singleImageData);

        // Stable key per project so React doesn't reuse the wrong component (fixes first/last showing same image)
        const projectKey = project.property?.id ?? project.title ?? `project-${index}`;

        // Alternate layouts: even index (0, 2, 4...) = layout1, odd index (1, 3, 5...) = layout2
        const isLayout1 = index % 2 === 0;

        const leftSrcSet = getImageSrcSet(leftImageData);
        const rightSrcSet = rightImageData ? getImageSrcSet(rightImageData) : undefined;
        const singleSrcSet = getImageSrcSet(singleImageData);

        if (isLayout1) {
          return (
            <BespokeLayout2
              key={projectKey}
              title={title}
              address={address}
              tagline={tagline}
              href={href}
              image={singleImageUrl ? {
                src: singleImageUrl,
                alt: singleImageData?.data?.attributes?.alternativeText || title,
                srcSet: singleSrcSet,
              } : undefined}
            />
          );
        } else {
          return (
            <BespokeLayout3
              key={projectKey}
              title={title}
              address={address}
              tagline={tagline}
              href={href}
              image={singleImageUrl ? {
                src: singleImageUrl,
                alt: singleImageData?.data?.attributes?.alternativeText || title,
                srcSet: singleSrcSet,
              } : undefined}
            />
          );
        }
      })}
    </section>
  );
};

export default BespokeContent;
