"use client";

import Lenis from "@studio-freight/lenis";
import Image from "next/image";
import { useEffect, useRef, useState } from "react";
import {
  FaEnvelope,
  FaFacebookF,
  FaInstagram,
  FaLinkedinIn,
} from "react-icons/fa";
import { useSections } from "../../hooks/useSections";
import {
  getMediaUrl,
  getMetaData,
  getSocialLinks,
} from "../../lib/strapiClient";
import FullscreenModal from "../FullscreenModal";
import CareerModalContent from "../FullscreenModal/contents/CarrerModalContent";
import ContactModalContent from "../FullscreenModal/contents/ContactModalContent";
import NewsletterModalContent from "../FullscreenModal/contents/NewsletterModalContent";
import OfferModalContent from "../FullscreenModal/contents/OfferModalContent";
import PortfolioModalContent from "../FullscreenModal/contents/PortfolioModalContent";
import ScrollDots from "../ScrollDots";
import TransparentNavbar from "../TransparentNavbar";
import LanguageSwitcher from "../LanguageSwitcher";
import { gaEvent } from "../../lib/ga";
import { DEFAULT_LOCALE, saveLocale, type SupportedLocale } from "../../lib/locale";

declare global {
  interface Window {
    lenis?: Lenis;
  }
}

export default function TestParallax({
  initialLocale = DEFAULT_LOCALE,
}: {
  initialLocale?: SupportedLocale;
}) {
  const { data: sections, loading, error } = useSections(initialLocale);
  const [socialLinks, setSocialLinks] = useState<any[]>([]);
  const sectionRefs = useRef<(HTMLDivElement | null)[]>([]);
  const videoRefs = useRef<(HTMLVideoElement | null)[]>([]);

  const [isModalOpen, setIsModalOpen] = useState(false);
  const [modalContent, setModalContent] = useState<React.ReactNode | null>(null);
  const [phoneNumber, setPhoneNumber] = useState<string | null>(null);
  const [currentSectionIndex, setCurrentSectionIndex] = useState(0);
  const [lenisInstance, setLenisInstance] = useState<Lenis | null>(null);

  const currentSectionRef = useRef(0);
  const lenisRef = useRef<Lenis | null>(null);

  const isIOS =
    typeof window !== "undefined" &&
    /iPad|iPhone|iPod/.test(navigator.userAgent || "");

  useEffect(() => {
    saveLocale(initialLocale);
  }, [initialLocale]);

  const openModalForAction = (action?: string | null) => {
    switch (action) {
      case "offer":
        setModalContent(<OfferModalContent locale={initialLocale} />);
        break;
      case "career":
        setModalContent(<CareerModalContent locale={initialLocale} />);
        break;
      case "contact":
        setModalContent(<ContactModalContent locale={initialLocale} />);
        break;
      case "newsletter":
        setModalContent(<NewsletterModalContent locale={initialLocale} />);
        break;
      case "portfolio":
        setModalContent(<PortfolioModalContent locale={initialLocale} />);
        break;
      default:
        setModalContent(null);
        return;
    }

    console.log("Opening modal for action:", action);
    gaEvent("modal_open", { modal: action ?? "unknown" });
    setIsModalOpen(true);
  };

  useEffect(() => {
    getSocialLinks(initialLocale).then(setSocialLinks).catch(console.error);
  }, [initialLocale]);

  useEffect(() => {
    const loadMeta = async () => {
      const meta = await getMetaData(initialLocale);
      if (meta?.[0]?.Numer_Telefonu) {
        setPhoneNumber(meta[0].Numer_Telefonu);
      }
    };

    loadMeta();
  }, [initialLocale]);

  useEffect(() => {
    if (typeof window === "undefined") return;

    if (window.location.href.includes("newsletter-action")) {
      openModalForAction("newsletter");
    }
  }, []);

  useEffect(() => {
    const lenis = lenisRef.current;
    if (!lenis) return;

    if (isModalOpen) {
      lenis.stop();
    } else {
      lenis.start();
    }
  }, [isModalOpen]);

  useEffect(() => {
    if (typeof window === "undefined") return;

    const isMobile = window.innerWidth < 640;

    if (isMobile) {
      document.body.style.overflow = "auto";
      document.body.style.scrollBehavior = "smooth";
      return;
    }

    const lenis = new Lenis({ lerp: 0.265 });

    window.lenis = lenis;
    lenisRef.current = lenis;
    setLenisInstance(lenis);

    let rafId = 0;

    const raf = (time: number) => {
      lenis.raf(time);
      rafId = requestAnimationFrame(raf);
    };

    rafId = requestAnimationFrame(raf);

    const update = () => {
      const winH = window.innerHeight;

      sectionRefs.current.forEach((section, idx) => {
        const video = videoRefs.current[idx];
        if (!section || !video) return;

        const rect = section.getBoundingClientRect();
        const offset = rect.top / winH;
        const translateY = offset * -65;

        video.style.transform = `translateY(${translateY}%)`;

        const textWrap = section.querySelector(
          ".text-wrapper"
        ) as HTMLDivElement | null;

        if (textWrap) {
          textWrap.style.transform = `translateY(${translateY}%)`;
        }
      });

      const firstVisible = sectionRefs.current.findIndex((section) => {
        if (!section) return false;

        const rect = section.getBoundingClientRect();

        return rect.top < winH * 0.6 && rect.bottom > winH * 0.4;
      });

      if (firstVisible !== -1 && firstVisible !== currentSectionRef.current) {
        currentSectionRef.current = firstVisible;
        setCurrentSectionIndex(firstVisible);
      }
    };

    lenis.on("scroll", update);
    update();

    return () => {
      cancelAnimationFrame(rafId);

      try {
        lenis.destroy();
      } catch {}

      lenisRef.current = null;
      setLenisInstance(null);
    };
  }, []);

  useEffect(() => {
    if (typeof window === "undefined") return;

    const isMobile = window.innerWidth < 640;
    if (!isMobile) return;

    const isIOSLocal = /iPad|iPhone|iPod/.test(navigator.userAgent || "");
    if (!isIOSLocal) return;

    const videos = videoRefs.current.filter(Boolean) as HTMLVideoElement[];
    if (!videos.length) return;

    videos.forEach((v) => {
      v.preload = "none";
      v.disablePictureInPicture = true;
    });

    const pauseAndUnload = (v: HTMLVideoElement) => {
      try {
        v.pause();
      } catch {}

      const src = v.getAttribute("src");

      if (src) {
        v.setAttribute("data-src", src);
        v.removeAttribute("src");
        v.load();
      }
    };

    const restoreAndPlay = async (v: HTMLVideoElement) => {
      if (!v.getAttribute("src")) {
        const dataSrc = v.getAttribute("data-src");

        if (dataSrc) {
          v.setAttribute("src", dataSrc);
        }

        v.load();
      }

      try {
        await v.play();
      } catch {}
    };

    const observer = new IntersectionObserver(
      (entries) => {
        const visible = entries
          .filter((e) => e.isIntersecting)
          .sort(
            (a, b) => (b.intersectionRatio ?? 0) - (a.intersectionRatio ?? 0)
          )[0];

        videos.forEach((v) => {
          if (!visible) {
            pauseAndUnload(v);
            return;
          }

          if (visible.target === v) {
            restoreAndPlay(v);
          } else {
            pauseAndUnload(v);
          }
        });
      },
      {
        threshold: [0, 0.25, 0.5, 0.75],
        rootMargin: "0px 0px -20% 0px",
      }
    );

    videos.forEach((v) => observer.observe(v));

    return () => {
      observer.disconnect();

      videos.forEach((v) => {
        const dataSrc = v.getAttribute("data-src");

        if (dataSrc && !v.getAttribute("src")) {
          v.setAttribute("src", dataSrc);
          v.removeAttribute("data-src");
          v.load();
        }
      });
    };
  }, []);

  if (loading) {
    return (
      <div className="text-white text-center py-10">Ładowanie sekcji…</div>
    );
  }

  if (error) {
    return (
      <div className="text-red-500 text-center py-10">Błąd: {error}</div>
    );
  }

  if (!Array.isArray(sections) || sections.length === 0) {
    return <p className="text-white text-center py-10">Brak sekcji w CMS.</p>;
  }

  return (
    <div className="bg-black">
      <TransparentNavbar locale={initialLocale} />

      {sections.map((section: any, idx: number) => {
        const videoSrc = getMediaUrl(section.video);
        const logoSrc = getMediaUrl(section.image);

        return (
          <section
            key={section.id}
            data-section-index={idx}
            ref={(el: HTMLDivElement | null) => {
              sectionRefs.current[idx] = el;
            }}
            className={`relative min-h-screen flex items-center justify-center ${
              !isIOS ? "overflow-hidden" : ""
            }`}
          >
            {idx === 0 && (
              <>
                {phoneNumber && (
                  <div className="fixed top-4 right-4 z-50">
                    <a
                      href={`tel:${phoneNumber}`}
                      onClick={() =>
                        gaEvent("contact_click", {
                          method: "phone",
                          placement: "intro_top_right",
                        })
                      }
                      className="text-[#eea71f] text-sm md:text-[35px] font-semibold bg-black/30 backdrop-blur-md px-6 py-1 rounded-lg"
                    >
                      {phoneNumber}
                    </a>
                  </div>
                )}


                <LanguageSwitcher currentLocale={initialLocale} />

                <div className="fixed bottom-4 right-4 z-50 flex space-x-3">
                  {socialLinks.map((item, index) => {
                    const Icon =
                      {
                        facebook: FaFacebookF,
                        instagram: FaInstagram,
                        linkedin: FaLinkedinIn,
                        newsletter: FaEnvelope,
                      }[item.type?.toLowerCase()] ?? null;

                    if (!Icon) return null;

                    if (item.action === "newsletter") {
                      return (
                        <button
                          key={index}
                          onClick={() => openModalForAction("newsletter")}
                          className="bg-black/30 backdrop-blur-md p-3 rounded-lg hover:bg-[#eea71f]/20 transition"
                          aria-label={item.type}
                        >
                          <Icon className="w-5 h-5 text-[#eea71f]" />
                        </button>
                      );
                    }

                    return (
                      <a
                        key={index}
                        href={item.link}
                        target="_blank"
                        rel="noopener noreferrer"
                        onClick={() =>
                          gaEvent("outbound_click", {
                            destination:
                              item.type?.toLowerCase() ?? "unknown",
                            placement: "intro_social",
                          })
                        }
                        className="bg-black/30 backdrop-blur-md p-3 rounded-lg hover:bg-[#eea71f]/20 transition"
                        aria-label={item.type}
                      >
                        <Icon className="w-5 h-5 text-[#eea71f]" />
                      </a>
                    );
                  })}
                </div>
              </>
            )}

            <video
              ref={(el) => {
                videoRefs.current[idx] = el;
              }}
              src={videoSrc}
              autoPlay
              muted
              loop
              playsInline
              disablePictureInPicture
              preload="metadata"
              className="absolute top-0 left-0 w-full h-[120%] object-cover pointer-events-none"
              style={{ filter: "brightness(80%)" }}
            />

            <div className="text-wrapper absolute inset-0 z-10 flex flex-col items-center justify-center px-6 text-center">
              {section.type === "intro" ? (
                <>
                  {logoSrc && (
                    <Image
                      src={logoSrc}
                      alt="Logo"
                      width={200}
                      height={200}
                      className="mx-auto mb-4"
                    />
                  )}

                  <h1 className="text-4xl md:text-7xl font-extrabold uppercase text-white drop-shadow-md tracking-wide">
                    {section.title || "Laskar"}
                  </h1>
                </>
              ) : (
                <div className="w-full space-y-6">
                  {logoSrc && (
                    <Image
                      src={logoSrc}
                      alt="Logo"
                      width={200}
                      height={200}
                      className="mx-auto mb-4"
                    />
                  )}

                  {section.title && (
                    <h1 className="text-4xl md:text-7xl font-extrabold uppercase text-white drop-shadow-md tracking-wide">
                      {section.title}
                    </h1>
                  )}

                  {section.subtitle && (
                    <p className="text-lg md:text-xl leading-relaxed text-white/90 max-w-3xl mx-auto bg-black/30 backdrop-blur-md px-6 py-4 rounded-lg shadow-md">
                      {section.subtitle}
                    </p>
                  )}

                  {section.buttonLabel && (
                    <button
                      onClick={() => {
                        gaEvent("cta_click", {
                          cta: section.buttonLabel ?? "unknown",
                          action: section.action ?? "unknown",
                        });

                        openModalForAction(section.action);
                      }}
                      className="mt-4 inline-block cursor-pointer text-lg md:text-5xl uppercase font-medium px-6 hover:text-[#eea71f] py-2 rounded-lg text-white transition duration-300 ease-in-out"
                    >
                      {section.buttonLabel}
                    </button>
                  )}
                </div>
              )}
            </div>
          </section>
        );
      })}

      <FullscreenModal
        isOpen={isModalOpen}
        onClose={() => setIsModalOpen(false)}
      >
        {modalContent}
      </FullscreenModal>

      {lenisInstance && (
        <ScrollDots
          currentIndex={currentSectionIndex}
          sections={sections.map((s: any) => s.title)}
          lenis={lenisInstance}
          sectionRefs={sectionRefs.current}
        />
      )}
    </div>
  );
}