import React, { useEffect, useRef, useState } from 'react';
import { motion, useScroll, useTransform, AnimatePresence } from 'framer-motion';
import Navigation from './components/Navigation';
import HeroSection from './components/HeroSection';
import ProductSection from './components/ProductSection';
import TeamSection from './components/TeamSection';
import CaseSection from './components/CaseSection';
import ContactSection from './components/ContactSection';
import './App.css';

const App = () => {
  const containerRef = useRef(null);
  const [currentSection, setCurrentSection] = useState(0);
  const [isScrolling, setIsScrolling] = useState(false);
  const isScrollingRef = useRef(false);
  const currentSectionRef = useRef(0);
  const isTouchInDetailPanelRef = useRef(false);

  const isEventFromDetailPanel = (target) => {
    if (!target) return false;
    if (typeof target.closest === 'function') {
      return !!(target.closest('.team-detail-panel') || target.closest('.detail-scroller'));
    }
    return false;
  };
  
  const { scrollYProgress } = useScroll({
    target: containerRef,
    offset: ["start start", "end start"]
  });

  const sections = [
    { id: 'hero', component: HeroSection, title: '发现新视界', subtitle: 'Discover New Horizons' },
    { id: 'product', component: ProductSection, title: 'AI产品', subtitle: 'AI hardware, AI solution' },
    { id: 'team', component: TeamSection, title: '专业团队', subtitle: 'Expert Team' },
    { id: 'cases', component: CaseSection, title: '成功案例', subtitle: 'Success Stories' },
    { id: 'contact', component: ContactSection, title: '联系我们', subtitle: 'Get In Touch' }
  ];

  // 同步 ref 值
  useEffect(() => {
    isScrollingRef.current = isScrolling;
    currentSectionRef.current = currentSection;
  }, [isScrolling, currentSection]);

  useEffect(() => {
    let timeout;
    let touchStartY = 0;
    let touchEndY = 0;
    
    const handleWheel = (e) => {
      if (isEventFromDetailPanel(e.target)) {
        return;
      }
      e.preventDefault();
      
      // 如果正在滚动中，忽略新的滚动事件
      if (isScrollingRef.current) {
        return;
      }
      
      // 设置滚动状态
      isScrollingRef.current = true;
      setIsScrolling(true);
      
      // 计算新的section索引
      let newSection = currentSectionRef.current;
      if (e.deltaY > 0 && currentSectionRef.current < sections.length - 1) {
        newSection = currentSectionRef.current + 1;
      } else if (e.deltaY < 0 && currentSectionRef.current > 0) {
        newSection = currentSectionRef.current - 1;
      }
      
      // 如果section有变化，更新状态
      if (newSection !== currentSectionRef.current) {
        setCurrentSection(newSection);
      }
      
      // 清除之前的超时
      if (timeout) {
        clearTimeout(timeout);
      }
      
      // 设置超时来重置滚动状态
      timeout = setTimeout(() => {
        isScrollingRef.current = false;
        setIsScrolling(false);
      }, 1200); // 增加到1.2秒，与动画时间匹配
    };

    // 触摸事件处理
    const handleTouchStart = (e) => {
      isTouchInDetailPanelRef.current = isEventFromDetailPanel(e.target);
      touchStartY = e.touches[0].clientY;
    };

    const handleTouchMove = (e) => {
      if (isTouchInDetailPanelRef.current) {
        return;
      }
      e.preventDefault();
    };

    const handleTouchEnd = (e) => {
      if (isTouchInDetailPanelRef.current) {
        isTouchInDetailPanelRef.current = false;
        return;
      }
      if (isScrollingRef.current) {
        return;
      }

      touchEndY = e.changedTouches[0].clientY;
      const deltaY = touchStartY - touchEndY;
      const minSwipeDistance = 50; // 最小滑动距离

      if (Math.abs(deltaY) > minSwipeDistance) {
        isScrollingRef.current = true;
        setIsScrolling(true);

        let newSection = currentSectionRef.current;
        if (deltaY > 0 && currentSectionRef.current < sections.length - 1) {
          // 向上滑动，下一页
          newSection = currentSectionRef.current + 1;
        } else if (deltaY < 0 && currentSectionRef.current > 0) {
          // 向下滑动，上一页
          newSection = currentSectionRef.current - 1;
        }

        if (newSection !== currentSectionRef.current) {
          setCurrentSection(newSection);
        }

        if (timeout) {
          clearTimeout(timeout);
        }

        timeout = setTimeout(() => {
          isScrollingRef.current = false;
          setIsScrolling(false);
        }, 1200);
      }
    };

    const container = containerRef.current;
    if (container) {
      container.addEventListener('wheel', handleWheel, { passive: false });
      container.addEventListener('touchstart', handleTouchStart, { passive: true });
      container.addEventListener('touchmove', handleTouchMove, { passive: false });
      container.addEventListener('touchend', handleTouchEnd, { passive: true });
    }

    return () => {
      if (container) {
        container.removeEventListener('wheel', handleWheel);
        container.removeEventListener('touchstart', handleTouchStart);
        container.removeEventListener('touchmove', handleTouchMove);
        container.removeEventListener('touchend', handleTouchEnd);
      }
      if (timeout) {
        clearTimeout(timeout);
      }
    };
  }, [sections.length]);

  const backgroundOpacity = useTransform(scrollYProgress, [0, 1], [1, 0.3]);
  const scale = useTransform(scrollYProgress, [0, 1], [1, 1.2]);

  return (
    <div className="app" ref={containerRef}>
      <Navigation 
        currentSection={currentSection} 
        sections={sections} 
        onSectionChange={setCurrentSection}
      />
      
      <motion.div 
        className="background-gradient"
        style={{ opacity: backgroundOpacity, scale }}
      />
      
      <div className="sections-container">
        <AnimatePresence mode="wait">
          {sections.map((section, index) => {
            const Component = section.component;
            const isActive = index === currentSection;
            
            return isActive ? (
              <motion.div
                key={section.id}
                className="section"
                initial={{ opacity: 0, scale: 0.8, rotateX: 15 }}
                animate={{ 
                  opacity: 1, 
                  scale: 1, 
                  rotateX: 0,
                  transition: { 
                    duration: 1.2, 
                    ease: [0.25, 0.1, 0.25, 1],
                    staggerChildren: 0.1
                  }
                }}
                exit={{ 
                  opacity: 0, 
                  scale: 1.1, 
                  rotateX: -15,
                  transition: { duration: 0.8 }
                }}
              >
                <motion.div
                  className="section-title"
                  initial={{ y: 100, opacity: 0 }}
                  animate={{ 
                    y: 0, 
                    opacity: 1,
                    transition: { delay: 0.3, duration: 0.8 }
                  }}
                >
                  <h1>{section.title}</h1>
                  <span className="subtitle">{section.subtitle}</span>
                </motion.div>
                
                <Component sectionIndex={index} isActive={isActive} />
              </motion.div>
            ) : null;
          })}
        </AnimatePresence>
      </div>
      
      <div className="section-indicators">
        {sections.map((_, index) => (
          <motion.div
            key={index}
            className={`indicator ${index === currentSection ? 'active' : ''}`}
            onClick={() => setCurrentSection(index)}
            whileHover={{ scale: 1.2 }}
            whileTap={{ scale: 0.9 }}
          />
        ))}
      </div>
    </div>
  );
};

export default App;
