"use client";

import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import Image from "next/image";
import { playfair as serif } from "@/lib/fonts";
import { AnimatePresence, motion } from "framer-motion";


const CMS_BASE_URL =
  process.env.NEXT_PUBLIC_CMS_BASE_URL?.replace(/\/$/, "") ?? "";

const TRANSITION = {
  duration: 0.8,
  ease: "easeInOut",
} as const;

import {
  type RichTextRoot,
  type RichTextChild,
  renderLexical,
  extractPlainText
} from "../utils";

type MediaSizes = {
  small?: { url?: string | null };
  medium?: { url?: string | null };
  large?: { url?: string | null };
  og?: { url?: string | null };
};

type MediaDocument = {
  url?: string | null;
  alt?: string | null;
  sizes?: MediaSizes | null;
};

type WhyChooseItem = {
  id?: string;
  imageId?: number | null;
  title?: RichTextRoot | string | null;
  body?: RichTextRoot | null;
};

type WhyChooseBlock = {
  type?: string;
  props?: {
    variant?: string | null;
    heading?: RichTextRoot | null;
    items?: WhyChooseItem[];
    meta?: {
      anchorId?: string | null;
    } | null;
  } | null;
};

type ScillyPageData = {
  layout?: WhyChooseBlock[];
  included?: {
    media?: Record<string, MediaDocument>;
  } | null;
};

type Card = {
  id: string;
  title: string;
  description: React.ReactNode;
  image: string | null;
  alt: string;
};

type HeadingSegment = {
  text: string;
  emphasized: boolean;
  format: number;
};

type SlotKey = "-1" | "0" | "1" | "2" | "3";
type SlotPosition = {
  x: number;
  y: number;
  width: number;
  height: number;
  opacity: number;
  zIndex: number;
};

function wrapIndex(index: number, length: number) {
  return (index + length) % length;
}

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

function isWhyChooseBlock(
  block: WhyChooseBlock | undefined,
): block is WhyChooseBlock {
  return (
    block?.type === "contentListV1" && block?.props?.variant === "media-grid"
  );
}

function toAbsoluteUrl(url?: string | null) {
  if (!url) return null;
  if (url.startsWith("http://") || url.startsWith("https://")) return url;
  if (!CMS_BASE_URL || !url.startsWith("/")) return url;
  return `${CMS_BASE_URL}${url}`;
}

function resolvePreferredImageUrl(media: MediaDocument | null) {
  return toAbsoluteUrl(
    media?.sizes?.large?.url ??
    media?.sizes?.medium?.url ??
    media?.sizes?.small?.url ??
    media?.url,
  );
}

function extractHeadingSegments(
  heading?: RichTextRoot | null,
): HeadingSegment[] {
  const firstParagraph = heading?.root?.children?.find(
    (child) => child.type === "paragraph",
  );

  const segments = firstParagraph?.children ?? [];

  return segments
    .map((segment) => ({
      text: segment.text ?? "",
      emphasized: Boolean((segment.format ?? 0) & 2),
      format: segment.format ?? 0,
    }))
    .filter((segment) => segment.text.length > 0);
}

function renderCardTitle(title: string) {

  if (title.includes(" & ")) {
    const parts = title.split(" & ");
    return (
      <>
        <span className="block">{parts[0]}</span>
        <span className="block">& {parts[1]}</span>
      </>
    );
  }


  const words = title.trim().split(/\s+/);
  if (words.length <= 2) {
    return words.map((word, index) => (
      <span key={`${title}-${word}-${index}`} className="block">
        {word}
      </span>
    ));
  }

  return title;
}



export default function WhyChooseSection({ data }: { data: ScillyPageData }) {
  const whyChooseBlock = data.layout?.find(isWhyChooseBlock);
  const [activeIndex, setActiveIndex] = useState(0);
  const [paused, setPaused] = useState(false);
  const [isMobileUserInteracting, setIsMobileUserInteracting] = useState(false);
  const [isAnimating, setIsAnimating] = useState(false);
  const [isInView, setIsInView] = useState(false);
  const [hoveredImage, setHoveredImage] = useState<{ id: string; x: number; y: number } | null>(null);
  const hoverTimerRef = React.useRef<NodeJS.Timeout | null>(null);
  const [carouselWidth, setCarouselWidth] = useState(760);
  const timerRef = useRef<NodeJS.Timeout | null>(null);
  const carouselRef = useRef<HTMLDivElement | null>(null);
  const mobileScrollRef = useRef<HTMLDivElement | null>(null);
  const mobileScrollReleaseRef = useRef<NodeJS.Timeout | null>(null);
  const mobileInteractionTimerRef = useRef<NodeJS.Timeout | null>(null);
  const hasInitialMobileSyncRef = useRef(false);
  const isProgrammaticMobileScrollRef = useRef(false);
  const cardOffsetsRef = useRef<number[]>([]);

  const headingSegments = useMemo(
    () => extractHeadingSegments(whyChooseBlock?.props?.heading),
    [whyChooseBlock?.props?.heading],
  );

  const cards = useMemo<Card[]>(() => {
    let rawItems = whyChooseBlock?.props?.items ?? [];
    if (rawItems.length > 0 && rawItems.length < 5) {
      let duplicated = [...rawItems];
      while (duplicated.length < 5) {
        duplicated = [...duplicated, ...rawItems];
      }
      rawItems = duplicated;
    }

    const mediaMap = data.included?.media ?? {};

    return rawItems
      .map((item, index) => {
        const media =
          item.imageId != null
            ? (mediaMap[String(item.imageId)] ?? null)
            : null;

        return {
          id: `${item.id ?? index}-${index}`,
          title: extractPlainText(item.title),
          description: renderLexical(item.body),
          image: resolvePreferredImageUrl(media),
          alt: media?.alt?.trim() || extractPlainText(item.title) || "",
        };
      })
      .filter(
        (card) => card.title || card.description || card.image || card.alt,
      );
  }, [data.included?.media, whyChooseBlock?.props?.items]);

  const cardCount = cards.length;
  const safeActiveIndex = cardCount > 0 ? wrapIndex(activeIndex, cardCount) : 0;
  const activeCard = cardCount > 0 ? cards[safeActiveIndex] : null;
  const isMobileLayout = carouselWidth < 560;

  const layout = useMemo(() => {
    const width = Math.max(carouselWidth, 280);
    const isMobile = width < 560;

    if (isMobile) {
      const activeSize = clamp(width * 0.78, 220, 280);
      const nextSize = clamp(activeSize * 0.78, 170, 220);
      const activeX = 12;

      return {
        height: activeSize + 36,
        slots: {
          "-1": {
            x: -nextSize - 32,
            y: 0,
            width: nextSize,
            height: nextSize,
            opacity: 0,
            zIndex: 0,
          },
          "0": {
            x: activeX,
            y: 0,
            width: activeSize,
            height: activeSize,
            opacity: 1,
            zIndex: 30,
          },
          "1": {
            x: activeX + activeSize + 16,
            y: 0,
            width: nextSize,
            height: nextSize,
            opacity: 1,
            zIndex: 20,
          },
          "2": {
            x: activeX + activeSize + nextSize + 48,
            y: 0,
            width: nextSize,
            height: nextSize,
            opacity: 0,
            zIndex: 10,
          },
          "3": {
            x: activeX + activeSize + nextSize * 2 + 80,
            y: 0,
            width: nextSize,
            height: nextSize,
            opacity: 0,
            zIndex: 0,
          },
        } satisfies Record<SlotKey, SlotPosition>,
      };
    }



    const scale = width / 760;
    const mainSize = Math.round(250 * scale);
    const smallSize = Math.round(200 * scale);
    const gap1 = Math.round(280 * scale);
    const gap2 = Math.round(500 * scale);

    return {
      height: Math.round(330 * scale),
      slots: {
        "-1": {
          x: Math.round(-260 * scale),
          y: 0,
          width: mainSize,
          height: mainSize,
          opacity: 0,
          zIndex: 0,
        },
        "0": {
          x: 0,
          y: 0,
          width: mainSize,
          height: mainSize,
          opacity: 1,
          zIndex: 30,
        },
        "1": {
          x: gap1,
          y: Math.round(77 * scale),
          width: smallSize,
          height: smallSize,
          opacity: 1,
          zIndex: 20,
        },
        "2": {
          x: gap2,
          y: Math.round(49 * scale),
          width: smallSize,
          height: smallSize,
          opacity: 1,
          zIndex: 10,
        },
        "3": {
          x: width + 28,
          y: Math.round(49 * scale),
          width: smallSize,
          height: smallSize,
          opacity: 0,
          zIndex: 0,
        },
      } satisfies Record<SlotKey, SlotPosition>,
    };
  }, [carouselWidth]);

  const visibleCards = useMemo(() => {
    if (cardCount === 0) return [];

    return [
      {
        card: cards[wrapIndex(activeIndex - 1, cardCount)],
        slot: "-1" as SlotKey,
      },
      {
        card: cards[safeActiveIndex],
        slot: "0" as SlotKey,
      },
      {
        card: cards[wrapIndex(activeIndex + 1, cardCount)],
        slot: "1" as SlotKey,
      },
      {
        card: cards[wrapIndex(activeIndex + 2, cardCount)],
        slot: "2" as SlotKey,
      },
      {
        card: cards[wrapIndex(activeIndex + 3, cardCount)],
        slot: "3" as SlotKey,
      },
    ];
  }, [activeIndex, cardCount, cards, safeActiveIndex]);

  const unlockAfterAnimation = useCallback(() => {
    if (timerRef.current) clearTimeout(timerRef.current);
    timerRef.current = setTimeout(() => {
      setIsAnimating(false);
    }, 850);
  }, []);

  const nextSlide = useCallback(() => {
    if (isAnimating || cardCount === 0) return;
    setIsAnimating(true);
    setActiveIndex((prev) => wrapIndex(prev - 1, cardCount));
    unlockAfterAnimation();
  }, [cardCount, isAnimating, unlockAfterAnimation]);

  const prevSlide = useCallback(() => {
    if (isAnimating || cardCount === 0) return;
    setIsAnimating(true);
    setActiveIndex((prev) => wrapIndex(prev + 1, cardCount));
    unlockAfterAnimation();
  }, [cardCount, isAnimating, unlockAfterAnimation]);

  const refreshCardOffsets = useCallback(() => {
    const node = mobileScrollRef.current;
    if (!node) return;
    cardOffsetsRef.current = Array.from(node.children).map(
      (c) => (c as HTMLElement).offsetLeft,
    );
  }, []);

  const scrollMobileCardIntoView = useCallback(
    (index: number, behavior: ScrollBehavior = "smooth") => {
      const node = mobileScrollRef.current;
      if (!node) return;

      const left = cardOffsetsRef.current[index] ?? 0;

      isProgrammaticMobileScrollRef.current = true;
      if (mobileScrollReleaseRef.current) {
        clearTimeout(mobileScrollReleaseRef.current);
      }

      node.scrollTo({
        left: Math.max(left - 12, 0),
        behavior,
      });

      mobileScrollReleaseRef.current = setTimeout(
        () => {
          isProgrammaticMobileScrollRef.current = false;
        },
        behavior === "smooth" ? 450 : 80,
      );
    },
    [],
  );

  const handleMobileScroll = useCallback(() => {
    const node = mobileScrollRef.current;
    if (!node || isProgrammaticMobileScrollRef.current) return;

    const offsets = cardOffsetsRef.current;
    if (!offsets.length) return;

    const scrollLeft = node.scrollLeft;
    let nearestIndex = 0;
    let smallestDistance = Number.POSITIVE_INFINITY;

    offsets.forEach((offsetLeft, index) => {
      const distance = Math.abs(offsetLeft - 12 - scrollLeft);
      if (distance < smallestDistance) {
        smallestDistance = distance;
        nearestIndex = index;
      }
    });

    setActiveIndex((prev) => (prev === nearestIndex ? prev : nearestIndex));
  }, []);

  const pauseMobileAutoplay = useCallback(() => {
    if (mobileInteractionTimerRef.current) {
      clearTimeout(mobileInteractionTimerRef.current);
    }
    setIsMobileUserInteracting(true);
  }, []);

  const resumeMobileAutoplaySoon = useCallback(() => {
    if (mobileInteractionTimerRef.current) {
      clearTimeout(mobileInteractionTimerRef.current);
    }
    mobileInteractionTimerRef.current = setTimeout(() => {
      setIsMobileUserInteracting(false);
    }, 2200);
  }, []);

  useEffect(() => {
    if (!isInView || paused || isAnimating || isMobileLayout || cardCount <= 1) return;

    const interval = setInterval(() => {
      setIsAnimating(true);
      setActiveIndex((prev) => wrapIndex(prev - 1, cardCount));
      if (timerRef.current) clearTimeout(timerRef.current);
      timerRef.current = setTimeout(() => {
        setIsAnimating(false);
      }, 850);
    }, 2500);

    return () => clearInterval(interval);
  }, [isInView, paused, isAnimating, isMobileLayout, cardCount]);

  useEffect(() => {
    if (!isInView || !isMobileLayout || cardCount <= 1 || isMobileUserInteracting) return;

    const interval = setInterval(() => {
      if (isProgrammaticMobileScrollRef.current) return;

      setActiveIndex((prev) => {
        const nextIndex = wrapIndex(prev - 1, cardCount);
        scrollMobileCardIntoView(nextIndex, "smooth");
        return nextIndex;
      });
    }, 4200);

    return () => clearInterval(interval);
  }, [
    isInView,
    cardCount,
    isMobileLayout,
    isMobileUserInteracting,
    scrollMobileCardIntoView,
  ]);

  useEffect(() => {
    const node = carouselRef.current;
    if (!node) return;
    const observer = new IntersectionObserver(
      ([entry]) => setIsInView(entry.isIntersecting),
      { threshold: 0.1 },
    );
    observer.observe(node);
    return () => observer.disconnect();
  }, []);

  useEffect(() => {
    return () => {
      if (timerRef.current) clearTimeout(timerRef.current);
      if (mobileScrollReleaseRef.current) {
        clearTimeout(mobileScrollReleaseRef.current);
      }
      if (mobileInteractionTimerRef.current) {
        clearTimeout(mobileInteractionTimerRef.current);
      }
    };
  }, []);

  useEffect(() => {
    const node = carouselRef.current;
    if (!node) return;

    const updateWidth = () => {
      setCarouselWidth(node.getBoundingClientRect().width);
      refreshCardOffsets();
    };

    updateWidth();

    if (typeof ResizeObserver === "undefined") {
      window.addEventListener("resize", updateWidth);
      return () => window.removeEventListener("resize", updateWidth);
    }

    const observer = new ResizeObserver(updateWidth);
    observer.observe(node);

    return () => observer.disconnect();
  }, [refreshCardOffsets]);

  useEffect(() => {
    if (!isMobileLayout || cardCount === 0) {
      hasInitialMobileSyncRef.current = false;
      return;
    }

    if (!hasInitialMobileSyncRef.current) {
      refreshCardOffsets();
      scrollMobileCardIntoView(safeActiveIndex, "auto");
      hasInitialMobileSyncRef.current = true;
    }
  }, [cardCount, isMobileLayout, safeActiveIndex, scrollMobileCardIntoView, refreshCardOffsets]);

  if (!whyChooseBlock || cardCount === 0 || !activeCard) {
    return null;
  }

  return (
    <section
      id={whyChooseBlock.props?.meta?.anchorId ?? undefined}
      className="relative w-full overflow-hidden px-4 py-10 sm:px-6 sm:py-12 lg:px-0 lg:pt-[120px] lg:pb-12"
    >
      <div className="mx-auto max-w-[1440px]">
        {headingSegments.length > 0 ? (
          <div className="mx-auto mb-8 flex max-w-[1081px] justify-center sm:mb-10 lg:mb-[60px] lg:px-[60px]">
            <h2 className="w-full text-center leading-tight text-[#85714D] sm:leading-none">
              {headingSegments.map((segment, index) =>
                segment.emphasized ? (
                  <span
                    key={`${segment.text}-${index}`}
                    className="font-snell text-[27px] capitalize leading-none tracking-[2px] text-[#85714D] sm:text-[40px] sm:tracking-[2.5px] md:text-[44px] lg:text-[55px] lg:tracking-[2.75px]"
                    style={{
                      fontFamily: "Snell",
                      fontWeight: 400,
                      fontStyle: "normal",
                      lineHeight: "normal",
                    }}
                  >
                    {segment.text}
                  </span>
                ) : (
                  <span
                    key={`${segment.text}-${index}`}
                    className={`text-[22px] sm:text-[28px] md:text-[32px] lg:text-[40px] ${serif.className} ${segment.format & 1 ? "font-bold" : "font-normal"
                      } ${segment.format & 2 ? "italic" : ""}`}
                  >
                    {segment.text}
                  </span>
                ),
              )}
            </h2>
          </div>
        ) : null}

        <div className="flex flex-col items-stretch gap-6 md:flex-row md:items-start md:justify-between md:px-8 lg:gap-[30px] lg:px-[60px]">
          <div className="min-h-[72px] w-full px-3 text-center md:min-h-[260px] md:max-w-[260px] md:shrink-0 md:pl-4 md:pr-0 md:pt-[70px] md:text-left lg:max-w-[332px] lg:pl-20">
            <AnimatePresence mode="wait">
              <motion.div
                key={activeCard.id}
                initial={{ opacity: 0, y: 12 }}
                animate={{ opacity: 1, y: 0 }}
                exit={{ opacity: 0, y: -12 }}
                transition={{ duration: 0.8, ease: "easeInOut" }}
                className="text-[14px] leading-[24px] text-[#5C5C5C] sm:text-[18px] sm:leading-[30px] md:text-[21px] md:leading-[34px] lg:text-[25px] lg:leading-[40px]"
              >
                {activeCard.description}
              </motion.div>
            </AnimatePresence>
          </div>

          <div
            className="flex w-full flex-1 min-w-0 justify-center md:justify-end"
            onMouseEnter={() => setPaused(true)}
            onMouseLeave={() => setPaused(false)}
          >
            <div ref={carouselRef} className="w-full overflow-hidden lg:max-w-[760px]">
              <div
                ref={mobileScrollRef}
                onScroll={() => {
                  handleMobileScroll();
                  if (!isProgrammaticMobileScrollRef.current) {
                    pauseMobileAutoplay();
                    resumeMobileAutoplaySoon();
                  }
                }}
                onTouchStart={pauseMobileAutoplay}
                onTouchEnd={resumeMobileAutoplaySoon}
                style={{ touchAction: "pan-x pan-y" }}
                className="flex snap-x snap-mandatory gap-4 overflow-x-auto px-3 pb-2 md:hidden overscroll-x-none [scrollbar-width:none] [-ms-overflow-style:none] [-webkit-tap-highlight-color:transparent] [&::-webkit-scrollbar]:hidden"
              >
                {cards.map((card, index) => (
                  <button
                    key={card.id}
                    type="button"
                    aria-label={`View ${card.alt || card.title || `slide ${index + 1}`}`}
                    onClick={() => {
                      pauseMobileAutoplay();
                      setActiveIndex(index);
                      scrollMobileCardIntoView(index);
                      resumeMobileAutoplaySoon();
                    }}
                    className="relative h-[296px] w-[296px] shrink-0 snap-start overflow-hidden rounded-[18px] border-none bg-transparent text-left outline-none ring-0 shadow-none appearance-none [-webkit-tap-highlight-color:transparent]"
                  >
                    {card.image ? (
                      <Image
                        src={card.image}
                        alt={card.alt}
                        fill
                        className="object-cover"
                        sizes="(max-width: 767px) 300px, 300px"
                        loading="lazy"
                      />
                    ) : null}

                    {card.title ? (
                      <div className="absolute bottom-4 right-4 max-w-[132px] text-right text-[15px] font-normal leading-[1.05] tracking-[-0.02em] text-white">
                        {renderCardTitle(card.title)}
                      </div>
                    ) : null}
                  </button>
                ))}
              </div>

              <div
                className="relative hidden overflow-hidden md:block"
                style={{ height: layout.height }}
              >
                {visibleCards.map(({ card, slot }) => {
                  const pos = layout.slots[slot];

                  return (
                    <motion.div
                      key={card.id}
                      initial={{
                        x:
                          slot === "3"
                            ? carouselWidth + 100
                            : slot === "-1"
                              ? -pos.width - 70
                              : pos.x,
                        y: pos.y,
                        width: pos.width,
                        height: pos.height,
                        opacity: pos.opacity,
                      }}
                      animate={{
                        x: pos.x,
                        y: pos.y,
                        width: pos.width,
                        height: pos.height,
                        opacity: pos.opacity,
                      }}
                      transition={TRANSITION}
                      className="absolute border-none outline-none ring-0 shadow-none"
                      style={{
                        zIndex: pos.zIndex,
                        pointerEvents: pos.opacity === 0 ? "none" : "auto",
                      }}
                    >
                      <div
                        className="relative h-full w-full overflow-hidden rounded-[8px]"
                        onMouseMove={(e) => {
                          const r = e.currentTarget.getBoundingClientRect();
                          const x = e.clientX - r.left;
                          const y = e.clientY - r.top;
                          if (hoverTimerRef.current) clearTimeout(hoverTimerRef.current);
                          setHoveredImage((prev) => (prev !== null ? null : prev));
                          hoverTimerRef.current = setTimeout(() => setHoveredImage({ id: card.id, x, y }), 1000);
                        }}
                        onMouseLeave={() => {
                          if (hoverTimerRef.current) clearTimeout(hoverTimerRef.current);
                          setHoveredImage(null);
                        }}
                      >
                        {card.image ? (
                          <Image
                            src={card.image}
                            alt={card.alt}
                            fill
                            className="object-cover"
                            sizes="(max-width: 768px) 100vw, 300px"
                            loading="lazy"
                          />
                        ) : null}

                        {card.title ? (
                          <div className="absolute bottom-[14px] right-[14px] max-w-[160px] text-right text-[15px] font-normal leading-[1.05] tracking-[-0.02em] text-white">
                            {renderCardTitle(card.title)}
                          </div>
                        ) : null}
                      </div>

                      <AnimatePresence>
                        {hoveredImage?.id === card.id && (
                          <motion.div
                            initial={{ opacity: 0, scale: 0.95 }}
                            animate={{ opacity: 1, scale: 1 }}
                            exit={{ opacity: 0, scale: 0.95 }}
                            transition={{ duration: 0.12 }}
                            style={{
                              position: "absolute",
                              left: hoveredImage.x,
                              top: hoveredImage.y,
                              transform: "translate(-50%, calc(-100% - 8px))",
                              pointerEvents: "none",
                              zIndex: 200,
                              whiteSpace: "nowrap",
                            }}
                            className="rounded border border-black bg-white px-3 py-1.5 text-sm font-semibold text-black shadow-sm"
                          >
                            {card.alt}
                          </motion.div>
                        )}
                      </AnimatePresence>
                    </motion.div>
                  );
                })}
              </div>
            </div>
          </div>
        </div>

        {cardCount > 1 ? (
          <div className="mt-4 flex justify-center gap-2 md:hidden">
            {cards.map((card, index) => {
              const isActive = index === safeActiveIndex;

              return (
                <motion.button
                  key={card.id}
                  type="button"
                  aria-label={`Go to slide ${index + 1}`}
                  whileTap={{ scale: 0.8 }}
                  onClick={() => {
                    setActiveIndex(index);
                    scrollMobileCardIntoView(index);
                  }}
                  className={`h-2.5 w-2.5 rounded-full transition-all cursor-pointer ${isActive ? "bg-[#85714D]" : "bg-[#DDD7CF]"
                    }`}
                />
              );
            })}
          </div>
        ) : null}

        {cardCount > 1 ? (
          <div className="mt-2 hidden justify-center gap-6 md:flex md:mt-[28px] md:justify-end md:gap-[24px] md:pr-8 lg:pr-[80px]">
            <motion.button
              type="button"
              aria-label="Previous"
              onClick={prevSlide}
              disabled={isAnimating}
              whileHover={{ scale: 1.1, x: -4 }}
              whileTap={{ scale: 0.9 }}
              className="flex h-[40px] w-[40px] items-center justify-center rounded-full bg-transparent text-[#85714D] transition-colors hover:bg-[#85714D]/10 disabled:pointer-events-none cursor-pointer"
            >
              <svg
                width="34"
                height="18"
                viewBox="0 0 34 18"
                fill="none"
                xmlns="http://www.w3.org/2000/svg"
                aria-hidden="true"
              >
                <path
                  d="M33 9H2M2 9L10 1M2 9L10 17"
                  stroke="currentColor"
                  strokeWidth="1.5"
                  strokeLinecap="square"
                />
              </svg>
            </motion.button>

            <motion.button
              type="button"
              aria-label="Next"
              onClick={nextSlide}
              disabled={isAnimating}
              whileHover={{ scale: 1.1, x: 4 }}
              whileTap={{ scale: 0.9 }}
              className="flex h-[40px] w-[40px] items-center justify-center rounded-full bg-transparent text-[#85714D] transition-colors hover:bg-[#85714D]/10 disabled:pointer-events-none cursor-pointer"
            >
              <svg
                width="34"
                height="18"
                viewBox="0 0 34 18"
                fill="none"
                xmlns="http://www.w3.org/2000/svg"
                aria-hidden="true"
              >
                <path
                  d="M1 9H32M32 9L24 1M32 9L24 17"
                  stroke="currentColor"
                  strokeWidth="1.5"
                  strokeLinecap="square"
                />
              </svg>
            </motion.button>
          </div>
        ) : null}
      </div>
    </section>
  );
}