"use client";

import Image from "next/image";
import {
  ArrowRight,
  ChevronDown,
  MessageCircle,
} from "lucide-react";
import {
  CSSProperties,
  useEffect,
  useRef,
  useState,
} from "react";
import AppleFrameSequence from "./AppleFrameSequence";

type Chapter = {
  start: number;
  end: number;
  eyebrow: string;
  title: string;
  body: string;
  alignment: "left" | "right" | "center";
  dark?: boolean;
};

const chapters: Chapter[] = [
  {
    start: 0,
    end: 0.16,
    eyebrow: "Lark Shine",
    title: "Cleaning, reimagined.",
    body:
      "Professional care for spaces that deserve more attention.",
    alignment: "center",
  },
  {
    start: 0.16,
    end: 0.34,
    eyebrow: "Precision",
    title: "Every surface. Considered.",
    body:
      "The appropriate tools, products and methods for every area.",
    alignment: "left",
  },
  {
    start: 0.34,
    end: 0.53,
    eyebrow: "Deep cleaning",
    title: "Go beyond what is visible.",
    body:
      "Detailed care for overlooked corners, surfaces and finishes.",
    alignment: "right",
    dark: true,
  },
  {
    start: 0.53,
    end: 0.72,
    eyebrow: "Floor and glass care",
    title: "Clarity in every detail.",
    body:
      "Specialized care designed to improve the final appearance.",
    alignment: "left",
    dark: true,
  },
  {
    start: 0.72,
    end: 0.88,
    eyebrow: "Professional service",
    title: "One team. Complete care.",
    body:
      "Residential and commercial cleaning managed from start to finish.",
    alignment: "right",
  },
  {
    start: 0.88,
    end: 1,
    eyebrow: "Lark Shine",
    title: "Your cleaner space starts here.",
    body:
      "Tell us about your property and the service you need.",
    alignment: "center",
  },
];

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

function visibility(
  progress: number,
  start: number,
  end: number,
) {
  const fade = 0.035;

  if (progress < start - fade || progress > end + fade) {
    return 0;
  }

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

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

  return 1;
}

export default function HeroStory() {
  const sectionRef = useRef<HTMLElement>(null);
  const progressRef = useRef(0);

  const [progress, setProgress] = useState(0);
  const [framesReady, setFramesReady] = useState(false);

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

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

      animationFrame = requestAnimationFrame(() => {
        const section = sectionRef.current;

        if (!section) return;

        const rect = section.getBoundingClientRect();

        const available =
          section.offsetHeight - window.innerHeight;

        const next = clamp(
          available > 0 ? -rect.top / available : 0,
        );

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

    update();

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

    window.addEventListener("resize", update);

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

  return (
    <section
      ref={sectionRef}
      id="home"
      className="relative h-[650vh] bg-[#f5f5f7] max-md:h-[480vh]"
    >
      <div className="sticky top-0 h-[100svh] overflow-hidden bg-[#f5f5f7]">
        <AppleFrameSequence
          progressRef={progressRef}
          onReady={() => setFramesReady(true)}
        />

        <div
          className="pointer-events-none absolute inset-0 z-10"
          style={{
            background:
              "linear-gradient(180deg, rgba(245,245,247,.2), transparent 22%, transparent 75%, rgba(245,245,247,.12))",
          }}
        />

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

            const center =
              chapter.start +
              (chapter.end - chapter.start) / 2;

            const offset = (progress - center) * -85;

            return (
              <article
                key={chapter.title}
                className={[
                  "apple-frame-chapter",
                  `apple-frame-${chapter.alignment}`,
                  chapter.dark ? "apple-frame-dark" : "",
                ].join(" ")}
                style={
                  {
                    opacity,
                    transform: `translate3d(0, ${offset}px, 0)`,
                    pointerEvents:
                      opacity > 0.75 ? "auto" : "none",
                  } as CSSProperties
                }
              >
                <div className="apple-frame-copy">
                  <p>{chapter.eyebrow}</p>

                  <h1>{chapter.title}</h1>

                  <span>{chapter.body}</span>

                  {index === 0 && (
                    <div className="apple-frame-actions">
                      <a
                        href="#services"
                        className="apple-frame-button-primary"
                      >
                        Explore services
                        <ArrowRight size={16} />
                      </a>

                      <a
                        href="#contact"
                        className="apple-frame-button-secondary"
                      >
                        Book now
                      </a>
                    </div>
                  )}

                  {index === chapters.length - 1 && (
                    <div className="apple-frame-actions">
                      <a
                        href="https://wa.me/971555822480"
                        target="_blank"
                        rel="noreferrer"
                        className="apple-frame-button-primary"
                      >
                        <MessageCircle size={17} />
                        WhatsApp
                      </a>

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

        <div
          className="absolute inset-x-0 top-0 z-40 transition-opacity duration-700"
          style={{
            opacity: framesReady ? 1 : 0,
          }}
        >
          <div className="apple-sequence-header">
            <Image
              src="/brand/lark-shine-logo.png"
              alt="Lark Shine Building Cleaning Services LLC"
              width={900}
              height={500}
              priority
            />

            <nav>
              <a href="#home">Overview</a>
              <a href="#services">Services</a>
              <a href="#contact">Contact</a>
            </nav>

            <a
              href="https://wa.me/971555822480"
              target="_blank"
              rel="noreferrer"
            >
              Book now
            </a>
          </div>
        </div>

        <div className="apple-frame-progress">
          <span
            style={{
              transform: `scaleX(${progress})`,
            }}
          />
        </div>

        <div
          className="apple-scroll-hint"
          style={{
            opacity: progress < 0.04 ? 1 : 0,
          }}
        >
          <ChevronDown size={18} />
          Scroll to explore
        </div>

        <style jsx global>{`
          .apple-sequence-header {
            display: grid;
            width: min(1180px, calc(100% - 48px));
            height: 68px;
            margin-inline: auto;
            grid-template-columns: 1fr auto 1fr;
            align-items: center;
          }

          .apple-sequence-header > img {
            width: 176px;
            height: 52px;
            object-fit: contain;
            object-position: left center;
          }

          .apple-sequence-header nav {
            display: flex;
            gap: 32px;
          }

          .apple-sequence-header nav a {
            color: rgba(20, 20, 22, 0.72);
            font-size: 12px;
            font-weight: 500;
          }

          .apple-sequence-header > a {
            justify-self: end;
            border-radius: 999px;
            background: #0071e3;
            padding: 8px 16px;
            color: white;
            font-size: 12px;
            font-weight: 600;
          }

          .apple-frame-chapter {
            position: absolute;
            inset: 0;
            display: flex;
            align-items: center;
            padding: 105px max(7vw, 52px) 60px;
            transition: opacity 75ms linear;
            will-change: opacity, transform;
          }

          .apple-frame-left {
            justify-content: flex-start;
          }

          .apple-frame-right {
            justify-content: flex-end;
          }

          .apple-frame-center {
            align-items: flex-start;
            justify-content: center;
            padding-top: clamp(115px, 15vh, 160px);
            text-align: center;
          }

          .apple-frame-copy {
            width: min(490px, 38vw);
          }

          .apple-frame-center .apple-frame-copy {
            width: min(920px, 78vw);
          }

          .apple-frame-copy > p {
            margin-bottom: 13px;
            color: #0071e3;
            font-size: 13px;
            font-weight: 600;
          }

          .apple-frame-copy h1 {
            margin: 0;
            color: #1d1d1f;
            font-size: clamp(3.6rem, 6.8vw, 7.8rem);
            font-weight: 600;
            letter-spacing: -0.072em;
            line-height: 0.92;
          }

          .apple-frame-center .apple-frame-copy h1 {
            font-size: clamp(4rem, 8vw, 9rem);
          }

          .apple-frame-copy > span {
            display: block;
            max-width: 500px;
            margin-top: 22px;
            color: rgba(29, 29, 31, 0.65);
            font-size: clamp(1rem, 1.4vw, 1.2rem);
            line-height: 1.6;
          }

          .apple-frame-center .apple-frame-copy > span {
            margin-inline: auto;
          }

          .apple-frame-dark .apple-frame-copy h1 {
            color: white;
          }

          .apple-frame-dark .apple-frame-copy > p {
            color: #67c8ff;
          }

          .apple-frame-dark .apple-frame-copy > span {
            color: rgba(255, 255, 255, 0.64);
          }

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

          .apple-frame-center .apple-frame-actions {
            justify-content: center;
          }

          .apple-frame-actions a {
            display: inline-flex;
            min-height: 44px;
            align-items: center;
            justify-content: center;
            gap: 8px;
            border-radius: 999px;
            padding: 0 20px;
            font-size: 14px;
            font-weight: 600;
          }

          .apple-frame-button-primary {
            background: #0071e3;
            color: white;
          }

          .apple-frame-button-secondary {
            border: 1px solid rgba(0, 113, 227, 0.45);
            color: #0071e3;
          }

          .apple-frame-dark .apple-frame-button-secondary {
            border-color: rgba(255, 255, 255, 0.42);
            color: white;
          }

          .apple-frame-progress {
            position: absolute;
            z-index: 60;
            right: 0;
            bottom: 0;
            left: 0;
            height: 2px;
            background: rgba(0, 0, 0, 0.08);
          }

          .apple-frame-progress span {
            display: block;
            width: 100%;
            height: 100%;
            background: #0071e3;
            transform-origin: left;
          }

          .apple-scroll-hint {
            position: absolute;
            z-index: 60;
            bottom: 24px;
            left: 50%;
            display: flex;
            align-items: center;
            gap: 7px;
            color: rgba(29, 29, 31, 0.48);
            font-size: 11px;
            font-weight: 600;
            transition: opacity 300ms ease;
            transform: translateX(-50%);
          }

          @media (max-width: 767px) {
            .apple-sequence-header {
              width: calc(100% - 32px);
              height: 60px;
              grid-template-columns: 1fr auto;
            }

            .apple-sequence-header > img {
              width: 140px;
              height: 44px;
            }

            .apple-sequence-header nav {
              display: none;
            }

            .apple-sequence-header > a {
              padding: 7px 13px;
              font-size: 11px;
            }

            .apple-frame-chapter,
            .apple-frame-center {
              align-items: flex-start;
              justify-content: flex-start;
              padding: 96px 20px 65px;
              text-align: left;
            }

            .apple-frame-copy,
            .apple-frame-center .apple-frame-copy {
              width: 100%;
            }

            .apple-frame-copy h1,
            .apple-frame-center .apple-frame-copy h1 {
              max-width: 340px;
              font-size: clamp(3rem, 13vw, 4.8rem);
            }

            .apple-frame-copy > span,
            .apple-frame-center .apple-frame-copy > span {
              max-width: 310px;
              margin: 16px 0 0;
              font-size: 0.94rem;
            }

            .apple-frame-center .apple-frame-actions {
              justify-content: flex-start;
            }
          }
        `}</style>
      </div>
    </section>
  );
}
