"use client";
import { useHeaderTheme } from "@/providers/HeaderTheme";
import React, { useEffect, useMemo, useRef, useState } from "react";

import type { Page } from "@/payload-types";

import { CMSLink } from "@/components/Link";
import { Media } from "@/components/Media";
import RichText from "@/components/RichText";

export const HighImpactHero: React.FC<Page["hero"]> = ({ links, media, richText, marquee }) => {
  const { setHeaderTheme } = useHeaderTheme();
  const marqueeScrollRef = useRef<HTMLDivElement | null>(null);
  const marqueeBaseRef = useRef<HTMLUListElement | null>(null);
  const marqueeSegmentRef = useRef<HTMLUListElement | null>(null);
  const [marqueeRepeatCount, setMarqueeRepeatCount] = useState(2);
  const [marqueeDuration, setMarqueeDuration] = useState(42);

  const marqueeItems = useMemo(() => {
    if (!marquee || typeof marquee !== "object" || !Array.isArray(marquee.marqueeItems)) {
      return [];
    }

    return marquee.marqueeItems;
  }, [marquee]);

  const repeatedMarqueeItems = useMemo(() => {
    if (marqueeItems.length === 0) {
      return [];
    }

    return Array.from({ length: marqueeRepeatCount }, () => marqueeItems).flat();
  }, [marqueeItems, marqueeRepeatCount]);

  useEffect(() => {
    setHeaderTheme("dark");
  });

  useEffect(() => {
    if (marqueeItems.length === 0) {
      return;
    }

    const updateMarqueeMetrics = () => {
      const scrollEl = marqueeScrollRef.current;
      const baseEl = marqueeBaseRef.current;
      const segmentEl = marqueeSegmentRef.current;

      if (!scrollEl || !baseEl) {
        return;
      }

      const viewportWidth = scrollEl.clientWidth;
      const baseWidth = baseEl.scrollWidth;

      if (viewportWidth <= 0 || baseWidth <= 0) {
        return;
      }

      const nextRepeatCount = Math.max(2, Math.ceil((viewportWidth * 1.5) / baseWidth));

      setMarqueeRepeatCount(prev => (prev !== nextRepeatCount ? nextRepeatCount : prev));
    };

    updateMarqueeMetrics();

    const resizeObserver = new ResizeObserver(updateMarqueeMetrics);

    if (marqueeScrollRef.current) {
      resizeObserver.observe(marqueeScrollRef.current);
    }

    if (marqueeBaseRef.current) {
      resizeObserver.observe(marqueeBaseRef.current);
    }

    if (marqueeSegmentRef.current) {
      resizeObserver.observe(marqueeSegmentRef.current);
    }

    return () => {
      resizeObserver.disconnect();
    };
  }, [marqueeItems, marqueeRepeatCount]);

  return (
    <div
      className="relative mt-[-10.4rem] flex items-center justify-center text-white"
      data-theme="dark"
    >
      <div className="container mb-8 z-10 relative flex items-center justify-center">
        <div className="max-w-146 md:text-center">
          {richText && <RichText className="mb-6" data={richText} enableGutter={false}/>}
          {Array.isArray(links) && links.length > 0 && (
            <ul className="flex md:justify-center gap-4">
              {links.map(({ link }, i) => {
                return (
                  <li key={i}>
                    <CMSLink {...link} />
                  </li>
                );
              })}
            </ul>
          )}
        </div>
      </div>
      <div className="min-h-[80vh] select-none">
        {media && typeof media === "object" && (
          <Media fill imgClassName="-z-10 object-cover" className="after:absolute after:inset-0 after:bg-radial after:from-black/70 after:to-black/50" priority resource={media}/>
        )}
        {
          marqueeItems.length > 0 && (
            <div className="marquee-scroll overflow-hidden w-full absolute bottom-1/12 left-0 right-0 m-auto" ref={marqueeScrollRef}>
              <ul className="absolute opacity-0 pointer-events-none whitespace-nowrap flex shrink-0 items-center" ref={marqueeBaseRef}>
                {marqueeItems.map((item, idx) => (
                  <li className="inline-block" key={idx} title={item.itemLabel}>{
                    item.itemClassName ? (
                      <i className={item.itemClassName + ` inline-block text-4xl opacity-50 hover:opacity-100 transition-all text-white mr-10`}/>) : item.itemMedia ? (
                      <Media resource={item.itemMedia}/>) : item.itemLabel
                  }</li>
                ))}
              </ul>
              <div className="animate-marquee flex w-max" style={{ "--marquee-duration": `${marqueeDuration}s` } as React.CSSProperties}>
                {[1, 2].map(i => (
                  <ul
                    className="flex shrink-0 items-center whitespace-nowrap"
                    ref={i === 1 ? marqueeSegmentRef : undefined}
                    key={i}
                  >
                    {repeatedMarqueeItems.map((item, idx) => (
                      <li className="inline-block" key={`${i}-${idx}`} title={item.itemLabel}>{
                        item.itemClassName ? (
                          <i className={item.itemClassName + ` inline-block text-4xl opacity-50 hover:opacity-100 transition-all text-white mr-10`}/>) : item.itemMedia ? (
                          <Media resource={item.itemMedia}/>) : item.itemLabel
                      }</li>
                    ))}
                  </ul>
                ))}
              </div>
            </div>
          )
        }
      </div>
    </div>
);
};
