import React, { useState, useEffect, useRef } from "react";
import { motion, AnimatePresence } from "framer-motion";
import { Element } from "react-scroll";
import { useTranslation } from "react-i18next";
import "../../../index.css";

import companyLogo from "../../../assets/REXNT.png";

const createStars = (count, config = {}) => 
  Array.from({ length: count }).map((_, i) => ({
    id: i,
    x: Math.random() * 100,
    y: Math.random() * 100,
    size: Math.random() * (config.maxSize || 3) + (config.minSize || 1),
    opacity: Math.random() * (config.maxOpacity || 0.8) + (config.minOpacity || 0.2),
    duration: Math.random() * (config.maxDuration || 10) + (config.minDuration || 5),
    delay: Math.random() * (config.maxDelay || 2),
  }));

const Home = () => {
  const { t } = useTranslation();
  const [showLogo, setShowLogo] = useState(false);
  const [showTagline, setShowTagline] = useState(false);
  const [scrollProgress, setScrollProgress] = useState(0);
  const homeRef = useRef(null);

  const stars = createStars(120);
  const backgroundStars = createStars(80, {
    minSize: 0.5,
    maxSize: 2,
    minOpacity: 0.1,
    maxOpacity: 0.5,
  });

  useEffect(() => {
    const logoTimeout = setTimeout(() => setShowLogo(true), 500);
    const taglineTimeout = setTimeout(() => setShowTagline(true), 1500);

    const handleScroll = () => {
      if (homeRef.current) {
        const scrollPosition = window.scrollY;
        const windowHeight = window.innerHeight;
        const progress = Math.min(scrollPosition / (windowHeight * 0.2), 1);
        setScrollProgress(progress);
      }
    };

    window.addEventListener("scroll", handleScroll);
    
    return () => {
      clearTimeout(logoTimeout);
      clearTimeout(taglineTimeout);
      window.removeEventListener("scroll", handleScroll);
    };
  }, []);

  const AnimatedStars = () => (
    <>
      {stars.map((star) => (
        <motion.div
          key={`star-${star.id}`}
          className="absolute rounded-full bg-white"
          style={{
            left: `${star.x}%`,
            top: `${star.y}%`,
            width: star.size,
            height: star.size,
            opacity: star.opacity,
          }}
          animate={{
            opacity: [star.opacity, star.opacity * 0.3, star.opacity],
            y: star.y - (scrollProgress * 10),
          }}
          transition={{
            duration: star.duration,
            delay: star.delay,
            repeat: Infinity,
            repeatType: "reverse",
          }}
        />
      ))}
    </>
  );

  const StaticStars = () => (
    <>
      {backgroundStars.map((star) => (
        <div
          key={`bg-star-${star.id}`}
          className="absolute rounded-full bg-white"
          style={{
            left: `${star.x}%`,
            top: `${star.y}%`,
            width: star.size,
            height: star.size,
            opacity: star.opacity,
          }}
        />
      ))}
    </>
  );

  return (
    <Element name="home" ref={homeRef}>
      <div className="fixed inset-0 -z-10 overflow-hidden">
        <div className="absolute inset-0 bg-gradient-to-b from-[#080613] via-[#12143b] to-[#080613]">
          <StaticStars />
        </div>
      </div>

      <div className="relative min-h-screen w-full overflow-hidden" dir="rtl">
        <div className="absolute inset-0 z-0">
          <AnimatedStars />
          
          <motion.div
            className="absolute inset-0"
            animate={{
              background: [
                "radial-gradient(circle at 30% 50%, rgba(63, 68, 106, 0.2) 0%, transparent 50%)",
                "radial-gradient(circle at 70% 50%, rgba(54, 57, 163, 0.3) 0%, transparent 50%)",
                "radial-gradient(circle at 30% 50%, rgba(63, 68, 106, 0.2) 0%, transparent 50%)",
              ],
            }}
            transition={{
              duration: 20,
              repeat: Infinity,
              repeatType: "reverse",
            }}
          />
        </div>

        <div className="absolute inset-0 overflow-hidden">
          <motion.div
            className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-[800px] h-[800px] rounded-full"
            animate={{
              background: [
                "radial-gradient(circle, rgba(87, 97, 221, 0.15) 0%, transparent 70%)",
                "radial-gradient(circle, rgba(54, 57, 163, 0.2) 0%, transparent 70%)",
                "radial-gradient(circle, rgba(87, 97, 221, 0.15) 0%, transparent 70%)",
              ],
            }}
            transition={{
              duration: 10,
              repeat: Infinity,
              repeatType: "reverse",
            }}
          />
        </div>

        <div className="relative z-10 min-h-screen flex flex-col items-center justify-center px-4">
          <AnimatePresence>
            {showLogo && (
              <motion.div
                initial={{ opacity: 0, y: 50, scale: 0.9 }}
                animate={{ opacity: 1, y: 0, scale: 1 }}
                transition={{
                  duration: 1.2,
                  type: "spring",
                  damping: 20,
                }}
                className="relative mb-2"
              >
                <div className="relative">
                  <motion.img
                    src={companyLogo}
                    alt="Company Logo"
                    className="w-auto max-w-[280px] md:max-w-[400px] lg:max-w-[400px] h-auto"
                    whileHover={{ scale: 1.03 }}
                    transition={{ type: "spring", stiffness: 300 }}
                  />
                  <motion.div
                    className="absolute inset-0 -z-10 blur-2xl opacity-40"
                    style={{
                      background: "linear-gradient(135deg, #5761dd 0%, #3639a3 50%, #3f446a 100%)",
                    }}
                    animate={{
                      scale: [1, 1.05, 1],
                      opacity: [0.3, 0.5, 0.3],
                    }}
                    transition={{
                      duration: 4,
                      repeat: Infinity,
                      repeatType: "reverse",
                    }}
                  />
                </div>
              </motion.div>
            )}
          </AnimatePresence>

          <AnimatePresence>
            {showTagline && (
              <motion.div
                initial={{ opacity: 0, y: 30 }}
                animate={{ opacity: 1, y: 0 }}
                transition={{
                  duration: 1,
                  delay: 0.8,
                }}
                className="text-center max-w-4xl mx-auto"
              >
                <motion.div
                  className="text-xl md:text-2xl lg:text-2xl font-bold text-white mb-4 leading-relaxed"
                  animate={{
                    opacity: [0.9, 1, 0.9],
                  }}
                  transition={{
                    duration: 4,
                    repeat: Infinity,
                    repeatType: "reverse",
                  }}
                >
                  <h2 className="mb-4 text-2xl md:text-3xl">
                    شريكك الهندسي والتقني الرائد
                  </h2>
                  <p className="mb-3">
                    في تنفيذ وإدارة المشاريع الصناعية والسكنية والنفطية
                  </p>
                  <p>
                    والمساهمة في تطوير البنية التحتية والقطاعات الإنتاجية
                    <span className="block mt-3 text-xl md:text-2xl">
                      عبر حلول حديثة ومستدامة
                    </span>
                  </p>
                </motion.div>
                
                <motion.div
                  className="w-48 h-1 mx-auto bg-gradient-to-r from-transparent via-[#5761dd] via-[#3639a3] to-transparent mt-6"
                  animate={{
                    scaleX: [0.5, 1, 0.5],
                  }}
                  transition={{
                    duration: 3,
                    repeat: Infinity,
                    repeatType: "reverse",
                  }}
                />
              </motion.div>
            )}
          </AnimatePresence>
        </div>

        <motion.div
          className="absolute inset-0 pointer-events-none"
          style={{
            background: `radial-gradient(circle at ${scrollProgress * 100}% ${50 + scrollProgress * 20}%, rgba(87, 97, 221, 0.1) 0%, transparent 50%)`,
          }}
        />
      </div>
    </Element>
  );
};

export default Home;