'use client';

import IconFont from '@/components/ui/iconFont';
import { cn } from '@/lib/utils';
import React, { useCallback, useEffect, useRef } from 'react';

type ScrollBoxProps = {
  children: React.ReactNode;
  contentClassName?: string; // 内容容器的样式类名
} & React.HTMLAttributes<HTMLDivElement>;

export default function ScrollBox(props: ScrollBoxProps) {
  const { children, contentClassName, ...rest } = props;
  const containerRef = useRef<HTMLDivElement>(null);
  const leftRef = useRef<HTMLSpanElement>(null);
  const rightRef = useRef<HTMLSpanElement>(null);

  const handleScroll = useCallback(() => {
    const container = containerRef.current;
    if (!container) return;
    const left = leftRef.current;
    const right = rightRef.current;
    if (!left || !right) return;
    if (container.scrollLeft <= 0) {
      left.style.display = 'none';
    } else {
      left.style.display = 'flex';
    }
    // 添加 1 像素的容差来处理浮点数精度问题
    const isAtEnd = container.scrollLeft + container.clientWidth >= container.scrollWidth - 1;
    if (isAtEnd) {
      right.style.display = 'none';
    } else {
      right.style.display = 'flex';
    }
  }, []);

  useEffect(() => {
    handleScroll();
  }, [handleScroll]);

  const scrollBy = (type: 'left' | 'right') => {
    const container = containerRef.current;
    if (!container) return;
    container.scrollBy({
      left: type === 'left' ? -container.clientWidth * 0.8 : container.clientWidth * 0.8,
      behavior: 'smooth',
    });
  };

  const iconClass =
    'rounded-full absolute h-8 w-8 sm:h-12 sm:w-12 cursor-pointer items-center justify-center z-10';
  const iconStyle: React.CSSProperties = {
    background: 'var(--sys-color-surface-element-normal, rgba(251, 222, 255, 0.08))',
    backdropFilter: 'blur(var(--sys-visualstyle-blur-s, 16px))',
    top: '50%',
    transform: 'translateY(-50%)',
  };

  return (
    <div className={cn('w-full max-w-full min-w-0 relative', rest.className)}>
      <div
        ref={containerRef}
        onScroll={handleScroll}
        className={cn(
          'w-full max-w-full min-w-0 overflow-x-auto overflow-y-hidden',
          contentClassName
        )}
      >
        {children}
      </div>

      {/* 左箭头 */}
      <span
        ref={leftRef}
        className={cn(iconClass, '-left-4 sm:-left-6')}
        style={iconStyle}
        onClick={() => scrollBy('left')}
      >
        <IconFont type="icon-a-Frame194" className="sm:text-2xl" />
      </span>

      {/* 右箭头 */}
      <span
        ref={rightRef}
        className={cn(iconClass, '-right-4 sm:-right-6')}
        style={iconStyle}
        onClick={() => scrollBy('right')}
      >
        <IconFont type="icon-a-Frame195" className="sm:text-2xl" />
      </span>
    </div>
  );
}
