import { forwardRef, type HTMLAttributes, type ReactNode } from "react";

import { useHorizontalWheelScroll, type UseHorizontalWheelScrollOptions } from "@/hooks/useHorizontalWheelScroll";
import { mergeRefs } from "@/utils/mergeRefs";

export type HorizontalWheelScrollProps = HTMLAttributes<HTMLDivElement> & UseHorizontalWheelScrollOptions;

/** 横向滚动容器：滚轮垂直滑动转为左右滚动 */
export const HorizontalWheelScroll = forwardRef<HTMLDivElement, HorizontalWheelScrollProps>(function HorizontalWheelScroll(
  { enabled, ignoreWithin, className, children, ...rest },
  forwardedRef,
) {
  const wheelRef = useHorizontalWheelScroll<HTMLDivElement>({ enabled, ignoreWithin });

  return (
    <div ref={mergeRefs(wheelRef, forwardedRef)} className={className} {...rest}>
      {children}
    </div>
  );
});

export type HorizontalWheelScrollRowProps = Omit<HTMLAttributes<HTMLDivElement>, "children"> &
  UseHorizontalWheelScrollOptions & {
    leading?: ReactNode;
    scrollClassName?: string;
    scrollProps?: HTMLAttributes<HTMLDivElement>;
    children?: ReactNode;
  };

/** 左侧固定 + 右侧横向滚动（滚轮可左右滑） */
export const HorizontalWheelScrollRow = forwardRef<HTMLDivElement, HorizontalWheelScrollRowProps>(function HorizontalWheelScrollRow(
  { leading, scrollClassName, scrollProps, className, children, enabled, ignoreWithin, ...rest },
  forwardedRef,
) {
  const wheelRef = useHorizontalWheelScroll<HTMLDivElement>({ enabled, ignoreWithin });
  const { className: scrollExtraClassName, ...scrollRest } = scrollProps ?? {};

  return (
    <div className={className} {...rest}>
      {leading}
      <div
        ref={mergeRefs(wheelRef, forwardedRef)}
        className={classNames(scrollClassName, scrollExtraClassName)}
        {...scrollRest}
      >
        {children}
      </div>
    </div>
  );
});
