import Image from "next/image";
import type { CardsBlock, Package, Inclusion, ExpectItem } from "@/types";

interface Props {
  data: CardsBlock;
}

function getTextContent(value?: string): string {
  return typeof value === "string" ? value : "";
}

function renderSplitTitle(
  title?: string,
  mode: "on" | "ampersand" | "default" = "default",
) {
  const safeTitle = getTextContent(title).trim();
  if (!safeTitle) return null;

  if (mode === "ampersand" && safeTitle.includes("&")) {
    const parts = safeTitle.split("&");
    return (
      <>
        <span className="block whitespace-nowrap">{parts[0]?.trim()}</span>
        <span className="block whitespace-nowrap">& {parts[1]?.trim()}</span>
      </>
    );
  }

  if (mode === "on") {
    const words = safeTitle.split(" ");
    const onIndex = words.findIndex((w) => w.toLowerCase() === "on");

    if (onIndex !== -1) {
      return (
        <>
          <span className="block">{words.slice(0, onIndex + 1).join(" ")}</span>
          <span className="block">{words.slice(onIndex + 1).join(" ")}</span>
        </>
      );
    }

    return (
      <>
        {words.map((word, i) => (
          <span key={i} className="block">
            {word}
          </span>
        ))}
      </>
    );
  }

  const words = safeTitle.split(" ");
  if (words.length === 1) {
    return <span className="block whitespace-nowrap">{words[0]}</span>;
  }

  return (
    <>
      <span className="block whitespace-nowrap">{words[0]}</span>
      <span className="block whitespace-nowrap">
        {words.slice(1).join(" ")}
      </span>
    </>
  );
}

export default function CardSection({ data }: Props) {
  const titleBlock = data?.titleBlock;
  const packages = Array.isArray(data?.packages) ? data.packages : [];
  const inclusions = Array.isArray(data?.inclusions) ? data.inclusions : [];
  const expectItems = Array.isArray(data?.expectItems) ? data.expectItems : [];

  const hasTitleBlock =
    titleBlock?.icon ||
    getTextContent(titleBlock?.heading) ||
    getTextContent(titleBlock?.subText);

  const hasInclusionsTitle =
    data?.inclusionsTitle?.icon ||
    getTextContent(data?.inclusionsTitle?.heading);

  const hasExpectTitle =
    data?.expectTitle?.icon || getTextContent(data?.expectTitle?.heading);

  return (
    <div id="card-section" className=" px-[15px] md:px-0">
      {hasTitleBlock && (
        <div className="relative text-center mb-[40px]">
          {titleBlock?.icon ? (
            <Image
              src={titleBlock.icon}
              alt="icon"
              width={64}
              height={64}
              className="mx-auto mb-2"
              style={{ width: "auto", height: "auto" }}
            />
          ) : null}

          <div className="h-5" />

          {titleBlock?.heading ? (
            <h2 className="uppercase text-[30px] lg:text-[36px] leading-[46px] font-[700] text-[#85714D] text-center mt-0 mb-[25px]">
              {titleBlock.heading}
            </h2>
          ) : null}

          {(titleBlock?.heading || titleBlock?.subText) && (
            <span className="line block w-[70px] h-[4px] bg-[#85714D] mx-auto my-[15px] mb-[44px]" />
          )}

          {titleBlock?.subText ? (
            <p className="text-[16px] lg:text-[20px] font-normal text-[#000000] mb-[25px]">
              {titleBlock.subText}
            </p>
          ) : null}
        </div>
      )}

      {packages.length > 0 && (
        <div className="h-auto">
          <div
            className="grid grid-cols-1 min-[992px]:[grid-template-columns:repeat(var(--expect-cols),minmax(0,1fr))] gap-[10px] min-[992px]:gap-[40px] w-full max-w-[720px] min-[992px]:max-w-[1024px] mx-auto"
            style={
              {
                "--expect-cols": packages.length,
              } as React.CSSProperties
            }
          >
            {packages.map((pkg: Package, idx: number) => (
              <div
                key={pkg.title || idx}
                className="relative overflow-hidden w-full max-w-[720px] mx-auto h-[400px] lg:h-[380px] lg:max-w-none"
              >
                {pkg?.image && (
                  <Image
                    src={pkg.image}
                    alt={pkg.title ?? ""}
                    fill
                    className="object-cover object-center"
                    sizes="(max-width: 992px) 720px, 33vw"
                    loading="lazy"
                  />
                )}
                <div className="absolute bottom-0 w-full p-[15px] text-center">
                  {pkg?.icon ? (
                    <Image
                      src={pkg.icon}
                      width={52}
                      height={52}
                      className="mx-auto mb-[10px]"
                      alt="icon"
                      style={{ width: "auto", height: "auto" }}
                    />
                  ) : null}

                  {pkg?.title ? (
                    <h3 className="text-white text-center text-[16px] lg:text-[24px] font-bold leading-[25px] mt-0 mb-[4px]">
                      {pkg.title}
                    </h3>
                  ) : null}

                  {pkg?.nights ? (
                    <p className="text-white text-center text-[13px] lg:text-[16px] leading-[24px]">
                      <strong className="font-bold">{pkg.nights}</strong>
                    </p>
                  ) : null}

                  {(pkg?.price || pkg?.subtitle) && (
                    <div className="mt-2 font-light">
                      {pkg?.price ? (
                        <p className="main text-[#c19c64] text-[28px] font-bold uppercase leading-[25px] py-[15px] pb-[8px] text-center whitespace-nowrap">
                          {pkg.price}
                        </p>
                      ) : null}

                      {pkg?.subtitle ? (
                        <p className="text-white/90 text-center text-[13px] lg:text-[16px] font-light leading-[25px] mb-0 uppercase tracking-[2px]">
                          {pkg.subtitle}
                        </p>
                      ) : null}
                    </div>
                  )}

                  <div className="py-[12px]" />

                  {pkg?.description ? (
                    <p
                      className="text-white/80 text-center text-[13px] lg:text-[16px] font-extralight leading-[21px] [&_strong]:text-white [&_strong]:font-bold [&_b]:text-white [&_b]:font-bold [&_em]:italic"
                      dangerouslySetInnerHTML={{ __html: pkg.description }}
                    />
                  ) : null}
                </div>
              </div>
            ))}
          </div>
        </div>
      )}

      {(hasInclusionsTitle || inclusions.length > 0) && (
        <>
          {hasInclusionsTitle && (
            <div className="text-center mb-[20px] pt-10">
              {data?.inclusionsTitle?.icon ? (
                <Image
                  src={data.inclusionsTitle.icon}
                  alt="icon"
                  width={86}
                  height={86}
                  className="block mx-auto align-middle border-0"
                />
              ) : null}
              <div className="h-[20px]" />
              {data?.inclusionsTitle?.heading ? (
                <h3 className="uppercase text-[28px] leading-[34px] font-bold mt-0 mb-[10px] text-center text-[#85714D]">
                  {data.inclusionsTitle.heading}
                </h3>
              ) : null}
            </div>
          )}

          {inclusions.length > 0 && (
            <div className="h-auto mb-[10px] lg:mb-[40px]">
              <div
                className="grid grid-cols-1 min-[992px]:[grid-template-columns:repeat(var(--expect-cols),minmax(0,1fr))] gap-[10px] min-[992px]:gap-[40px] w-full max-w-[720px] min-[992px]:max-w-[1024px] mx-auto"
                style={
                  {
                    "--expect-cols": inclusions.length,
                  } as React.CSSProperties
                }
              >
                {inclusions.map((inc: Inclusion, idx: number) => (
                  <div
                    key={inc.title || idx}
                    className="relative overflow-hidden w-full max-w-[720px] mx-auto h-[400px] min-[943px]:h-[380px] min-[943px]:max-w-none"
                  >
                    {inc?.image && (
                      <Image
                        src={inc.image}
                        alt={inc.title ?? ""}
                        fill
                        className="object-cover object-center"
                        sizes="(max-width: 943px) 720px, 33vw"
                        loading="lazy"
                      />
                    )}
                    <div className="absolute bottom-0 w-full h-[254px] box-border p-[15px] text-center">
                      {inc?.icon ? (
                        <Image
                          src={inc.icon}
                          width={52}
                          height={52}
                          className="mx-auto mb-[20px]"
                          alt="icon"
                          style={{ width: "auto", height: "auto" }}
                        />
                      ) : null}

                      {inc?.title ? (
                        <h3 className="text-white text-center text-[16px] lg:text-[24px] leading-[25px] font-bold mt-0 mb-[4px]">
                          <span className="block min-[943px]:hidden">
                            {inc.title}
                          </span>
                          <span className="hidden min-[943px]:block">
                            {renderSplitTitle(inc.title, "on")}
                          </span>
                        </h3>
                      ) : null}

                      <div className="flex flex-col items-center">
                        {inc?.description ? (
                          <div
                            className="text-white text-center text-[13px] lg:text-[16px] !font-[300] leading-[18px] lg:leading-[21px] mb-[20px] max-w-[240px] min-[943px]:max-w-[260px] mx-auto [&_strong]:text-white [&_strong]:font-bold [&_b]:text-white [&_b]:font-bold [&_em]:italic"
                            dangerouslySetInnerHTML={{
                              __html: inc.description,
                            }}
                          />
                        ) : null}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </>
      )}

      {(hasExpectTitle || expectItems.length > 0 || data?.cta) && (
        <div className="bg-[#efe9de] w-screen relative left-1/2 right-1/2 -ml-[50vw] -mr-[50vw] py-6 overflow-hidden">
          {hasExpectTitle && (
            <div className="text-center mb-[40px] pt-10">
              {data?.expectTitle?.icon ? (
                <Image
                  src={data.expectTitle.icon}
                  alt="icon"
                  width={86}
                  height={86}
                  className="block mx-auto align-middle border-0"
                />
              ) : null}
              <div className="h-[20px]" />
              {data?.expectTitle?.heading ? (
                <h3 className="uppercase text-[28px] leading-[41px] font-bold mt-0 mb-[10px] text-center text-[#85714D]">
                  {data.expectTitle.heading}
                </h3>
              ) : null}
            </div>
          )}

          {expectItems.length > 0 && (
            <div className="w-full sm:px-[15px]">
              <div
                className="grid grid-cols-1 min-[992px]:[grid-template-columns:repeat(var(--expect-cols),minmax(282px,282px))] gap-[10px] min-[992px]:gap-[10px] w-full px-[16px] max-w-[1440px] mx-auto justify-items-center"
                style={
                  {
                    "--expect-cols": expectItems.length,
                  } as React.CSSProperties
                }
              >
                {expectItems.map((item: ExpectItem, idx: number) => (
                  <div
                    key={item.title || idx}
                    className="relative overflow-hidden w-[400px] sm:w-full sm:max-w-[720px] lg:max-w-none h-[380px] md:h-[380px] lg:h-[380px] min-w-0 mx-auto justify-items-center"
                  >
                    {item?.image && (
                      <Image
                        src={item.image}
                        alt={item.title ?? ""}
                        fill
                        className="object-cover object-center"
                        sizes="(max-width: 992px) 720px, 282px"
                        loading="lazy"
                      />
                    )}
                    <div className="absolute bottom-0 w-full p-[15px] md:p-[18px] lg:p-[20px] text-center">
                      {item?.icon ? (
                        <Image
                          src={item.icon}
                          width={60}
                          height={60}
                          className="mx-auto mb-[16px] md:mb-[18px] lg:mb-[20px]"
                          alt="icon"
                          style={{ width: "auto", height: "auto", maxWidth: "60px" }}
                        />
                      ) : null}

                      {item?.title ? (
                        <h3 className="text-white text-center text-[14px] md:text-[16px] lg:text-[18px] leading-[1.5rem] md:leading-[1.8rem] lg:leading-[2.2rem] font-bold mt-0 mb-[0.4rem] w-full min-w-0">
                          {renderSplitTitle(
                            item.title,
                            item.title.includes("&") ? "ampersand" : "default",
                          )}
                        </h3>
                      ) : null}

                      <div className="flex flex-col items-center">
                        {item?.description ? (
                          <p
                            className="text-white text-center text-[13px] md:text-[13px] lg:text-[14px] font-[300] leading-[18px] md:leading-[19px] lg:leading-[20px] mb-[20px] max-w-[90%] mx-auto opacity-90 [&_strong]:text-white [&_strong]:font-bold [&_b]:text-white [&_b]:font-bold [&_em]:italic"
                            dangerouslySetInnerHTML={{
                              __html: item.description,
                            }}
                          />
                        ) : null}
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}

          {data?.cta && (
            <div className="mb-[60px] text-center">
              {data.cta.headline ? (
                <h4 className="text-[30px] leading-[30px] font-bold uppercase text-[#85714D] mt-[40px] mb-[10px]">
                  {data.cta.headline}
                </h4>
              ) : null}

              {Array.isArray(data.cta.paragraphs) &&
                data.cta.paragraphs.map((para, idx) =>
                  para ? (
                    <p
                      key={idx}
                      className="text-[1.6rem] lg:text-[2rem] mb-[20px] text-black text-center leading-[1.5] font-[400]"
                      dangerouslySetInnerHTML={{ __html: para }}
                    />
                  ) : null,
                )}
            </div>
          )}
        </div>
      )}
    </div>
  );
}
