"use client";

import dynamic from "next/dynamic";
import {
  ArrowRight,
  Check,
  ChevronDown,
  MessageCircle,
} from "lucide-react";
import {
  CSSProperties,
  useEffect,
  useMemo,
  useRef,
  useState,
} from "react";

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

type Chapter = {
  id: string;
  eyebrow: string;
  title: string;
  body: string;
  position: "left" | "right" | "center";
};

const chapters: Chapter[] = [
  {
    id: "overview",
    eyebrow: "Lark Shine",
    title: "A cleaner space changes everything.",
    body:
      "Professional cleaning for homes, offices and properties, delivered with precision and care.",
    position: "center",
  },
  {
    id: "equipment",
    eyebrow: "Professional equipment",
    title: "Designed for a deeper clean.",
    body:
      "Specialist tools help our team work thoroughly across floors, surfaces and difficult-to-reach areas.",
    position: "left",
  },
  {
    id: "water-system",
    eyebrow: "Controlled care",
    title: "The right method for every surface.",
    body:
      "Careful product selection and controlled cleaning methods help protect the materials throughout your property.",
    position: "right",
  },
  {
    id: "floor-care",
    eyebrow: "Floor care",
    title: "Powerful where it matters. Gentle where it counts.",
    body:
      "Focused floor treatment helps lift dirt while preserving the finish and character of each surface.",
    position: "left",
  },
  {
    id: "service",
    eyebrow: "Complete service",
    title: "One team. Every important detail.",
    body:
      "Residential, commercial, deep cleaning, glass care, carpet care and property cleaning through one reliable team.",
    position: "right",
  },
  {
    id: "contact",
    eyebrow: "Book with Lark Shine",
    title: "Ready to make your space shine?",
    body:
      "Tell us what needs attention and we will help arrange the appropriate cleaning service.",
    position: "center",
  },
];

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

function chapterVisibility(
  progress: number,
  index: number,
  total: number,
) {
  const chapterStart = index / total;
  const chapterEnd = (index + 1) / total;
  const fade = 0.035;

  if (
    progress < chapterStart - fade ||
    progress > chapterEnd + fade
  ) {
    return 0;
  }

  if (progress < chapterStart + fade) {
    return clamp(
      (progress - (chapterStart - fade)) /
        (fade * 2),
    );
  }

  if (progress > chapterEnd - fade) {
    return clamp(
      ((chapterEnd + fade) - progress) /
        (fade * 2),
    );
  }

  return 1;
}

function chapterTransform(
  progress: number,
  index: number,
  total: number,
) {
  const center = (index + 0.5) / total;
  const distance = progress - center;

  return {
    transform: `translate3d(0, ${distance * -75}px, 0)`,
  } as CSSProperties;
}

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

  const [progress, setProgress] = useState(0);
  const [ready, setReady] = useState(false);

  const activeIndex = Math.min(
    chapters.length - 1,
    Math.floor(progress * chapters.length),
  );

  const chapterProgress = useMemo(
    () => Math.min(1, progress * chapters.length - activeIndex),
    [activeIndex, progress],
  );

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

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

      frame = requestAnimationFrame(() => {
        const root = rootRef.current;
        if (!root) return;

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

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

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

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

    update();

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

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

  return (
    <section
      ref={rootRef}
      id="home"
      className="relative h-[600vh] bg-[#eaf8fc]"
    >
      <div className="sticky top-0 h-[100svh] overflow-hidden">
        <div
          aria-hidden="true"
          className="absolute inset-0"
          style={{
            background:
              "radial-gradient(circle at 50% 42%, rgba(255,255,255,1) 0%, rgba(238,250,254,.98) 34%, rgba(219,243,250,.96) 66%, rgba(202,232,242,.98) 100%)",
          }}
        />

        <div
          aria-hidden="true"
          className="absolute inset-0 opacity-80"
          style={{
            background:
              "radial-gradient(circle at 18% 18%, rgba(77,198,233,.14), transparent 30%), radial-gradient(circle at 82% 78%, rgba(14,130,185,.1), transparent 34%)",
          }}
        />

        <div
          aria-hidden="true"
          className="apple-noise absolute inset-0 opacity-[0.055]"
        />

        <div className="pointer-events-none absolute inset-0 z-10">
          <LarkShine3DScene
            progressRef={progressRef}
            pointerRef={pointerRef}
            onReady={() => setReady(true)}
          />
        </div>

        <div
          className="pointer-events-none absolute inset-0 z-[80] flex items-center justify-center bg-[#eaf8fc] transition-all duration-700"
          style={{
            opacity: ready ? 0 : 1,
            visibility: ready ? "hidden" : "visible",
          }}
        >
          <div className="flex flex-col items-center gap-4">
            <span className="h-7 w-7 animate-spin rounded-full border-2 border-[#0b80bc]/15 border-t-[#0b80bc]" />
            <span className="text-[10px] font-semibold uppercase tracking-[0.26em] text-[#315d70]/55">
              Loading experience
            </span>
          </div>
        </div>

        <div className="absolute inset-0 z-20">
          {chapters.map((chapter, index) => {
            const opacity = chapterVisibility(
              progress,
              index,
              chapters.length,
            );

            const isContact = chapter.id === "contact";

            return (
              <article
                key={chapter.id}
                id={chapter.id}
                className={`chapter chapter-${chapter.position}`}
                style={{
                  opacity,
                  pointerEvents:
                    opacity > 0.78 ? "auto" : "none",
                  ...chapterTransform(
                    progress,
                    index,
                    chapters.length,
                  ),
                }}
              >
                <div
                  className={`chapter-copy ${
                    chapter.position === "center"
                      ? "chapter-copy-center"
                      : ""
                  }`}
                >
                  <p className="chapter-eyebrow">
                    {chapter.eyebrow}
                  </p>

                  <h1
                    className={
                      index === 0
                        ? "chapter-title chapter-title-hero"
                        : "chapter-title"
                    }
                  >
                    {chapter.title}
                  </h1>

                  <p className="chapter-body">
                    {chapter.body}
                  </p>

                  {index === 0 && (
                    <div className="chapter-actions">
                      <a
                        href="#contact"
                        className="apple-button apple-button-primary"
                      >
                        Request a quote
                        <ArrowRight size={16} />
                      </a>

                      <a
                        href="#equipment"
                        className="apple-button apple-button-secondary"
                      >
                        Explore
                        <ChevronDown size={16} />
                      </a>
                    </div>
                  )}

                  {chapter.id === "service" && (
                    <div className="service-list">
                      {[
                        "Residential cleaning",
                        "Commercial cleaning",
                        "Deep cleaning",
                        "Glass and floor care",
                      ].map((service) => (
                        <span key={service}>
                          <Check size={14} />
                          {service}
                        </span>
                      ))}
                    </div>
                  )}

                  {isContact && (
                    <div className="chapter-actions justify-center">
                      <a
                        href="https://wa.me/971555822480"
                        target="_blank"
                        rel="noreferrer"
                        className="apple-button apple-button-primary"
                      >
                        <MessageCircle size={17} />
                        WhatsApp
                      </a>

                      <a
                        href="tel:+971555822480"
                        className="apple-button apple-button-secondary"
                      >
                        Call us
                      </a>
                    </div>
                  )}
                </div>
              </article>
            );
          })}
        </div>

        <aside
          aria-label="Experience chapters"
          className="chapter-navigation"
        >
          <span className="chapter-count">
            {String(activeIndex + 1).padStart(2, "0")}
          </span>

          <nav>
            {chapters.map((chapter, index) => (
              <a
                key={chapter.id}
                href={`#${chapter.id}`}
                className={
                  index === activeIndex ? "active" : ""
                }
                aria-current={
                  index === activeIndex ? "step" : undefined
                }
              >
                <i />
                <span>{chapter.eyebrow}</span>
              </a>
            ))}
          </nav>

          <span className="chapter-total">
            {String(chapters.length).padStart(2, "0")}
          </span>
        </aside>

        <div className="mobile-chapter-indicator">
          <span>
            {String(activeIndex + 1).padStart(2, "0")}
          </span>

          <div>
            <i
              style={{
                width: `${Math.max(
                  3,
                  ((activeIndex + chapterProgress) /
                    chapters.length) *
                    100,
                )}%`,
              }}
            />
          </div>

          <span>
            {String(chapters.length).padStart(2, "0")}
          </span>
        </div>

        <style jsx global>{`
          .chapter {
            position: absolute;
            inset: 0;
            display: flex;
            align-items: center;
            padding: 110px max(6vw, 48px) 64px;
            transition: opacity 90ms linear;
            will-change: opacity, transform;
          }

          .chapter-left {
            justify-content: flex-start;
          }

          .chapter-right {
            justify-content: flex-end;
          }

          .chapter-center {
            align-items: flex-start;
            justify-content: center;
            padding-top: clamp(125px, 16vh, 175px);
            text-align: center;
          }

          .chapter-copy {
            width: min(39vw, 550px);
          }

          .chapter-copy-center {
            width: min(880px, 78vw);
          }

          .chapter-eyebrow {
            margin: 0 0 14px;
            color: #087eb9;
            font-size: 12px;
            font-weight: 700;
            letter-spacing: 0.17em;
            text-transform: uppercase;
          }

          .chapter-title {
            margin: 0;
            color: #102f3e;
            font-size: clamp(3rem, 5.7vw, 6.5rem);
            font-weight: 650;
            letter-spacing: -0.065em;
            line-height: 0.95;
          }

          .chapter-title-hero {
            margin-inline: auto;
            max-width: 960px;
            font-size: clamp(3.6rem, 7vw, 7.8rem);
          }

          .chapter-body {
            max-width: 560px;
            margin-top: 24px;
            color: rgba(42, 80, 97, 0.74);
            font-size: clamp(1rem, 1.35vw, 1.16rem);
            line-height: 1.72;
          }

          .chapter-copy-center .chapter-body {
            margin-inline: auto;
          }

          .chapter-actions {
            position: relative;
            z-index: 40;
            display: flex;
            flex-wrap: wrap;
            gap: 12px;
            margin-top: 28px;
          }

          .chapter-copy-center .chapter-actions {
            justify-content: center;
          }

          .apple-button {
            display: inline-flex;
            min-height: 45px;
            align-items: center;
            justify-content: center;
            gap: 9px;
            border-radius: 999px;
            padding: 0 21px;
            font-size: 14px;
            font-weight: 650;
            transition:
              transform 180ms ease,
              background 180ms ease,
              box-shadow 180ms ease;
          }

          .apple-button:hover {
            transform: translateY(-2px);
          }

          .apple-button-primary {
            background: #087fbb;
            box-shadow: 0 12px 35px rgba(8, 127, 187, 0.2);
            color: white;
          }

          .apple-button-primary:hover {
            background: #066d9f;
            box-shadow: 0 17px 45px rgba(8, 127, 187, 0.28);
          }

          .apple-button-secondary {
            border: 1px solid rgba(21, 101, 137, 0.18);
            background: rgba(255, 255, 255, 0.48);
            color: #12435a;
            backdrop-filter: blur(16px);
          }

          .apple-button-secondary:hover {
            background: rgba(255, 255, 255, 0.78);
          }

          .service-list {
            display: grid;
            gap: 10px;
            margin-top: 27px;
          }

          .service-list span {
            display: flex;
            align-items: center;
            gap: 9px;
            color: rgba(21, 63, 82, 0.77);
            font-size: 14px;
            font-weight: 600;
          }

          .service-list svg {
            color: #0784bf;
          }

          .chapter-navigation {
            position: absolute;
            z-index: 50;
            top: 50%;
            left: 28px;
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 13px;
            transform: translateY(-50%);
          }

          .chapter-navigation nav {
            display: flex;
            flex-direction: column;
            gap: 10px;
          }

          .chapter-navigation a {
            display: flex;
            min-height: 26px;
            align-items: center;
            gap: 10px;
            color: rgba(24, 69, 88, 0.35);
            font-size: 10px;
            font-weight: 700;
            letter-spacing: 0.08em;
            text-transform: uppercase;
            transition: color 180ms ease;
          }

          .chapter-navigation a i {
            display: block;
            width: 6px;
            height: 6px;
            border: 1px solid rgba(8, 126, 184, 0.35);
            border-radius: 50%;
            transition:
              width 180ms ease,
              height 180ms ease,
              background 180ms ease;
          }

          .chapter-navigation a span {
            max-width: 0;
            overflow: hidden;
            opacity: 0;
            white-space: nowrap;
            transition:
              max-width 220ms ease,
              opacity 180ms ease;
          }

          .chapter-navigation a:hover span,
          .chapter-navigation a.active span {
            max-width: 140px;
            opacity: 1;
          }

          .chapter-navigation a.active {
            color: #087fbb;
          }

          .chapter-navigation a.active i {
            width: 9px;
            height: 9px;
            background: #087fbb;
          }

          .chapter-count,
          .chapter-total {
            color: rgba(25, 67, 84, 0.42);
            font-size: 9px;
            font-weight: 700;
            letter-spacing: 0.13em;
          }

          .mobile-chapter-indicator {
            position: absolute;
            z-index: 50;
            right: 20px;
            bottom: 19px;
            left: 20px;
            display: none;
            align-items: center;
            gap: 10px;
            color: rgba(24, 70, 89, 0.42);
            font-size: 9px;
            font-weight: 700;
          }

          .mobile-chapter-indicator div {
            flex: 1;
            height: 2px;
            overflow: hidden;
            border-radius: 999px;
            background: rgba(12, 91, 126, 0.1);
          }

          .mobile-chapter-indicator i {
            display: block;
            height: 100%;
            border-radius: inherit;
            background: #0784bf;
            transition: width 80ms linear;
          }

          .apple-noise {
            background-image: url("data:image/svg+xml,%3Csvg viewBox='0 0 180 180' xmlns='http://www.w3.org/2000/svg'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.8' numOctaves='4' stitchTiles='stitch'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)' opacity='.35'/%3E%3C/svg%3E");
          }

          @media (max-width: 1023px) {
            .chapter {
              padding-inline: 7vw;
            }

            .chapter-copy {
              width: min(44vw, 480px);
            }

            .chapter-navigation {
              left: 17px;
            }
          }

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

            .chapter {
              align-items: flex-start;
              justify-content: flex-start;
              padding: 112px 22px 74px;
              text-align: left;
            }

            .chapter-center {
              padding-top: 112px;
              text-align: left;
            }

            .chapter-copy,
            .chapter-copy-center {
              width: 100%;
              max-width: 100%;
            }

            .chapter-eyebrow {
              margin-bottom: 10px;
              font-size: 10px;
            }

            .chapter-title,
            .chapter-title-hero {
              max-width: 340px;
              margin-inline: 0;
              font-size: clamp(2.7rem, 12vw, 4.2rem);
              line-height: 0.94;
            }

            .chapter-body,
            .chapter-copy-center .chapter-body {
              max-width: 315px;
              margin: 16px 0 0;
              font-size: 0.94rem;
              line-height: 1.58;
            }

            .chapter-actions,
            .chapter-copy-center .chapter-actions {
              justify-content: flex-start;
              margin-top: 19px;
            }

            .apple-button {
              min-height: 43px;
              padding-inline: 18px;
              font-size: 13px;
            }

            .service-list {
              max-width: 300px;
              margin-top: 18px;
              gap: 7px;
            }

            .chapter-navigation {
              display: none;
            }

            .mobile-chapter-indicator {
              display: flex;
            }
          }

          @media (max-width: 420px) {
            .chapter {
              padding-inline: 18px;
            }

            .chapter-title,
            .chapter-title-hero {
              max-width: 300px;
              font-size: clamp(2.45rem, 11.8vw, 3.6rem);
            }

            .chapter-body,
            .chapter-copy-center .chapter-body {
              max-width: 285px;
              font-size: 0.88rem;
            }
          }

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

            #home canvas,
            .chapter-navigation,
            .mobile-chapter-indicator {
              display: none;
            }

            .chapter {
              position: relative;
              min-height: auto;
              padding-block: 90px;
              opacity: 1 !important;
              transform: none !important;
              pointer-events: auto !important;
            }
          }
        `}</style>
      </div>
    </section>
  );
}
