// export default Promotion;

import React, { useEffect, useState, useRef } from 'react';
import './Promotion.css';

const Promotion = () => {
  const [promotions, setPromotions] = useState([]);
  const [loading, setLoading] = useState(true);

  const [promoIndex, setPromoIndex] = useState(0);
  const promoTimerRef = useRef(null);

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

  useEffect(() => {
    if (promotions.length === 0) return;
    clearInterval(promoTimerRef.current);
    promoTimerRef.current = setInterval(() => {
      setPromoIndex(prev => (prev + 1) % promotions.length);
    }, 5000);
    return () => clearInterval(promoTimerRef.current);
  }, [promotions]);

  const fetchData = async () => {
    try {
      // ✅ 获取促销活动列表（新接口）
      const promoResponse = await fetch(`/seeds/promotions`);
      const promoJson = await promoResponse.json();
      console.log('接口返回数据:', promoJson);
      const promoData = Array.isArray(promoJson?.result) ? promoJson.result : [];
      setPromotions(promoData);
    } catch (error) {
      console.error('获取促销活动失败:', error);
    } finally {
      setLoading(false);
    }
  };

  if (loading) {
    return <div className="promotion-container">加载中...</div>;
  }

  const prevPromo = () => setPromoIndex((promoIndex - 1 + promotions.length) % promotions.length);
  const nextPromo = () => setPromoIndex((promoIndex + 1) % promotions.length);
  const currentPromo = promotions[promoIndex];

  return (
    <div className="promotion-container carousel-container">
      {/* 促销活动轮播 */}
      <section className="carousel-section">
        <h2>当前促销活动</h2>
        {promotions.length === 0 || !currentPromo ? (
          <div className="empty-state">暂无促销活动</div>
        ) : (
          <div
            className="carousel"
            onMouseEnter={() => clearInterval(promoTimerRef.current)}
            onMouseLeave={() => {
              promoTimerRef.current = setInterval(() => {
                setPromoIndex(prev => (prev + 1) % promotions.length);
              }, 3000);
            }}
          >
            <button className="arrow left" onClick={prevPromo}>&lt;</button>
            <div className="slide">
              <div><strong>促销名称：</strong>{currentPromo?.name ?? '未知'}</div>
              <div><strong>促销时间：</strong>
                {currentPromo?.pStartTime && currentPromo?.pEndTime
                  ? `${new Date(currentPromo.pStartTime).toLocaleString()} ～ ${new Date(currentPromo.pEndTime).toLocaleString()}`
                  : '未知'}
              </div>
              <div><strong>上传奖励系数：</strong>{currentPromo?.uploadCoeff ?? '无'}</div>
              <div><strong>下载折扣系数：</strong>{currentPromo?.downloadCoeff ?? '无'}</div>
              {currentPromo?.description && (
                <div><strong>描述：</strong>{currentPromo.description}</div>
              )}
            </div>
            <button className="arrow right" onClick={nextPromo}>&gt;</button>
          </div>
        )}
      </section>
    </div>
  );
};

export default Promotion;

