// ============================================================
// BannerCarousel — 首页顶部轮播图
// 使用 useBannerList() Hook 获取数据，组件仅负责渲染
//
// 关闭行为：
//   - 关闭后当前会话不再显示（组件内 useState 驱动）
//   - 刷新/重启应用 → state 重置 → 重新展示
//   - 不做 localStorage 持久化，确保每次启动都可见
// ============================================================

import { useRef, useMemo, useState } from 'react';
import { Carousel, Skeleton, Button } from 'antd';
import { CloseOutlined } from '@ant-design/icons';
import type { CarouselRef } from 'antd/es/carousel';

import { useBannerList } from '@/shared/hooks/use-api';
import type { Banner } from '@/modules/home/controllers/banner-api';

// ---------- 组件 Props ----------

interface BannerCarouselProps {
   className?: string;
}

// ---------- 组件 ----------

export function BannerCarousel({ className }: BannerCarouselProps) {
   const carouselRef = useRef<CarouselRef>(null);
   const { data: rawBanners, loading } = useBannerList();

   /** 当前会话是否已关闭轮播图（组件卸载即重置，下次启动重新展示） */
   const [dismissed, setDismissed] = useState(false);

   // 过滤 + 排序（纯计算，无副作用）
   const banners = useMemo<Banner[]>(() => {
      if (!rawBanners) return [];
      return rawBanners
         .filter((b) => b.is_active)
         .filter((b) => b.category === 'banner')
         .sort((a, b) => a.sort_order - b.sort_order);
   }, [rawBanners]);

   // 用户已关闭或加载完成但无数据 → 不渲染
   if (dismissed || (!loading && banners.length === 0)) {
      return null;
   }

   // 加载态 — 适配长条比例（2280×90）
   if (loading) {
      return (
         <div className={className} style={{ width: '100%' }}>
            <Skeleton.Input active block style={{ height: 90 }} />
         </div>
      );
   }

   return (
      <div
         className={`banner-carousel ${className ?? ''}`}
         style={{ position: 'relative', width: '100%', overflow: 'hidden', lineHeight: 0 }}
      >
         <Carousel
            ref={carouselRef}
            autoplay
            autoplaySpeed={5000}
            effect="fade"
            pauseOnHover
            adaptiveHeight={true}
            dots={banners.length > 1}
         >
            {banners.map((banner) => (
               <div key={banner.id}>
                  <img
                     src={banner.image_url}
                     alt={banner.title}
                     style={{ width: '100%', height: 'auto', display: 'block' }}
                  />
               </div>
            ))}
         </Carousel>

         {/* 关闭按钮 — 右上角悬浮，半透明底色，hover 加深 */}
         <Button
            type="text"
            size="small"
            icon={<CloseOutlined />}
            onClick={() => setDismissed(true)}
            title="关闭轮播图"
            style={{
               position: 'absolute',
               top: 8,
               right: 8,
               zIndex: 10,
               color: '#fff',
               background: 'rgba(0, 0, 0, 0.35)',
               borderRadius: 4,
               width: 24,
               height: 24,
               display: 'flex',
               alignItems: 'center',
               justifyContent: 'center',
            }}
            onMouseEnter={(e) => {
               (e.currentTarget as HTMLButtonElement).style.background = 'rgba(0, 0, 0, 0.55)';
            }}
            onMouseLeave={(e) => {
               (e.currentTarget as HTMLButtonElement).style.background = 'rgba(0, 0, 0, 0.35)';
            }}
         />
      </div>
   );
}
