"use client";

import Link from "next/link";
import { useEffect, useRef, useState } from "react";

export type HeroButton = {
  label: string;
  href: string;
  variant: "primary" | "secondary";
};

export type HeroProps = {
  title: string;
  titleBold?: string;
  description: string;
  buttons: HeroButton[];
  desktopImage?: string;
  tabletImage?: string;
  mobileImage?: string;
  desktopImageAlt?: string;
  mobileImageAlt?: string;
};

function IconArrowPrimary() {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 36 36" fill="none">
      <path
        className="fill-[#053F31] group-hover:fill-[#F7FAF8] transition-colors"
        d="M0 18C0 8.05887 8.05887 0 18 0C27.9411 0 36 8.05887 36 18C36 27.9411 27.9411 36 18 36C8.05887 36 0 27.9411 0 18Z"
      />
      <path
        className="stroke-[#DAE6DC] group-hover:stroke-[#053F31] transition-colors"
        d="M10 18H25.5M25.5 18L19.5 12M25.5 18L19.5 24.5"
        strokeWidth="2"
      />
    </svg>
  );
}

function IconArrowSecondary() {
  return (
    <svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 36 36" fill="none">
      <path
        className="fill-[#F7FAF8] group-hover:fill-[#053F31] transition-colors"
        d="M0 18C0 8.05887 8.05887 0 18 0C27.9411 0 36 8.05887 36 18C36 27.9411 27.9411 36 18 36C8.05887 36 0 27.9411 0 18Z"
      />
      <path
        className="stroke-[#053F31] group-hover:stroke-[#DAE6DC] transition-colors"
        d="M10 18H25.5M25.5 18L19.5 12M25.5 18L19.5 24.5"
        strokeWidth="2"
      />
    </svg>
  );
}

export default function Hero({
  title,
  titleBold,
  description,
  buttons,
  desktopImage,
  tabletImage,
  mobileImage,
  desktopImageAlt,
  mobileImageAlt,
}: HeroProps) {
  const contentRef = useRef<HTMLDivElement>(null);
  const bgImageRef = useRef<HTMLImageElement>(null);
  const [inView, setInView] = useState(false);
  const [bgLoaded, setBgLoaded] = useState(false);

  const d = (desktopImage ?? "").trim();
  const t = (tabletImage ?? "").trim();
  const m = (mobileImage ?? "").trim();
  const fallback = d || t || m;
  const desktopSrc = d || fallback;
  const tabletSrc = t || d || fallback;
  const mobileSrc = m || d || fallback;
  const imageAlt =
    (desktopImageAlt ?? "").trim() ||
    (mobileImageAlt ?? "").trim() ||
    "";
  const hasBackground = Boolean(fallback);

  useEffect(() => {
    const el = contentRef.current;
    if (!el) return;
    const obs = new IntersectionObserver(
      ([entry]) => setInView(!!entry.isIntersecting),
      { threshold: 0.12, rootMargin: "0px" }
    );
    obs.observe(el);
    return () => obs.disconnect();
  }, []);

  useEffect(() => {
    setBgLoaded(false);
  }, [desktopSrc, tabletSrc, mobileSrc]);

  useEffect(() => {
    const img = bgImageRef.current;
    if (!img || !hasBackground) return;
    if (img.complete && img.naturalWidth > 0) {
      setBgLoaded(true);
    }
  }, [hasBackground, desktopSrc, tabletSrc, mobileSrc]);

  return (
    <section className="relative w-full overflow-hidden rounded-[12px] sm:rounded-[16px] md:rounded-[20px] md:px-0 min-w-[320px] xl:max-w-[1440px] 2xl:max-w-[1840px] mx-auto">

      <div className="relative w-full mt-[20px] sm:mt-6 md:mt-8 lg:mt-10">

        {hasBackground ? (
          <div className="relative w-full bg-[#053F31]">
            <picture>
              <source media="(max-width: 650px)" srcSet={mobileSrc} />
              <source media="(min-width: 651px) and (max-width: 1023px)" srcSet={tabletSrc} />
              <source media="(min-width: 1024px) and (max-width: 1279px)" srcSet={desktopSrc} />
              <img
                ref={bgImageRef}
                src={desktopSrc}
                alt={imageAlt}
                onLoad={() => setBgLoaded(true)}
                className={`w-full h-auto object-cover object-top transition-opacity duration-300 ${bgLoaded ? "opacity-100" : "opacity-0"}`}
                style={{ verticalAlign: "top" }}
              />
            </picture>
          </div>
        ) : (
          <></>
        )}
        <style dangerouslySetInnerHTML={{
          __html: `
          @keyframes hero-icon-in {
            0%, 100% { opacity: 1; transform: scale(1); }
            50% { opacity: 0.75; transform: scale(0.92); }
          }
          .hero-icon-anim {
            animation: hero-icon-in 1.5s ease-in-out both infinite;
          }
          @keyframes contact-hero-rain-fall {
            0% { transform: translate(-50%, -60%); opacity: 0; }
            10% { opacity: 0.9; }
            90% { opacity: 0.9; }
            100% { transform: translate(-50%, 40%); opacity: 0; }
        }
        .contact-hero-rain-lines {
          animation: contact-hero-rain-fall 3.5s ease-in infinite;
        }
        .hero-text-slide { opacity: 0; }
        .hero-text-in .hero-text-slide {
          animation: hero-slide-down 0.55s ease-out forwards;
        }
        @keyframes hero-slide-down {
          from { opacity: 0; transform: translateY(-22px); }
          to { opacity: 1; transform: translateY(0); }
        }
        `}} />

        {hasBackground && (
        <div className="absolute inset-0 pointer-events-none md:hidden" aria-hidden>
          <div className="hero-icon-anim absolute flex items-center justify-center" style={{ left: "16%", top: "9%", animationDelay: "0.1s" }}>
            <img src="/tree.png" alt="biomket" className="w-10 h-10" />
          </div>
          <div className="hero-icon-anim absolute flex items-center justify-center" style={{ right: "17%", top: "4%", animationDelay: "0.15s" }}>
            <img src="/truck.png" alt="biomket" className="w-10 h-10" />
          </div>
          <div className="hero-icon-anim absolute flex items-center justify-center" style={{ left: "16%", bottom: "10%", animationDelay: "0.25s" }}>
            <img src="/boat.png" alt="biomket" className="w-10 h-10" />
          </div>
          <div className="hero-icon-anim absolute flex items-center justify-center" style={{ right: "16%", bottom: "3%", animationDelay: "0.3s" }}>
            <img src="/bin.png" alt="biomket" className="w-10 h-10" />
          </div>
          <div
            className="contact-hero-rain-lines absolute left-1/2 bottom-0 pointer-events-none flex items-end justify-center gap-14"
            style={{ height: "35%" }}
            aria-hidden
          >
            <img src="/line1.png" alt="biomket" style={{ transform: "translateY(40%)" }} />
            <img src="/line2.png" alt="biomket" style={{ transform: "translateY(15%)" }} />
            <img src="/line3.png" alt="biomket" style={{ transform: "translateY(-12%)" }} />
          </div>
        </div>
        )}

        {hasBackground && (
        <div className="absolute inset-0 pointer-events-none hidden md:block" aria-hidden>
          <div className="hero-icon-anim absolute flex items-center justify-center" style={{ left: "4%", top: "14%", animationDelay: "0.1s" }}>
            <img src="/tree.png" alt="biomket" />
          </div>
          <div className="hero-icon-anim absolute flex items-center justify-center" style={{ left: "14%", top: "35%", animationDelay: "0.2s" }}>
            <img src="/notes.png" alt="biomket" />
          </div>
          <div className="hero-icon-anim absolute flex items-center justify-center" style={{ left: "6%", top: "80%", animationDelay: "0.3s" }}>
            <img src="/boat.png" alt="biomket" />
          </div>
          <div className="hero-icon-anim absolute flex items-center justify-center" style={{ right: "10%", top: "7%", animationDelay: "0.15s" }}>
            <img src="/truck.png" alt="biomket" />
          </div>
          <div className="hero-icon-anim absolute flex items-center justify-center" style={{ right: "18%", top: "28%", animationDelay: "0.25s" }}>
            <img src="/cart.png" alt="biomket" />
          </div>
          <div className="hero-icon-anim absolute flex items-center justify-center" style={{ right: "2%", top: "44%", animationDelay: "0.35s" }}>
            <img src="/gear.png" alt="biomket" />
          </div>
          <div className="hero-icon-anim absolute flex items-center justify-center" style={{ right: "22%", top: "77%", animationDelay: "0.4s" }}>
            <img src="/recycle.png" alt="biomket" />
          </div>
          <div className="hero-icon-anim absolute flex items-center justify-center" style={{ right: "6%", top: "70%", animationDelay: "0.45s" }}>
            <img src="/bin.png" alt="biomket" />
          </div>
          <div
            className="contact-hero-rain-lines absolute left-1/2 bottom-0 pointer-events-none flex items-end justify-center 2xl:gap-14 gap-10"
            style={{ height: "35%" }}
            aria-hidden
          >
            <img src="/line1.png" alt="biomket" style={{ transform: "translateY(40%)" }} />
            <img src="/line2.png" alt="biomket" style={{ transform: "translateY(15%)" }} />
            <img src="/line3.png" alt="biomket" style={{ transform: "translateY(-12%)" }} />
          </div>
        </div>
        )}

        <div
          ref={contentRef}
          className={`absolute inset-0 flex flex-col items-center justify-center px-4 sm:px-6 md:px-8 lg:px-12 xl:px-16 2xl:px-20 py-12 sm:py-16 md:py-20 lg:py-24 text-center ${inView ? "hero-text-in" : ""}`}
        >

        <h1 className="hero-text-slide mb-4 sm:text-[33px]! lg:text-[60px]! sm:mb-5 md:mb-6 font-extralight tracking-wide text-white max-w-full sm:max-w-[500px] md:max-w-[600px] lg:max-w-[700px] xl:max-w-[800px]" style={{ animationDelay: "0s" }}>
            {(() => {
              const allWords = `${title ?? ""} ${titleBold ?? ""}`.trim().split(/\s+/).filter(Boolean);
              const lightText = allWords.slice(0, 3).join(" ");
              const mediumText = allWords.slice(3).join(" ");
              return (
                <>
                  {lightText}
                  {mediumText ? <span className="font-medium"> {" "}{mediumText}</span> : null}
                </>
              );
            })()}
          </h1>

          <p className="hero-text-slide sm:text-[14px]! lg:text-[18px]! mb-6 sm:mb-7 md:mb-8 font-light font-outfit leading-relaxed text-[#DAE6DC] max-w-full sm:max-w-[400px] md:max-w-[600px] lg:max-w-[700px] xl:max-w-[800px]" style={{ animationDelay: "0.1s" }}>
            {description}
          </p>

          <div className="hero-text-slide flex flex-col sm:flex-row gap-3 sm:gap-4" style={{ animationDelay: "0.2s" }}>
            {buttons
              .filter((btn) => Boolean((btn.label ?? "").trim()))
              .map((btn, index) => (
              <Link
                key={`${btn.label || "btn"}-${btn.href || "#"}-${index}`}
                href={btn.href}
                className={
                  btn.variant === "primary"
                    ? "group flex items-center justify-center gap-2 mx-auto bg-[#DAE6DC] text-[#053F31] p-[7px_7px_7px_15px] rounded-full font-semibold cursor-pointer border-2 border-[#DAE6DC] hover:bg-[#DAE6DC]/10 hover:text-white hover:backdrop-blur-sm transition"
                    : "group flex items-center justify-center gap-2 border-2 text-[#DAE6DC] border-[#DAE6DC] bg-white/10 backdrop-blur-sm p-[7px_7px_7px_15px] rounded-full font-semibold cursor-pointer hover:bg-[#DAE6DC] hover:text-[#053F31] transition"
                }
              >
                {btn.label}
                {btn.variant === "primary" ? <IconArrowPrimary /> : <IconArrowSecondary />}
              </Link>
            ))}
          </div>

        </div>
      </div>
    </section>
  );
}
