"use client";

import { motion } from "framer-motion";
import { useState, useEffect, useRef } from "react";
import styles from "./Loader.module.css";

interface LoaderProps {
  onLoaded: () => void;
}

interface Particle {
  left: string;
  top: string;
}

interface Shape {
  left: string;
  top: string;
  width: string;
  height: string;
  borderRadius: string;
}

/** ============================
 *  🔎 DEBUG FLAG & LOG HELPERS
 *  - يتعطّل تلقائيًا في الإنتاج
 *  - يمكن إجبار التفعيل عبر NEXT_PUBLIC_DEBUG
 * ============================ */
const DEBUG_ENV =
  (typeof process !== "undefined" &&
    typeof process.env !== "undefined" &&
    typeof process.env.NEXT_PUBLIC_DEBUG === "string" &&
    process.env.NEXT_PUBLIC_DEBUG.toLowerCase() === "true") ||
  (typeof process !== "undefined" && process.env.NODE_ENV !== "production");

const DEBUG: boolean = DEBUG_ENV;

const dlog = (...args: any[]) => {
  if (DEBUG) console.log("[Loader]", ...args);
};
const dwarn = (...args: any[]) => {
  if (DEBUG) console.warn("[Loader]", ...args);
};
// نُبقي error ظاهر حتى في الإنتاج
const derr = (...args: any[]) => console.error("[Loader]", ...args);

export default function Loader({ onLoaded }: LoaderProps) {
  const [progress, setProgress] = useState(0);
  const [status, setStatus] = useState("Initializing system...");
  const [particles, setParticles] = useState<Particle[]>([]);
  const [shapes, setShapes] = useState<Shape[]>([]);

  // refs لمراقبة اللوجز بدون إعادة الريندر
  const lastStatusRef = useRef(status);
  const lastBucketRef = useRef(0); // progress bucket (كل 10%)

  // 🧩 safe animation data generation
  useEffect(() => {
    if (typeof window === "undefined") return; // skip on SSR

    const genParticles = Array.from({ length: 30 }).map(() => ({
      left: `${Math.random() * 100}%`,
      top: `${Math.random() * 100}%`,
    }));

    const genShapes = Array.from({ length: 6 }).map(() => ({
      left: `${Math.random() * 100}%`,
      top: `${Math.random() * 100}%`,
      width: `${20 + Math.random() * 30}px`,
      height: `${20 + Math.random() * 30}px`,
      borderRadius: Math.random() > 0.5 ? "50%" : "0",
    }));

    setParticles(genParticles);
    setShapes(genShapes);

    dlog(`Particles generated: ${genParticles.length}`);
    dlog(`Shapes generated: ${genShapes.length}`);
  }, []);

  // 🧠 progress simulation (+ debug buckets)
  useEffect(() => {
    const interval = setInterval(() => {
      setProgress((prev) => {
        let next = prev;

        if (prev < 30) {
          if (lastStatusRef.current !== "Loading core modules...") {
            setStatus("Loading core modules...");
            lastStatusRef.current = "Loading core modules...";
            dlog(`Status → "${lastStatusRef.current}"`);
          }
          next = prev + 5;
        } else if (prev < 70) {
          if (lastStatusRef.current !== "Preparing desktop environment...") {
            setStatus("Preparing desktop environment...");
            lastStatusRef.current = "Preparing desktop environment...";
            dlog(`Status → "${lastStatusRef.current}"`);
          }
          next = prev + 3;
        } else if (prev < 95) {
          if (lastStatusRef.current !== "Finalizing user experience...") {
            setStatus("Finalizing user experience...");
            lastStatusRef.current = "Finalizing user experience...";
            dlog(`Status → "${lastStatusRef.current}"`);
          }
          next = prev + 1;
        } else {
          clearInterval(interval);
          if (lastStatusRef.current !== "Ready!") {
            setStatus("Ready!");
            lastStatusRef.current = "Ready!";
            dlog(`Status → "${lastStatusRef.current}"`);
          }
          setTimeout(onLoaded, 500);
          next = 100;
        }

        // log per 10% bucket to avoid spam
        const bucket = Math.floor(next / 10) * 10;
        if (bucket !== lastBucketRef.current) {
          lastBucketRef.current = bucket;
          dlog(`Progress → ${bucket}%`);
        }

        return next;
      });
    }, 150);

    return () => clearInterval(interval);
  }, [onLoaded]);

  // 🎨 motion variants
  const containerVariants = {
    hidden: { opacity: 0 },
    visible: {
      opacity: 1,
      transition: { staggerChildren: 0.1 },
    },
  };

  const itemVariants = {
    hidden: { opacity: 0, y: 20 },
    visible: { opacity: 1, y: 0 },
  };

  const ringVariants = {
    animate: {
      rotate: 360,
      transition: { duration: 20, ease: "linear", repeat: Infinity },
    },
  };

  const particleVariants = {
    animate: {
      x: [0, Math.random() * 200 - 100, 0],
      y: [0, Math.random() * 200 - 100, 0],
      opacity: [0, 1, 0],
      scale: [0.5, 1.5, 0.5],
      transition: {
        duration: 5 + Math.random() * 5,
        repeat: Infinity,
        ease: "easeInOut",
        delay: Math.random() * 2,
      },
    },
  };

  const shapeVariants = {
    animate: {
      rotate: 360,
      x: [0, Math.random() * 100 - 50, 0],
      y: [0, Math.random() * 100 - 50, 0],
      scale: [1, 1.2, 1],
      opacity: [0.8, 0.5, 0.8],
      transition: {
        duration: 10 + Math.random() * 10,
        repeat: Infinity,
        ease: "linear",
        delay: Math.random() * 3,
      },
    },
  };

  return (
    <motion.div
      className={styles.loaderContainer}
      initial="hidden"
      animate="visible"
      variants={containerVariants}
    >
      <div className={styles.gradientBackground} />

      {/* particles */}
      <div className={styles.particlesContainer}>
        {particles.map((p, i) => (
          <motion.div
            key={`p-${i}`}
            className={styles.particle}
            variants={particleVariants}
            animate="animate"
            style={{ left: p.left, top: p.top }}
          />
        ))}
      </div>

      {/* shapes */}
      <div className={styles.shapesContainer}>
        {shapes.map((s, i) => (
          <motion.div
            key={`s-${i}`}
            className={styles.shape}
            variants={shapeVariants}
            animate="animate"
            style={{
              left: s.left,
              top: s.top,
              width: s.width,
              height: s.height,
              borderRadius: s.borderRadius,
            }}
          />
        ))}
      </div>

      {/* logo + rings */}
      <motion.div className={styles.logoWrapper} variants={itemVariants}>
        <motion.div className={styles.outerRing} variants={ringVariants} />
        <motion.div className={styles.innerRing} variants={ringVariants} />
        <motion.div
          className={styles.logo}
          animate={{
            rotateY: [0, 360],
            rotateX: [0, 360],
            scale: [1, 1.05, 1],
            boxShadow: [
              "0 0 10px rgba(0, 191, 255, 0.5)",
              "0 0 20px rgba(0, 191, 255, 0.8)",
              "0 0 10px rgba(0, 191, 255, 0.5)",
            ],
          }}
          transition={{ duration: 5, repeat: Infinity, ease: "easeInOut" }}
        >
          <span className={styles.logoText}>MG</span>
        </motion.div>
      </motion.div>

      {/* progress bar */}
      <motion.div className={styles.progressBarContainer} variants={itemVariants}>
        <div className={styles.progressBar} style={{ width: `${progress}%` }} />
      </motion.div>

      {/* status text */}
      <motion.p className={styles.statusText} variants={itemVariants}>
        {status}
      </motion.p>
    </motion.div>
  );
}
