'use client';

import React, { useEffect, useState } from 'react';
import { motion, AnimatePresence } from 'framer-motion';

const PRELOAD_VIDEOS = [
  '/assets/videos/web/hero-bohrung.mp4'
];

export function InitialLoader({ shouldShowLoader = true }: { shouldShowLoader?: boolean }) {
  const [isLoading, setIsLoading] = useState(shouldShowLoader);

  useEffect(() => {
    if (!shouldShowLoader) return;
    
    // Fallback Timeout (4 Sekunden), falls Videos hängen
    const timeout = setTimeout(() => {
      finishLoading();
    }, 4000);

    let videosLoaded = 0;
    
    const checkAllLoaded = () => {
      videosLoaded++;
      if (videosLoaded === PRELOAD_VIDEOS.length) {
        clearTimeout(timeout);
        // Kleine Verzögerung für die smootheness
        setTimeout(finishLoading, 800);
      }
    };

    PRELOAD_VIDEOS.forEach((src) => {
      const video = document.createElement('video');
      video.preload = 'auto';
      video.oncanplaythrough = checkAllLoaded;
      video.onerror = checkAllLoaded; // bei Fehler trotzdem weitermachen
      video.src = src;
      video.load();
    });

    // Cleanup
    return () => clearTimeout(timeout);
  }, [shouldShowLoader]);

  const finishLoading = () => {
    // Set a session cookie so the server knows not to render the loader again
    document.cookie = "etib_initial_load=true; path=/; samesite=lax";
    setIsLoading(false);
  };

  // Wenn wir serverseitig rendern und es nicht zeigen sollen, return null
  if (!shouldShowLoader) return null;

  return (
    <AnimatePresence>
      {isLoading && (
        <motion.div
          key="initial-loader"
          initial={{ y: 0 }}
          exit={{ y: '-100%' }}
          transition={{ duration: 1.2, ease: [0.16, 1, 0.3, 1], delay: 0.2 }}
          className="fixed inset-0 z-[9999] bg-neutral-dark flex flex-col items-center justify-center overflow-hidden"
        >
          {/* E-TIB Premium Glow */}
          <div className="absolute inset-0 bg-[radial-gradient(circle_at_center,_var(--tw-gradient-stops))] from-primary/20 via-transparent to-transparent opacity-60" />
          
          <motion.div 
            initial={{ opacity: 0, scale: 0.95 }}
            animate={{ opacity: 1, scale: 1 }}
            transition={{ duration: 0.8, ease: "easeOut" }}
            className="relative z-10 flex flex-col items-center"
          >
            {/* Minimalistisches Logo oder Loader */}
            <div className="w-24 h-24 relative mb-8">
              <motion.div 
                className="absolute inset-0 border-2 border-primary/20 rounded-xl"
                animate={{ rotate: 360 }}
                transition={{ duration: 8, ease: "linear", repeat: Infinity }}
              />
              <motion.div 
                className="absolute inset-2 border-2 border-accent/40 rounded-lg"
                animate={{ rotate: -360 }}
                transition={{ duration: 6, ease: "linear", repeat: Infinity }}
              />
              <motion.div 
                className="absolute inset-4 border-2 border-white rounded-md bg-white/5 backdrop-blur-sm flex items-center justify-center"
              >
                <span className="text-white font-bold text-xl tracking-tighter">E-TIB</span>
              </motion.div>
            </div>
            
            <motion.div 
              initial={{ opacity: 0, y: 10 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.4 }}
              className="h-1 w-48 bg-neutral-800 rounded-full overflow-hidden"
            >
              <motion.div 
                className="h-full bg-primary"
                initial={{ width: "0%" }}
                animate={{ width: "100%" }}
                transition={{ duration: 3.5, ease: [0.16, 1, 0.3, 1] }}
              />
            </motion.div>
            <motion.p 
              initial={{ opacity: 0 }}
              animate={{ opacity: 1 }}
              transition={{ delay: 0.6 }}
              className="mt-4 text-xs text-neutral-400 font-mono tracking-widest uppercase"
            >
              Loading Infrastructure
            </motion.p>
          </motion.div>
        </motion.div>
      )}
    </AnimatePresence>
  );
}
