 "use client";

import Image from "next/image";
import type { HeroBlock, PromoItem } from "@/types";

const splitLabelIntoTwoLines = (title: string, subtitle?: string) => {
  const fullText = [title, subtitle].filter(Boolean).join(" ").trim();
  const words = fullText.split(/\s+/).filter(Boolean);

  if (words.length === 0) return { line1: "", line2: "" };
  if (words.length === 1) return { line1: words[0], line2: "" };
  if (words.length === 2) return { line1: words[0], line2: words[1] };

  let bestDiff = Number.POSITIVE_INFINITY;
  let splitIndex = 1;

  for (let i = 1; i < words.length; i++) {
    const leftChars = words.slice(0, i).join(" ").length;
    const rightChars = words.slice(i).join(" ").length;
    const diff = Math.abs(leftChars - rightChars);
    if (diff <= bestDiff) {
      bestDiff = diff;
      splitIndex = i;
    }
  }

  return {
    line1: words.slice(0, splitIndex).join(" "),
    line2: words.slice(splitIndex).join(" "),
  };
};

interface Props {
  data: HeroBlock;
}

export default function Hero({ data }: Props) {
  const fullHeadline = [data.headline1, data.headline2]
    .filter(Boolean)
    .join(" - ");

  return (
    <section id="hero-banner" className="relative w-full">
      <div className="absolute left-0 top-0 z-20 w-full bg-gradient-to-b from-[#020024]/50 to-transparent pt-[3.4rem] pb-[4rem]">
        <div className="relative z-10 mx-auto flex h-full w-full px-[15px] md:max-w-[750px] lg:max-w-[970px] xl:max-w-[1170px] 2xl:max-w-[1480px]">
          <a href={data.logoHref} className="block max-w-[130px] min-[1366px]:max-w-[200px]">
            {data.logoSrc ? (
              <Image
                src={data.logoSrc}
                alt={data.logoAlt}
                width={200}
                height={60}
                priority
                unoptimized
                className="h-auto w-full object-contain"
              />
            ) : null}
          </a>
        </div>
      </div>

      <div className="relative h-[600px] w-full overflow-hidden lg:h-screen">
        {data.heroImageLandscape ? (
          <Image
            src={data.heroImageLandscape}
            alt={data.headline1 || "Hero"}
            fill
            priority
            unoptimized
            quality={90}
            className="absolute inset-0 h-full w-full object-cover"
            sizes="100vw"
          />
        ) : (
          <div className="absolute inset-0 bg-black" />
        )}

        <div className="absolute inset-0" />

        <div className="absolute bottom-0 left-0 right-0 z-20 bg-gradient-to-t from-[#020024]/90 to-transparent pt-[40px] pb-[25px] md:pt-[5rem] md:pb-[61px]">
          <div className="mx-auto w-full px-[15px] md:max-w-[750px] lg:max-w-[970px] xl:max-w-[1170px] 2xl:max-w-[1480px]">
            <div className="flex flex-col gap-8 text-white lg:flex-row lg:items-end lg:justify-between">
              <div className="w-full lg:w-[70%] xl:w-[75%]">
                <h1 className="relative m-0 max-w-[32ch] p-0 text-[24px] font-bold leading-tight text-white md:max-w-[44rem] md:leading-[1.1] md:text-[clamp(2rem,4vw,3.5rem)]">
                  <span className="block md:hidden max-w-[30ch]">{fullHeadline}</span>
                  <span className="hidden md:block lg:whitespace-nowrap">{data.headline1}</span>
                  {data.headline2 ? (
                    <span className="hidden md:block lg:whitespace-nowrap">
                      {data.headline2}
                    </span>
                  ) : null}
                </h1>

                <div className="relative mt-4 flex flex-wrap items-center gap-y-3 pt-5 md:mt-[26px] md:pt-[30px]">
                  <span className="absolute left-0 top-0 h-[3px] w-[52px] bg-white" />
                  <div className="mt-5 grid grid-cols-2 gap-x-6 gap-y-5 md:mt-8 md:flex md:flex-wrap md:gap-x-6 md:gap-y-5 xl:flex-nowrap xl:items-center xl:gap-x-0">
                    {data.promoItems.map((item: PromoItem, idx: number) => {
                      const { line1, line2 } = splitLabelIntoTwoLines(
                        item.title,
                        item.subtitle,
                      );
                      const normalizedLabel = [item.title, item.subtitle]
                        .filter(Boolean)
                        .join(" ")
                        .replace(/\s+/g, " ")
                        .trim()
                        .toLowerCase();
                      const isHiddenBeaches =
                        normalizedLabel === "hidden beaches & coastal walks";
                      const mobileLines = isHiddenBeaches
                        ? ["Hidden", "Beaches", "& Coastal", "Walks"]
                        : [
                            ...line1
                              .replace(/-/g, " ")
                              .split(/\s+/)
                              .filter(Boolean),
                            ...line2
                              .replace(/-/g, " ")
                              .split(/\s+/)
                              .filter(Boolean),
                          ];
                      const isLast = idx === data.promoItems.length - 1;
                      return (
                        <div
                          key={idx}
                          className={`flex items-center p-[8px] md:p-0 ${
                            isLast
                              ? "col-span-2 justify-self-start md:col-span-1 md:justify-self-auto"
                              : ""
                          }`}
                        >
                          <div className="flex min-w-0 items-center">
                            {item.iconSrc ? (
                              <Image
                                src={item.iconSrc}
                                alt={line1 || item.title}
                                width={42}
                                height={38}
                                unoptimized
                                className="mr-[16px] h-[34px] w-[34px] shrink-0 object-contain opacity-95 md:h-[38px] md:w-[42px]"
                              />
                            ) : null}
                            <p className="m-0 text-left font-normal leading-tight text-white text-[13px] lg:text-[19px]">
                              <span className="block md:hidden">
                                {mobileLines.map((word, i) => (
                                  <span key={`m-${idx}-${i}`} className="block">
                                    {word}
                                  </span>
                                ))}
                              </span>
                              <span className="hidden md:block">
                                <span className="block">{line1}</span>
                                {line2 ? <span className="block">{line2}</span> : null}
                              </span>
                            </p>
                          </div>
                          {idx !== data.promoItems.length - 1 ? (
                            <span
                              aria-hidden="true"
                              className="mx-[20px] hidden h-[34px] w-px shrink-0 bg-white/30 xl:inline-block"
                            />
                          ) : null}
                        </div>
                      );
                    })}
                  </div>
                </div>
              </div>

              <div className="relative w-full text-left lg:w-[30%] lg:text-right">
                <div className="inline-block mt-6 lg:mt-0">
                  <a
                    href={data.ctaHref}
                    id={data.ctaId ?? undefined}
                    onClick={(e) => {
                      if (!data.ctaHref?.startsWith("#")) return;
                      const target = document.querySelector(data.ctaHref);
                      if (!target) return;
                      e.preventDefault();
                      const targetY =
                        target.getBoundingClientRect().top + window.scrollY;
                      window.scrollTo({ top: targetY, behavior: "smooth" });
                    }}
                    className="relative inline-flex w-fit items-center whitespace-nowrap font-medium rounded-full border-2 border-white py-[8px] pl-[12px] pr-[8px] text-[clamp(0.95rem,2.2vw,1.75rem)] uppercase text-white transition-all duration-200"
                  >
                    <span className="leading-none">{data.ctaLabel}</span>
                    <span className="ml-[6px] flex h-[clamp(26px,3.2vw,36px)] w-[clamp(26px,3.2vw,36px)] shrink-0 items-center justify-center rounded-full border-[3px] border-white bg-transparent text-white transition-all duration-200">
                      <svg
                        viewBox="0 0 24 24"
                        fill="none"
                        stroke="currentColor"
                        strokeWidth="4"
                        className="block h-[clamp(14px,1.6vw,22px)] w-[clamp(14px,1.6vw,22px)] transition-all duration-250"
                      >
                        <path d="M9 18l6-6-6-6" />
                      </svg>
                    </span>
                  </a>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
