import Title from "@/components/atoms/Title";
import Image from "next/image";
import { getStrapiImageUrl } from "@/utils/getStrapiUrl";
import type { ServiceItem } from "@/utils/strapi";

const FALLBACK_IMAGE = "/images/designo/services/designo-service.png";

/** Absolute Strapi URL for next/image; avoids relative /uploads/... hitting the Next origin. */
function resolveServicesImageSrc(fromCms: string | null | undefined): string {
  if (!fromCms?.trim()) {
    return FALLBACK_IMAGE;
  }
  const raw = fromCms.trim();
  if (raw.startsWith("http://") || raw.startsWith("https://")) {
    return raw;
  }
  if (raw.startsWith("/uploads/") || raw.startsWith("uploads/")) {
    const normalized = raw.startsWith("/") ? raw : `/${raw}`;
    return getStrapiImageUrl(normalized) || FALLBACK_IMAGE;
  }
  return raw;
}

const STATIC_SERVICES: ServiceItem[] = [
  {
    title: "Interior Design",
    description:
      "We design to elevate your lifestyle. Our architectural experts work closely with you to make your dream space a reality.",
  },
  {
    title: "Building Finishes",
    description:
      "We are on a mission to design cohesive and effective interiors where every corner will lift your spirit.",
  },
  {
    title: "Renovation",
    description:
      "Breathe in nature's modernity with our landscape designs. We aim to revitalize your outdoors, which blends in with your lifestyle.",
  },
  {
    title: "Interior Technical Support",
    description:
      "Our plumbing and electrical service will increase your living experience with flexibility. We handle each work with precision by professionals.",
  },
  {
    title: "Supervision",
    description:
      "Get your interior constructed with a well-researched plan, effective and innovative design, and connection to nature.",
  },
];

const cardClass =
  "p-6 xl:p-8 2xl:p-16 min-h-[240px] xl:min-h-[320px] flex flex-col justify-center";

const getCardBgClass = (index: number) =>
  index % 2 === 0 ? "bg-[#FAFAFA]" : "bg-[#EFEFEF]";

const cardClassFor = (service: ServiceItem, index: number) =>
  service.boxColor ? cardClass : `${cardClass} ${getCardBgClass(index)}`;

const cardStyleFor = (service: ServiceItem) =>
  service.boxColor ? { backgroundColor: service.boxColor } : undefined;

export interface DesignoServicesProps {
  servicesTitle?: string;
  servicesImageUrl?: string | null;
  services?: ServiceItem[];
}

const DesignoServices = ({
  servicesTitle,
  servicesImageUrl,
  services,
}: DesignoServicesProps) => {
  const list =
    services && services.length > 0 ? services : STATIC_SERVICES;
  const imageSrc = resolveServicesImageSrc(servicesImageUrl);
  const imageIsRemote =
    imageSrc.startsWith("http://") || imageSrc.startsWith("https://");
  const sectionTitle = servicesTitle || "Designo Services";
  const imageAlt = sectionTitle;

  const h3Mobile =
    "font-creato text-3xl font-medium uppercase leading-none text-[#28241E]";
  const h3Desktop =
    "font-creato lg:text-[30px] xl:text-[33px] 2xl:text-[36px] font-medium uppercase leading-tight tracking-wide text-[#28241E] whitespace-pre-line";
  const bodyMobile = "mt-4 max-w-[50ch] text-base leading-relaxed text-[#333333]";
  const bodyDesktop =
    "mt-4 max-w-[40ch] text-[17px] leading-relaxed text-[#333333]";

  const d = (i: number) => list[i];

  /** Strapi can store markup (e.g. `<br />`, `<span>`). Only use trusted CMS content. */
  const renderTitleHtml = (html: string) => ({
    __html: html || "",
  });

  return (
    <section className="w-full">
      <div className="text-center pb-28">
        <Title text={sectionTitle} />
      </div>
      <div className="mx-auto w-full">
        {/* mobile view */}
        <div className="lg:hidden">
          <div className="relative h-[260px] sm:h-[340px]">
            <Image
              src={imageSrc}
              alt={imageAlt}
              fill
              className="object-cover"
              sizes="100vw"
              priority={false}
              unoptimized={imageIsRemote}
            />
          </div>

          <div className="grid grid-cols-1">
            {list.map((service, index) => (
              <article
                key={`designo-service-mobile-${index}`}
                className={cardClassFor(service, index)}
                style={cardStyleFor(service)}
              >
                <h3
                  className={`${h3Mobile} [&_br]:block`}
                  dangerouslySetInnerHTML={renderTitleHtml(service.title)}
                />
                <p className={bodyMobile}>{service.description}</p>
              </article>
            ))}
          </div>
        </div>

        {/* desktop view — matches 3×3 grid: card | image span 2×2 | … */}
        <div className="hidden lg:grid lg:grid-cols-3 lg:grid-rows-3">
          {d(0) && (
            <article
              className={cardClassFor(d(0)!, 0)}
              style={cardStyleFor(d(0)!)}
            >
              <h3
                className={`${h3Desktop} [&_br]:block`}
                dangerouslySetInnerHTML={renderTitleHtml(d(0)!.title)}
              />
              <p className={bodyDesktop}>{d(0)!.description}</p>
            </article>
          )}

          <div className="relative col-span-2 row-span-2 min-h-[560px]">
            <Image
              src={imageSrc}
              alt={imageAlt}
              fill
              className="object-cover object-bottom"
              sizes="(min-width: 1024px) 70vw, 100vw"
              unoptimized={imageIsRemote}
            />
          </div>

          {[1, 2, 3, 4].map((i) => {
            const service = d(i);
            if (!service) return null;
            return (
              <article
                key={`designo-service-desktop-${i}`}
                className={cardClassFor(service, i)}
                style={cardStyleFor(service)}
              >
                <h3
                  className={`${h3Desktop} [&_br]:block`}
                  dangerouslySetInnerHTML={renderTitleHtml(service.title)}
                />
                <p className={bodyDesktop}>{service.description}</p>
              </article>
            );
          })}
        </div>
      </div>
    </section>
  );
};

export default DesignoServices;
