'use client';

import { usePathname } from "next/navigation";
import Image from "next/image";
import clsx from "clsx";
import HorizontalScrollView from "@/components/listview/HorizontalScrollView";
import CategoryItemRenderer from "@/components/listview/CategoryItemRenderer";
import CategorySmallItemRenderer from "@/components/listview/CategorySmallItemRenderer";
import { Category } from "@/app/[name]/(Main)/types/Types";

const SVG_MASK_STYLE = {
  maskSize: "contain",
  maskRepeat: "no-repeat",
  maskPosition: "center",
  WebkitMaskSize: "contain",
  WebkitMaskRepeat: "no-repeat",
  WebkitMaskPosition: "center",
} as const;

function CategoryImage({
  src,
  size,
  alt,
  proxyBase,
}: {
  src: string;
  size: number;
  alt: string;
  proxyBase: string | null;
}) {
  const isSvg = src.endsWith(".svg");

  if (isSvg) {
    const isSameOrigin =
      src.startsWith("/") ||
      (typeof window !== "undefined" &&
        new URL(src, window.location.href).origin === window.location.origin);

    const maskUrl = isSameOrigin
      ? src
      : proxyBase
        ? `${proxyBase}/api/proxy-svg?url=${encodeURIComponent(src)}`
        : null;

    if (maskUrl) {
      return (
        <div
          className="shrink-0 bg-primary"
          style={{
            width: size,
            height: size,
            maskImage: `url(${maskUrl})`,
            WebkitMaskImage: `url(${maskUrl})`,
            ...SVG_MASK_STYLE,
          }}
          role="img"
          aria-label={alt}
        />
      );
    }

    return (
      // eslint-disable-next-line @next/next/no-img-element
      <img
        src={src}
        width={size}
        height={size}
        alt={alt}
        className="shrink-0 object-contain"
      />
    );
  }

  return (
    <Image priority src={src} width={size} height={size} alt={alt} />
  );
}

type Variant = "large" | "small";

const variantConfig: Record<
  Variant,
  {
    renderer: typeof CategoryItemRenderer;
    imageSize: number;
  }
> = {
  large: {
    renderer: CategoryItemRenderer,
    imageSize: 32,
  },
  small: {
    renderer: CategorySmallItemRenderer,
    imageSize: 24,
  },
};

type Props = {
  categories: Category[];
  selectedCategory: string;
  onSelect: (categoryId: string) => void;
  variant?: Variant;
  className?: string;
};

const CategoryScroll = ({
  categories,
  selectedCategory,
  onSelect,
  variant = "large",
  className,
}: Props) => {
  const segment = usePathname()?.split("/").filter(Boolean)[0];
  const proxyBase = segment != null ? `/${segment}` : null;
  const { renderer: Renderer, imageSize } = variantConfig[variant];

  const handleSelect = (categoryId: string) => () => onSelect(categoryId);

  return (
    <HorizontalScrollView
      className={clsx(
        "w-full noscrollbar py-4!",
        variant === "large" && "mt-4!",
        className
      )}
    >
      {/* <Renderer
        key="all"
        className={clsx(selectedCategory === "0" && "bg-container!")}
        onClick={handleSelect(0)}
      >
        <Image
          priority
          src="/assets/images/food-image.png"
          width={imageSize}
          height={imageSize}
          alt="category image"
        />
        <span className="text-xs text-foreground">همه</span>
      </Renderer> */}
      {categories.map((item) => {
        const isSelected = item.id === selectedCategory;

        return (
          <Renderer
            key={item.id}
            className={clsx(isSelected && "bg-container!")}
            onClick={handleSelect(item.id)}
          >
            <CategoryImage
              src={item.avatarUrl || "/assets/images/food-image.png"}
              size={imageSize}
              alt="category image"
              proxyBase={proxyBase}
            />
            <span className="text-xs text-foreground text-center">{item.title}</span>
          </Renderer>
        );
      })}
    </HorizontalScrollView>
  );
};

export default CategoryScroll;

