"use client";

import { useEffect, useRef } from "react";

type WhyOfficialItem = {
  description: string;
  icon: "briefcase" | "rocket" | "badge";
  title: string;
};

function WhyOfficialIcon({ type }: { type: WhyOfficialItem["icon"] }) {
  return (
    <div className="flex h-14 w-14 items-center justify-center rounded-full border border-[#dce7ff] bg-[radial-gradient(circle_at_top,#f7fbff_0%,#e8f0ff_100%)] text-[#2f6df6] shadow-[0_10px_24px_rgba(47,109,246,0.08)]">
      <svg
        aria-hidden="true"
        className="h-6 w-6"
        fill="none"
        stroke="currentColor"
        strokeLinecap="round"
        strokeLinejoin="round"
        strokeWidth="1.8"
        viewBox="0 0 24 24"
      >
        {type === "briefcase" ? (
          <>
            <path d="M4 8.5h16v8.3a1.8 1.8 0 0 1-1.8 1.8H5.8A1.8 1.8 0 0 1 4 16.8z" />
            <path d="M8.5 8V6.5A1.5 1.5 0 0 1 10 5h4a1.5 1.5 0 0 1 1.5 1.5V8" />
            <path d="M4 11.2h16" />
          </>
        ) : null}
        {type === "rocket" ? (
          <>
            <path d="M9.5 14.5c-2-3.6.2-7.8 6.1-9 1.2 5.8-.2 10.1-4 11.8" />
            <path d="m9.3 14.7-3.1 3.1" />
            <path d="m8 9.8-2.8.3.4-2.6 2.4-.8" />
            <path d="m14.3 16 1 2.4 2.6.4-.3-2.8" />
            <circle cx="13.9" cy="9.6" r="1" />
          </>
        ) : null}
        {type === "badge" ? (
          <>
            <path d="M12 4.8 18 7v4.6c0 3-1.9 5.6-6 7.6-4.1-2-6-4.6-6-7.6V7z" />
            <path d="m9.9 12.1 1.5 1.6 2.9-3.2" />
          </>
        ) : null}
      </svg>
    </div>
  );
}

function WhyOfficialCard({
  item,
  compact = false,
}: {
  item: WhyOfficialItem;
  compact?: boolean;
}) {
  return (
    <div className={compact ? "px-5 py-6 sm:px-6 sm:py-8" : "px-4 py-8 sm:px-6"}>
      <div className="mx-auto flex w-fit justify-center">
        <WhyOfficialIcon type={item.icon} />
      </div>
      <p className="mt-6 text-[21px] font-semibold tracking-[-0.05em] text-[#16213d] sm:text-[23px] md:mt-8 md:text-[24px] lg:text-[27px]">
        {item.title}
      </p>
      <p className="mt-4 whitespace-pre-line text-[15px] leading-[1.72] text-[#68758d] sm:text-[16px] md:mt-5 lg:text-[17px]">
        {item.description}
      </p>
    </div>
  );
}

export function WhyOfficialCarousel({
  items,
  label,
}: {
  items: readonly WhyOfficialItem[];
  label: string;
}) {
  const scrollerRef = useRef<HTMLDivElement>(null);
  const rollingItems = [...items, ...items];

  useEffect(() => {
    const scroller = scrollerRef.current;

    if (!scroller || items.length < 2 || window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
      return;
    }

    let isInteracting = false;
    let resetTimer: number | undefined;

    const getStep = () => {
      const firstSlide = scroller.querySelector<HTMLElement>("[data-why-slide]");
      const gap = Number.parseFloat(window.getComputedStyle(scroller).columnGap) || 0;
      return firstSlide ? firstSlide.getBoundingClientRect().width + gap : 0;
    };

    const advance = () => {
      if (isInteracting || document.hidden) {
        return;
      }

      const step = getStep();

      if (!step) {
        return;
      }

      const currentIndex = Math.round(scroller.scrollLeft / step);
      const nextIndex = currentIndex >= items.length ? 1 : currentIndex + 1;

      if (currentIndex >= items.length) {
        scroller.scrollTo({ behavior: "auto", left: 0 });
      }

      scroller.scrollTo({ behavior: "smooth", left: nextIndex * step });

      if (nextIndex === items.length) {
        window.clearTimeout(resetTimer);
        resetTimer = window.setTimeout(() => {
          scroller.scrollTo({ behavior: "auto", left: 0 });
        }, 700);
      }
    };

    const pause = () => {
      isInteracting = true;
    };
    const resume = () => {
      isInteracting = false;
    };

    const interval = window.setInterval(advance, 3000);
    scroller.addEventListener("pointerdown", pause);
    scroller.addEventListener("pointerup", resume);
    scroller.addEventListener("pointercancel", resume);
    scroller.addEventListener("mouseenter", pause);
    scroller.addEventListener("mouseleave", resume);
    scroller.addEventListener("focusin", pause);
    scroller.addEventListener("focusout", resume);

    return () => {
      window.clearInterval(interval);
      window.clearTimeout(resetTimer);
      scroller.removeEventListener("pointerdown", pause);
      scroller.removeEventListener("pointerup", resume);
      scroller.removeEventListener("pointercancel", resume);
      scroller.removeEventListener("mouseenter", pause);
      scroller.removeEventListener("mouseleave", resume);
      scroller.removeEventListener("focusin", pause);
      scroller.removeEventListener("focusout", resume);
    };
  }, [items.length]);

  return (
    <div className="mt-10 sm:mt-14 md:mt-16">
      <div
        ref={scrollerRef}
        aria-label={label}
        aria-roledescription="carousel"
        className="-mx-4 flex snap-x snap-mandatory gap-4 overflow-x-auto px-4 pb-2 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden sm:-mx-8 sm:px-8 md:hidden"
        data-why-carousel
        role="region"
        tabIndex={0}
      >
        {rollingItems.map((item, index) => (
          <div
            key={`${item.title}-${index}`}
            aria-hidden={index >= items.length}
            className="fade-up shrink-0 basis-[calc(100%-42px)] snap-start border-r border-[#e5ebf6] sm:basis-[calc(50%-8px)]"
            data-why-slide
            style={{ animationDelay: `${120 + (index % items.length) * 80}ms` }}
          >
            <WhyOfficialCard compact item={item} />
          </div>
        ))}
      </div>

      <div className="hidden grid-cols-3 md:grid" data-why-grid>
        {items.map((item, index) => (
          <div
            key={item.title}
            className={`fade-up min-w-0 ${index > 0 ? "border-l border-[#edf1fa]" : ""}`}
            style={{ animationDelay: `${120 + index * 80}ms` }}
          >
            <WhyOfficialCard item={item} />
          </div>
        ))}
      </div>
    </div>
  );
}
