"use client";

import dynamic from "next/dynamic";
import {
  ArrowRight,
  Building2,
  CheckCircle2,
  Home,
  MessageCircle,
  ShieldCheck,
  Sparkles,
  Waves,
} from "lucide-react";
import {
  CSSProperties,
  MutableRefObject,
  useEffect,
  useRef,
  useState,
} from "react";

const LarkShine3DScene = dynamic(
  () => import("./LarkShine3DScene"),
  {
    ssr: false,
    loading: () => null,
  },
);

function clamp(value: number) {
  return Math.min(1, Math.max(0, value));
}

function sectionOpacity(
  progress: number,
  start: number,
  center: number,
  end: number,
) {
  if (progress <= start || progress >= end) return 0;

  if (progress < center) {
    return clamp((progress - start) / (center - start));
  }

  return clamp((end - progress) / (end - center));
}

function GlassScreen({
  children,
  className = "",
  style,
}: {
  children: React.ReactNode;
  className?: string;
  style?: CSSProperties;
}) {
  return (
    <div
      className={`glass-screen ${className}`}
      style={style}
    >
      <div className="glass-screen-highlight" />
      <div className="relative z-10">{children}</div>
    </div>
  );
}

export default function HeroStory() {
  const storyRef = useRef<HTMLElement>(null);
  const progressRef = useRef(0);
  const pointerRef = useRef({ x: 0, y: 0 });

  const [progress, setProgress] = useState(0);
  const [sceneReady, setSceneReady] = useState(false);

  useEffect(() => {
    let frame = 0;

    const updateProgress = () => {
      cancelAnimationFrame(frame);

      frame = requestAnimationFrame(() => {
        const element = storyRef.current;
        if (!element) return;

        const rect = element.getBoundingClientRect();
        const scrollable = Math.max(
          element.offsetHeight - window.innerHeight,
          1,
        );

        const next = clamp(-rect.top / scrollable);

        progressRef.current = next;
        setProgress(next);
      });
    };

    const updatePointer = (event: PointerEvent) => {
      pointerRef.current = {
        x: (event.clientX / window.innerWidth - 0.5) * 2,
        y: (event.clientY / window.innerHeight - 0.5) * 2,
      };
    };

    updateProgress();

    window.addEventListener("scroll", updateProgress, {
      passive: true,
    });
    window.addEventListener("resize", updateProgress);
    window.addEventListener("pointermove", updatePointer, {
      passive: true,
    });

    return () => {
      cancelAnimationFrame(frame);
      window.removeEventListener("scroll", updateProgress);
      window.removeEventListener("resize", updateProgress);
      window.removeEventListener("pointermove", updatePointer);
    };
  }, []);

  const introOpacity = sectionOpacity(
    progress,
    -0.02,
    0.075,
    0.245,
  );

  const servicesOpacity = sectionOpacity(
    progress,
    0.18,
    0.36,
    0.53,
  );

  const transformationOpacity = sectionOpacity(
    progress,
    0.47,
    0.615,
    0.76,
  );

  const trustOpacity = sectionOpacity(
    progress,
    0.69,
    0.805,
    0.91,
  );

  const contactOpacity = clamp(
    (progress - 0.84) / 0.12,
  );

  return (
    <section
      ref={storyRef}
      id="home"
      className="relative h-[460vh] bg-[#06141c]"
    >
      <div className="sticky top-0 h-screen overflow-hidden">
        {/* Background atmosphere */}
        <div
          aria-hidden="true"
          className="absolute inset-0 bg-[radial-gradient(circle_at_50%_40%,#12394a_0%,#092430_33%,#06141c_68%,#040e14_100%)]"
        />

        <div
          aria-hidden="true"
          className="absolute inset-0 opacity-60"
          style={{
            background:
              "radial-gradient(circle at 17% 20%, rgba(35,190,235,.18), transparent 28%), radial-gradient(circle at 82% 73%, rgba(59,201,237,.13), transparent 32%)",
          }}
        />

        <div
          aria-hidden="true"
          className="absolute inset-0 cinematic-grid"
        />

        {/* Full persistent 3D canvas */}
        <div className="absolute inset-0 z-[2]">
          <LarkShine3DScene
            progressRef={
              progressRef as MutableRefObject<number>
            }
            pointerRef={pointerRef}
            setReady={setSceneReady}
          />
        </div>

        {/* Loading veil */}
        <div
          className="pointer-events-none absolute inset-0 z-[70] flex items-center justify-center bg-[#06141c] transition-opacity duration-1000"
          style={{
            opacity: sceneReady ? 0 : 1,
            visibility: sceneReady ? "hidden" : "visible",
          }}
        >
          <div className="flex flex-col items-center gap-5">
            <div className="relative h-16 w-16">
              <span className="absolute inset-0 rounded-full border border-[#6edcff]/15" />
              <span className="absolute inset-1 animate-spin rounded-full border-2 border-transparent border-t-[#6edcff]" />
              <span className="absolute inset-[18px] rounded-full bg-[#5bd5f5] shadow-[0_0_24px_rgba(91,213,245,.8)]" />
            </div>

            <span className="text-xs font-semibold uppercase tracking-[0.34em] text-white/55">
              Preparing the shine
            </span>
          </div>
        </div>

        {/* Navigation-safe top gradient */}
        <div className="pointer-events-none absolute inset-x-0 top-0 z-[5] h-40 bg-gradient-to-b from-[#041017]/90 to-transparent" />

        {/* Scene 1: Hero */}
        <div
          className="pointer-events-none absolute inset-0 z-10"
          style={{
            opacity: introOpacity,
            transform: `translate3d(0, ${
              progress * -42
            }px, 0)`,
          }}
        >
          <div className="shell flex h-full items-center">
            <div className="w-full">
              <div className="max-w-[620px]">
                <div className="mb-6 inline-flex items-center gap-2 rounded-full border border-white/15 bg-white/[0.07] px-4 py-2 text-xs font-semibold uppercase tracking-[0.18em] text-[#aeeeff] shadow-[0_12px_50px_rgba(0,0,0,.16)] backdrop-blur-xl">
                  <Sparkles size={15} />
                  Lark Shine Cleaning Services
                </div>

                <h1 className="text-[clamp(3.8rem,7.2vw,7.7rem)] font-semibold leading-[0.88] tracking-[-0.068em] text-white">
                  Beyond
                  <span className="block bg-gradient-to-r from-[#aeeeff] via-[#4dd4f5] to-[#149bd8] bg-clip-text text-transparent">
                    clean.
                  </span>
                  Built to shine.
                </h1>

                <p className="mt-7 max-w-[540px] text-base leading-8 text-white/62 md:text-lg">
                  A new generation of professional cleaning for
                  homes, offices and properties across the UAE.
                </p>

                <div className="pointer-events-auto mt-9 flex flex-wrap gap-4">
                  <a
                    href="#contact"
                    className="group inline-flex items-center gap-3 rounded-full bg-white px-6 py-3.5 text-sm font-bold text-[#0a2633] shadow-[0_18px_70px_rgba(47,206,246,.2)] transition hover:-translate-y-0.5 hover:shadow-[0_22px_80px_rgba(47,206,246,.34)]"
                  >
                    Request a quote
                    <ArrowRight
                      size={17}
                      className="transition-transform group-hover:translate-x-1"
                    />
                  </a>

                  <a
                    href="https://wa.me/971555822480"
                    target="_blank"
                    rel="noreferrer"
                    className="inline-flex items-center gap-3 rounded-full border border-white/16 bg-white/[0.07] px-6 py-3.5 text-sm font-bold text-white backdrop-blur-xl transition hover:bg-white/[0.13]"
                  >
                    <MessageCircle size={17} />
                    WhatsApp
                  </a>
                </div>
              </div>

              <div className="absolute bottom-10 left-1/2 -translate-x-1/2 text-center">
                <span className="block text-[10px] font-semibold uppercase tracking-[0.34em] text-white/38">
                  Scroll to explore
                </span>

                <span className="mx-auto mt-3 block h-12 w-px bg-gradient-to-b from-[#72ddfa] to-transparent" />
              </div>
            </div>
          </div>
        </div>

        {/* Scene 2: Services */}
        <div
          className="pointer-events-none absolute inset-0 z-20"
          style={{
            opacity: servicesOpacity,
          }}
        >
          <div className="shell relative h-full">
            <div className="absolute left-0 top-[16%] max-w-[430px]">
              <GlassScreen
                className="rotate-[-1.4deg]"
                style={{
                  transform: `translate3d(${
                    (1 - servicesOpacity) * -55
                  }px, 0, 0) rotate(-1.4deg)`,
                }}
              >
                <span className="text-[10px] font-semibold uppercase tracking-[0.3em] text-[#82dffc]">
                  One system. Complete care.
                </span>

                <h2 className="mt-4 text-4xl font-semibold tracking-[-0.045em] text-white md:text-5xl">
                  Cleaning built around your space.
                </h2>

                <p className="mt-5 text-sm leading-7 text-white/58 md:text-base">
                  Every service is delivered with professional
                  equipment, trained specialists and careful
                  attention to detail.
                </p>
              </GlassScreen>
            </div>

            <div className="absolute bottom-[12%] right-0 grid w-[min(640px,52vw)] grid-cols-2 gap-3">
              {[
                {
                  icon: Home,
                  title: "Residential",
                  text: "Homes, villas and apartments",
                },
                {
                  icon: Building2,
                  title: "Commercial",
                  text: "Offices and business properties",
                },
                {
                  icon: Waves,
                  title: "Deep Cleaning",
                  text: "Detailed surface and floor care",
                },
                {
                  icon: Sparkles,
                  title: "Glass & Interior",
                  text: "Clear finishes and polished spaces",
                },
              ].map((service, index) => {
                const Icon = service.icon;

                return (
                  <GlassScreen
                    key={service.title}
                    className="min-h-[132px] !rounded-[24px] !p-5"
                    style={{
                      transform: `translate3d(0, ${
                        (1 - servicesOpacity) *
                        (40 + index * 9)
                      }px, 0) rotate(${
                        index % 2 === 0 ? "-0.6deg" : "0.6deg"
                      })`,
                    }}
                  >
                    <Icon
                      size={21}
                      className="text-[#6ee0fb]"
                    />

                    <h3 className="mt-4 text-lg font-semibold text-white">
                      {service.title}
                    </h3>

                    <p className="mt-1.5 text-xs leading-5 text-white/48">
                      {service.text}
                    </p>
                  </GlassScreen>
                );
              })}
            </div>
          </div>
        </div>

        {/* Scene 3: Transformation */}
        <div
          className="pointer-events-none absolute inset-0 z-30"
          style={{
            opacity: transformationOpacity,
          }}
        >
          <div className="shell flex h-full items-center justify-end">
            <GlassScreen
              className="w-full max-w-[520px]"
              style={{
                transform: `translate3d(${
                  (1 - transformationOpacity) * 70
                }px, 0, 0) rotate(1.2deg)`,
              }}
            >
              <span className="text-[10px] font-semibold uppercase tracking-[0.3em] text-[#82dffc]">
                The Lark Shine standard
              </span>

              <h2 className="mt-4 text-4xl font-semibold tracking-[-0.05em] text-white md:text-6xl">
                From overlooked
                <span className="block text-[#65dcf8]">
                  to immaculate.
                </span>
              </h2>

              <p className="mt-6 text-base leading-8 text-white/58">
                We combine specialist tools, proven methods and a
                careful human touch to restore clarity, freshness
                and comfort throughout your property.
              </p>

              <div className="mt-7 grid grid-cols-3 gap-3">
                {[
                  ["01", "Inspect"],
                  ["02", "Restore"],
                  ["03", "Shine"],
                ].map(([number, label]) => (
                  <div
                    key={label}
                    className="rounded-2xl border border-white/10 bg-white/[0.055] p-4"
                  >
                    <span className="text-xs font-bold text-[#5ed9f7]">
                      {number}
                    </span>
                    <span className="mt-3 block text-sm font-semibold text-white/80">
                      {label}
                    </span>
                  </div>
                ))}
              </div>
            </GlassScreen>
          </div>
        </div>

        {/* Scene 4: Trust */}
        <div
          className="pointer-events-none absolute inset-0 z-40"
          style={{
            opacity: trustOpacity,
          }}
        >
          <div className="shell flex h-full items-center">
            <div className="grid w-full grid-cols-1 gap-5 lg:grid-cols-[1.1fr_.9fr]">
              <GlassScreen>
                <ShieldCheck
                  size={26}
                  className="text-[#6ee0fb]"
                />

                <h2 className="mt-5 max-w-[520px] text-4xl font-semibold tracking-[-0.05em] text-white md:text-6xl">
                  Care you can see.
                  <span className="block text-white/42">
                    Quality you can trust.
                  </span>
                </h2>

                <p className="mt-6 max-w-[550px] text-base leading-8 text-white/56">
                  Professional teams, reliable communication and
                  consistent standards from the first inspection
                  to the final finishing touch.
                </p>
              </GlassScreen>

              <div className="grid grid-cols-2 gap-4">
                {[
                  ["Professional", "Trained cleaning specialists"],
                  ["Responsive", "Fast booking and communication"],
                  ["Detailed", "Careful work across every surface"],
                  ["Reliable", "Service designed around your needs"],
                ].map(([title, text], index) => (
                  <GlassScreen
                    key={title}
                    className="!rounded-[25px] !p-5"
                    style={{
                      transform: `translateY(${
                        index % 2 === 0 ? "-10px" : "10px"
                      })`,
                    }}
                  >
                    <CheckCircle2
                      size={18}
                      className="text-[#61daf8]"
                    />

                    <h3 className="mt-5 text-lg font-semibold text-white">
                      {title}
                    </h3>

                    <p className="mt-2 text-xs leading-5 text-white/48">
                      {text}
                    </p>
                  </GlassScreen>
                ))}
              </div>
            </div>
          </div>
        </div>

        {/* Scene 5: Contact */}
        <div
          id="contact"
          className="absolute inset-0 z-50"
          style={{
            opacity: contactOpacity,
            pointerEvents:
              contactOpacity > 0.7 ? "auto" : "none",
          }}
        >
          <div className="shell flex h-full items-center justify-center">
            <GlassScreen
              className="w-full max-w-[880px] text-center"
              style={{
                transform: `translate3d(0, ${
                  (1 - contactOpacity) * 75
                }px, 0) scale(${
                  0.92 + contactOpacity * 0.08
                })`,
              }}
            >
              <span className="text-[10px] font-semibold uppercase tracking-[0.32em] text-[#82dffc]">
                Start with Lark Shine
              </span>

              <h2 className="mx-auto mt-5 max-w-[720px] text-[clamp(3rem,6vw,6.8rem)] font-semibold leading-[0.92] tracking-[-0.065em] text-white">
                Ready to make your space shine?
              </h2>

              <p className="mx-auto mt-6 max-w-[560px] text-base leading-8 text-white/56">
                Tell us what needs cleaning and our team will help
                arrange the right service for your property.
              </p>

              <div className="mt-8 flex flex-wrap justify-center gap-4">
                <a
                  href="https://wa.me/971555822480"
                  target="_blank"
                  rel="noreferrer"
                  className="group inline-flex items-center gap-3 rounded-full bg-[#55d6f5] px-7 py-4 text-sm font-bold text-[#06202c] shadow-[0_20px_70px_rgba(47,206,246,.26)] transition hover:-translate-y-1 hover:bg-white"
                >
                  <MessageCircle size={18} />
                  Chat on WhatsApp
                  <ArrowRight
                    size={17}
                    className="transition-transform group-hover:translate-x-1"
                  />
                </a>

                <a
                  href="tel:+971555822480"
                  className="inline-flex items-center gap-3 rounded-full border border-white/18 bg-white/[0.07] px-7 py-4 text-sm font-bold text-white backdrop-blur-xl transition hover:bg-white/[0.13]"
                >
                  Call +971 55 582 2480
                </a>
              </div>
            </GlassScreen>
          </div>
        </div>

        {/* Progress indicator */}
        <div className="pointer-events-none absolute bottom-8 right-7 z-[60] hidden items-end gap-3 md:flex">
          <span className="text-[9px] font-bold uppercase tracking-[0.28em] text-white/28">
            Experience
          </span>

          <div className="h-28 w-[2px] overflow-hidden rounded-full bg-white/10">
            <span
              className="block w-full origin-top rounded-full bg-gradient-to-b from-[#a9efff] to-[#159bd8]"
              style={{
                height: `${Math.max(progress * 100, 3)}%`,
              }}
            />
          </div>

          <span className="w-8 text-right text-[10px] font-semibold tabular-nums text-white/45">
            {String(Math.round(progress * 100)).padStart(
              2,
              "0",
            )}
          </span>
        </div>

        <style jsx global>{`
          .glass-screen {
            position: relative;
            overflow: hidden;
            border: 1px solid rgba(191, 239, 255, 0.18);
            border-radius: 34px;
            padding: clamp(1.45rem, 3vw, 2.6rem);
            background:
              linear-gradient(
                145deg,
                rgba(255, 255, 255, 0.13),
                rgba(255, 255, 255, 0.035) 48%,
                rgba(94, 207, 238, 0.055)
              );
            box-shadow:
              inset 0 1px 0 rgba(255, 255, 255, 0.2),
              inset 0 -1px 0 rgba(81, 196, 226, 0.07),
              0 30px 100px rgba(0, 0, 0, 0.28),
              0 0 70px rgba(56, 193, 228, 0.055);
            backdrop-filter: blur(26px) saturate(135%);
            -webkit-backdrop-filter: blur(26px) saturate(135%);
            transition:
              transform 140ms linear,
              opacity 140ms linear;
            will-change: transform, opacity;
          }

          .glass-screen::before {
            content: "";
            position: absolute;
            inset: 0;
            border-radius: inherit;
            background:
              radial-gradient(
                circle at 10% 0%,
                rgba(255, 255, 255, 0.2),
                transparent 34%
              ),
              linear-gradient(
                115deg,
                transparent 20%,
                rgba(255, 255, 255, 0.065) 48%,
                transparent 72%
              );
            pointer-events: none;
          }

          .glass-screen::after {
            content: "";
            position: absolute;
            inset: 1px;
            border-radius: calc(34px - 1px);
            box-shadow:
              inset 16px 0 28px rgba(83, 212, 245, 0.025),
              inset -16px 0 28px rgba(255, 255, 255, 0.018);
            pointer-events: none;
          }

          .glass-screen-highlight {
            position: absolute;
            left: 8%;
            right: 8%;
            top: 0;
            height: 1px;
            background: linear-gradient(
              90deg,
              transparent,
              rgba(255, 255, 255, 0.65),
              transparent
            );
            opacity: 0.62;
          }

          .cinematic-grid {
            background-image:
              linear-gradient(
                rgba(132, 225, 250, 0.026) 1px,
                transparent 1px
              ),
              linear-gradient(
                90deg,
                rgba(132, 225, 250, 0.026) 1px,
                transparent 1px
              );
            background-size: 72px 72px;
            mask-image: radial-gradient(
              circle at 50% 48%,
              black,
              transparent 75%
            );
          }

          @media (max-width: 1023px) {
            .glass-screen {
              border-radius: 26px;
              padding: 1.3rem;
              backdrop-filter: blur(20px);
              -webkit-backdrop-filter: blur(20px);
            }
          }

          @media (max-width: 767px) {
            #home {
              height: 430vh;
            }

            #home .shell {
              padding-left: 1.15rem;
              padding-right: 1.15rem;
            }

            .glass-screen {
              border-radius: 23px;
              padding: 1.2rem;
            }
          }

          @media (prefers-reduced-motion: reduce) {
            #home {
              height: 100vh;
            }

            #home canvas {
              display: none;
            }
          }
        `}</style>
      </div>
    </section>
  );
}
