// Global Effects Component - Loading, Cursor, Scroll Animations
// Include this in all pages for consistent experience

// ============================================
// LOADING SCREEN
// ============================================
function LoadingScreen() {
  const [isLoading, setIsLoading] = React.useState(true);
  const [progress, setProgress] = React.useState(0);

  React.useEffect(() => {
    // Simulate loading progress
    const interval = setInterval(() => {
      setProgress(prev => {
        if (prev >= 100) {
          clearInterval(interval);
          setTimeout(() => setIsLoading(false), 500);
          return 100;
        }
        return prev + Math.random() * 15;
      });
    }, 100);

    // Fallback - hide after 2.5s max
    const timeout = setTimeout(() => {
      setProgress(100);
      setTimeout(() => setIsLoading(false), 500);
    }, 2500);

    return () => {
      clearInterval(interval);
      clearTimeout(timeout);
    };
  }, []);

  if (!isLoading) return null;

  return (
    <div className={`loading-screen ${progress >= 100 ? 'fade-out' : ''}`}>
      <div className="loading-content">
        <div className="loading-logo">
          <svg viewBox="0 0 100 100" className="loading-circle">
            <circle cx="50" cy="50" r="45" className="circle-bg" />
            <circle
              cx="50"
              cy="50"
              r="45"
              className="circle-progress"
              style={{ strokeDashoffset: 283 - (283 * Math.min(progress, 100)) / 100 }}
            />
          </svg>
          <span className="loading-text">AEQ</span>
        </div>
        <div className="loading-bar">
          <div className="loading-bar-fill" style={{ width: `${Math.min(progress, 100)}%` }}></div>
        </div>
        <p className="loading-tagline">Safety Excellence Since 2013</p>
      </div>

      <style>{`
        .loading-screen {
          position: fixed;
          inset: 0;
          background: linear-gradient(135deg, #030712 0%, #0f172a 50%, #030712 100%);
          display: flex;
          align-items: center;
          justify-content: center;
          z-index: 99999;
          transition: opacity 0.5s ease, visibility 0.5s ease;
        }

        .loading-screen.fade-out {
          opacity: 0;
          visibility: hidden;
        }

        .loading-content {
          text-align: center;
        }

        .loading-logo {
          position: relative;
          width: 120px;
          height: 120px;
          margin: 0 auto 30px;
        }

        .loading-circle {
          width: 100%;
          height: 100%;
          transform: rotate(-90deg);
        }

        .circle-bg {
          fill: none;
          stroke: rgba(251, 191, 36, 0.1);
          stroke-width: 4;
        }

        .circle-progress {
          fill: none;
          stroke: url(#loadingGradient);
          stroke-width: 4;
          stroke-linecap: round;
          stroke-dasharray: 283;
          transition: stroke-dashoffset 0.3s ease;
        }

        .loading-logo::before {
          content: '';
          position: absolute;
          inset: 10px;
          border-radius: 50%;
          background: linear-gradient(135deg, rgba(251, 191, 36, 0.1) 0%, rgba(251, 191, 36, 0.05) 100%);
          animation: pulse 2s ease-in-out infinite;
        }

        @keyframes pulse {
          0%, 100% { transform: scale(1); opacity: 0.5; }
          50% { transform: scale(1.05); opacity: 1; }
        }

        .loading-text {
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          font-size: 24px;
          font-weight: 800;
          color: #fbbf24;
          letter-spacing: 0.1em;
        }

        .loading-bar {
          width: 200px;
          height: 3px;
          background: rgba(251, 191, 36, 0.1);
          border-radius: 3px;
          overflow: hidden;
          margin: 0 auto 20px;
        }

        .loading-bar-fill {
          height: 100%;
          background: linear-gradient(90deg, #fbbf24, #f59e0b);
          border-radius: 3px;
          transition: width 0.3s ease;
        }

        .loading-tagline {
          color: #64748b;
          font-size: 14px;
          letter-spacing: 0.05em;
          margin: 0;
          animation: fadeInUp 0.6s ease forwards;
        }

        @keyframes fadeInUp {
          from { opacity: 0; transform: translateY(10px); }
          to { opacity: 1; transform: translateY(0); }
        }
      `}</style>

      <svg width="0" height="0">
        <defs>
          <linearGradient id="loadingGradient" x1="0%" y1="0%" x2="100%" y2="0%">
            <stop offset="0%" stopColor="#fbbf24" />
            <stop offset="100%" stopColor="#f59e0b" />
          </linearGradient>
        </defs>
      </svg>
    </div>
  );
}

// ============================================
// CUSTOM CURSOR
// ============================================
function CustomCursor() {
  const cursorRef = React.useRef(null);
  const cursorDotRef = React.useRef(null);
  const [isHovering, setIsHovering] = React.useState(false);
  const [isClicking, setIsClicking] = React.useState(false);

  React.useEffect(() => {
    const cursor = cursorRef.current;
    const dot = cursorDotRef.current;

    let mouseX = 0, mouseY = 0;
    let cursorX = 0, cursorY = 0;

    const handleMouseMove = (e) => {
      mouseX = e.clientX;
      mouseY = e.clientY;

      // Dot follows instantly
      if (dot) {
        dot.style.left = mouseX + 'px';
        dot.style.top = mouseY + 'px';
      }
    };

    const handleMouseDown = () => setIsClicking(true);
    const handleMouseUp = () => setIsClicking(false);

    // Smooth cursor animation
    const animateCursor = () => {
      cursorX += (mouseX - cursorX) * 0.15;
      cursorY += (mouseY - cursorY) * 0.15;

      if (cursor) {
        cursor.style.left = cursorX + 'px';
        cursor.style.top = cursorY + 'px';
      }

      requestAnimationFrame(animateCursor);
    };

    // Detect hoverable elements
    const handleMouseOver = (e) => {
      if (e.target.closest('a, button, [role="button"], input, textarea, select, .hoverable')) {
        setIsHovering(true);
      }
    };

    const handleMouseOut = (e) => {
      if (e.target.closest('a, button, [role="button"], input, textarea, select, .hoverable')) {
        setIsHovering(false);
      }
    };

    document.addEventListener('mousemove', handleMouseMove);
    document.addEventListener('mousedown', handleMouseDown);
    document.addEventListener('mouseup', handleMouseUp);
    document.addEventListener('mouseover', handleMouseOver);
    document.addEventListener('mouseout', handleMouseOut);

    animateCursor();

    return () => {
      document.removeEventListener('mousemove', handleMouseMove);
      document.removeEventListener('mousedown', handleMouseDown);
      document.removeEventListener('mouseup', handleMouseUp);
      document.removeEventListener('mouseover', handleMouseOver);
      document.removeEventListener('mouseout', handleMouseOut);
    };
  }, []);

  // Don't show on touch devices
  if (typeof window !== 'undefined' && 'ontouchstart' in window) {
    return null;
  }

  return (
    <>
      <div
        ref={cursorRef}
        className={`custom-cursor ${isHovering ? 'hovering' : ''} ${isClicking ? 'clicking' : ''}`}
      />
      <div
        ref={cursorDotRef}
        className={`cursor-dot ${isClicking ? 'clicking' : ''}`}
      />
      <style>{`
        .custom-cursor {
          position: fixed;
          width: 40px;
          height: 40px;
          border: 2px solid rgba(251, 191, 36, 0.5);
          border-radius: 50%;
          pointer-events: none;
          z-index: 99998;
          transform: translate(-50%, -50%);
          transition: width 0.3s ease, height 0.3s ease, border-color 0.3s ease, background 0.3s ease;
          mix-blend-mode: difference;
        }

        .custom-cursor.hovering {
          width: 60px;
          height: 60px;
          border-color: #fbbf24;
          background: rgba(251, 191, 36, 0.1);
        }

        .custom-cursor.clicking {
          transform: translate(-50%, -50%) scale(0.8);
        }

        .cursor-dot {
          position: fixed;
          width: 8px;
          height: 8px;
          background: #fbbf24;
          border-radius: 50%;
          pointer-events: none;
          z-index: 99999;
          transform: translate(-50%, -50%);
          transition: transform 0.1s ease;
        }

        .cursor-dot.clicking {
          transform: translate(-50%, -50%) scale(0.5);
        }

        @media (max-width: 768px) {
          .custom-cursor, .cursor-dot {
            display: none;
          }
        }

        /* Hide default cursor on desktop */
        @media (min-width: 769px) {
          body {
            cursor: none;
          }

          a, button, input, textarea, select {
            cursor: none;
          }
        }
      `}</style>
    </>
  );
}

// ============================================
// SCROLL REVEAL ANIMATION
// ============================================
function useScrollReveal() {
  React.useEffect(() => {
    // Wait for GSAP and ScrollTrigger to load
    const initScrollTrigger = () => {
      if (typeof gsap !== 'undefined' && typeof ScrollTrigger !== 'undefined') {
        gsap.registerPlugin(ScrollTrigger);

        // Reveal animations for elements with data-reveal attribute
        const revealElements = document.querySelectorAll('[data-reveal]');

        revealElements.forEach((el, index) => {
          const direction = el.dataset.reveal || 'up';
          const delay = parseFloat(el.dataset.revealDelay) || 0;
          const duration = parseFloat(el.dataset.revealDuration) || 0.8;

          let fromVars = { opacity: 0, duration, delay };

          switch(direction) {
            case 'up':
              fromVars.y = 60;
              break;
            case 'down':
              fromVars.y = -60;
              break;
            case 'left':
              fromVars.x = -60;
              break;
            case 'right':
              fromVars.x = 60;
              break;
            case 'scale':
              fromVars.scale = 0.8;
              break;
            case 'rotate':
              fromVars.rotation = 10;
              fromVars.y = 40;
              break;
            default:
              fromVars.y = 60;
          }

          gsap.from(el, {
            ...fromVars,
            ease: 'power3.out',
            scrollTrigger: {
              trigger: el,
              start: 'top 85%',
              toggleActions: 'play none none reverse'
            }
          });
        });

        // Stagger animations for groups
        const staggerGroups = document.querySelectorAll('[data-stagger]');
        staggerGroups.forEach(group => {
          const children = group.children;
          const staggerAmount = parseFloat(group.dataset.stagger) || 0.1;

          gsap.from(children, {
            opacity: 0,
            y: 40,
            duration: 0.6,
            stagger: staggerAmount,
            ease: 'power3.out',
            scrollTrigger: {
              trigger: group,
              start: 'top 85%',
              toggleActions: 'play none none reverse'
            }
          });
        });

        // Parallax effects
        const parallaxElements = document.querySelectorAll('[data-parallax]');
        parallaxElements.forEach(el => {
          const speed = parseFloat(el.dataset.parallax) || 0.5;

          gsap.to(el, {
            y: () => -100 * speed,
            ease: 'none',
            scrollTrigger: {
              trigger: el,
              start: 'top bottom',
              end: 'bottom top',
              scrub: true
            }
          });
        });
      }
    };

    // Check if GSAP is loaded, if not wait for it
    if (typeof gsap !== 'undefined' && typeof ScrollTrigger !== 'undefined') {
      initScrollTrigger();
    } else {
      // Wait for scripts to load
      const checkInterval = setInterval(() => {
        if (typeof gsap !== 'undefined' && typeof ScrollTrigger !== 'undefined') {
          clearInterval(checkInterval);
          initScrollTrigger();
        }
      }, 100);

      // Cleanup after 5 seconds
      setTimeout(() => clearInterval(checkInterval), 5000);
    }
  }, []);
}

// ============================================
// FLOATING PARTICLES BACKGROUND
// ============================================
function FloatingParticles({ count = 30, color = 'rgba(251, 191, 36, 0.3)' }) {
  const particles = React.useMemo(() => {
    return Array.from({ length: count }, (_, i) => ({
      id: i,
      size: Math.random() * 6 + 2,
      left: Math.random() * 100,
      top: Math.random() * 100,
      duration: Math.random() * 20 + 15,
      delay: Math.random() * 10,
      opacity: Math.random() * 0.5 + 0.1
    }));
  }, [count]);

  return (
    <div className="floating-particles">
      {particles.map(p => (
        <div
          key={p.id}
          className="floating-particle"
          style={{
            '--size': `${p.size}px`,
            '--left': `${p.left}%`,
            '--top': `${p.top}%`,
            '--duration': `${p.duration}s`,
            '--delay': `${p.delay}s`,
            '--opacity': p.opacity,
            '--color': color
          }}
        />
      ))}
      <style>{`
        .floating-particles {
          position: absolute;
          inset: 0;
          overflow: hidden;
          pointer-events: none;
        }

        .floating-particle {
          position: absolute;
          width: var(--size);
          height: var(--size);
          background: var(--color);
          border-radius: 50%;
          left: var(--left);
          top: var(--top);
          opacity: var(--opacity);
          animation: floatParticle var(--duration) ease-in-out infinite;
          animation-delay: var(--delay);
        }

        @keyframes floatParticle {
          0%, 100% {
            transform: translate(0, 0) rotate(0deg);
          }
          25% {
            transform: translate(30px, -50px) rotate(90deg);
          }
          50% {
            transform: translate(-20px, -100px) rotate(180deg);
          }
          75% {
            transform: translate(40px, -50px) rotate(270deg);
          }
        }
      `}</style>
    </div>
  );
}

// ============================================
// ANIMATED TEXT
// ============================================
function AnimatedText({ text, className = '', tag = 'span', delay = 0 }) {
  const Tag = tag;
  const words = text.split(' ');

  return (
    <Tag className={`animated-text ${className}`}>
      {words.map((word, i) => (
        <span
          key={i}
          className="word-wrapper"
          style={{ '--word-delay': `${delay + i * 0.1}s` }}
        >
          <span className="word">{word}</span>
          {i < words.length - 1 && ' '}
        </span>
      ))}
      <style>{`
        .animated-text {
          display: inline;
        }

        .word-wrapper {
          display: inline-block;
          overflow: hidden;
        }

        .word {
          display: inline-block;
          animation: wordReveal 0.8s cubic-bezier(0.4, 0, 0.2, 1) forwards;
          animation-delay: var(--word-delay);
          opacity: 0;
          transform: translateY(100%);
        }

        @keyframes wordReveal {
          to {
            opacity: 1;
            transform: translateY(0);
          }
        }
      `}</style>
    </Tag>
  );
}

// ============================================
// MAGNETIC BUTTON
// ============================================
function MagneticButton({ children, className = '', onClick, href }) {
  const buttonRef = React.useRef(null);

  const handleMouseMove = (e) => {
    const btn = buttonRef.current;
    if (!btn) return;

    const rect = btn.getBoundingClientRect();
    const x = e.clientX - rect.left - rect.width / 2;
    const y = e.clientY - rect.top - rect.height / 2;

    btn.style.transform = `translate(${x * 0.3}px, ${y * 0.3}px)`;
  };

  const handleMouseLeave = () => {
    const btn = buttonRef.current;
    if (btn) {
      btn.style.transform = 'translate(0, 0)';
    }
  };

  const Component = href ? 'a' : 'button';

  return (
    <Component
      ref={buttonRef}
      className={`magnetic-btn ${className}`}
      onClick={onClick}
      href={href}
      onMouseMove={handleMouseMove}
      onMouseLeave={handleMouseLeave}
    >
      {children}
      <style>{`
        .magnetic-btn {
          display: inline-flex;
          align-items: center;
          gap: 10px;
          transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        }
      `}</style>
    </Component>
  );
}

// ============================================
// 3D TILT CARD
// ============================================
function TiltCard({ children, className = '' }) {
  const cardRef = React.useRef(null);

  const handleMouseMove = (e) => {
    const card = cardRef.current;
    if (!card) return;

    const rect = card.getBoundingClientRect();
    const x = e.clientX - rect.left;
    const y = e.clientY - rect.top;

    const centerX = rect.width / 2;
    const centerY = rect.height / 2;

    const rotateX = (y - centerY) / 10;
    const rotateY = (centerX - x) / 10;

    card.style.transform = `perspective(1000px) rotateX(${rotateX}deg) rotateY(${rotateY}deg) scale3d(1.02, 1.02, 1.02)`;
  };

  const handleMouseLeave = () => {
    const card = cardRef.current;
    if (card) {
      card.style.transform = 'perspective(1000px) rotateX(0) rotateY(0) scale3d(1, 1, 1)';
    }
  };

  return (
    <div
      ref={cardRef}
      className={`tilt-card ${className}`}
      onMouseMove={handleMouseMove}
      onMouseLeave={handleMouseLeave}
    >
      {children}
      <style>{`
        .tilt-card {
          transition: transform 0.3s ease;
          transform-style: preserve-3d;
        }
      `}</style>
    </div>
  );
}

// ============================================
// PAGE TRANSITION
// ============================================
function PageTransition() {
  const [isTransitioning, setIsTransitioning] = React.useState(false);

  React.useEffect(() => {
    // Intercept link clicks for page transitions
    const handleClick = (e) => {
      const link = e.target.closest('a');
      if (link && link.href && link.href.includes(window.location.origin) && !link.href.includes('#')) {
        e.preventDefault();
        setIsTransitioning(true);

        setTimeout(() => {
          window.location.href = link.href;
        }, 600);
      }
    };

    document.addEventListener('click', handleClick);
    return () => document.removeEventListener('click', handleClick);
  }, []);

  if (!isTransitioning) return null;

  return (
    <div className="page-transition">
      <div className="transition-layer layer-1"></div>
      <div className="transition-layer layer-2"></div>
      <div className="transition-layer layer-3"></div>
      <style>{`
        .page-transition {
          position: fixed;
          inset: 0;
          z-index: 99997;
          pointer-events: none;
        }

        .transition-layer {
          position: absolute;
          left: 0;
          right: 0;
          height: 34%;
          background: #030712;
          transform: scaleY(0);
          transform-origin: bottom;
        }

        .layer-1 {
          top: 0;
          animation: slideIn 0.6s ease forwards;
          animation-delay: 0s;
        }

        .layer-2 {
          top: 33%;
          animation: slideIn 0.6s ease forwards;
          animation-delay: 0.1s;
        }

        .layer-3 {
          top: 66%;
          animation: slideIn 0.6s ease forwards;
          animation-delay: 0.2s;
        }

        @keyframes slideIn {
          0% { transform: scaleY(0); transform-origin: bottom; }
          50% { transform: scaleY(1); transform-origin: bottom; }
          50.1% { transform-origin: top; }
          100% { transform: scaleY(1); transform-origin: top; }
        }
      `}</style>
    </div>
  );
}

// ============================================
// FLOATING HRD CORP BADGE
// ============================================
function FloatingHRDBadge() {
  const [isExpanded, setIsExpanded] = React.useState(false);

  return (
    <div className={`floating-hrd-badge ${isExpanded ? 'is-expanded' : ''}`}>
      <div
        className="hrd-badge-container"
        onClick={() => setIsExpanded(!isExpanded)}
        onMouseEnter={() => setIsExpanded(true)}
        onMouseLeave={() => setIsExpanded(false)}
      >
        <div className="hrd-glow"></div>
        <div className="hrd-glow-pulse"></div>
        <img
          src="assets/hrdcorp-logo.png"
          alt="HRD Corp Registered Training Provider"
          className="hrd-badge-img"
        />
        <div className="hrd-badge-text">
          <span className="hrd-title">HRD Corp</span>
          <span className="hrd-subtitle">Registered Provider</span>
        </div>
      </div>

      <style>{`
        .floating-hrd-badge {
          position: fixed;
          bottom: 30px;
          right: 30px;
          right: calc(30px + env(safe-area-inset-right, 0px));
          z-index: 9990;
          transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
        }

        .hrd-badge-container {
          position: relative;
          display: flex;
          align-items: center;
          gap: 16px;
          padding: 16px 20px;
          background: linear-gradient(135deg, rgba(255, 255, 255, 0.98) 0%, rgba(248, 250, 252, 0.95) 100%);
          border-radius: 20px;
          cursor: pointer;
          box-shadow:
            0 10px 40px rgba(0, 0, 0, 0.3),
            0 0 60px rgba(14, 165, 233, 0.4),
            0 0 100px rgba(251, 191, 36, 0.3),
            inset 0 1px 0 rgba(255, 255, 255, 1);
          border: 2px solid rgba(14, 165, 233, 0.3);
          transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
          overflow: hidden;
        }

        .hrd-badge-container:hover {
          transform: translateY(-5px) scale(1.02);
          box-shadow:
            0 20px 60px rgba(0, 0, 0, 0.4),
            0 0 80px rgba(14, 165, 233, 0.5),
            0 0 120px rgba(251, 191, 36, 0.4),
            inset 0 1px 0 rgba(255, 255, 255, 1);
          border-color: rgba(14, 165, 233, 0.5);
        }

        .hrd-glow {
          position: absolute;
          inset: -20px;
          background: radial-gradient(circle at center, rgba(14, 165, 233, 0.3) 0%, transparent 70%);
          animation: hrdGlowPulse 3s ease-in-out infinite;
          pointer-events: none;
        }

        .hrd-glow-pulse {
          position: absolute;
          inset: -10px;
          border-radius: 25px;
          background: transparent;
          border: 2px solid rgba(14, 165, 233, 0.3);
          animation: hrdRingPulse 2s ease-out infinite;
          pointer-events: none;
        }

        @keyframes hrdGlowPulse {
          0%, 100% { opacity: 0.5; transform: scale(1); }
          50% { opacity: 1; transform: scale(1.1); }
        }

        @keyframes hrdRingPulse {
          0% { transform: scale(1); opacity: 1; }
          100% { transform: scale(1.5); opacity: 0; }
        }

        .hrd-badge-img {
          width: 120px;
          height: auto;
          position: relative;
          z-index: 2;
          transition: all 0.4s ease;
          filter: drop-shadow(0 4px 12px rgba(0, 0, 0, 0.15));
        }

        .floating-hrd-badge.is-expanded .hrd-badge-img {
          width: 160px;
        }

        .hrd-badge-text {
          display: flex;
          flex-direction: column;
          gap: 2px;
          opacity: 0;
          max-width: 0;
          overflow: hidden;
          transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
          white-space: nowrap;
        }

        .floating-hrd-badge.is-expanded .hrd-badge-text {
          opacity: 1;
          max-width: 150px;
        }

        .hrd-title {
          font-size: 18px;
          font-weight: 700;
          color: #0369a1;
          letter-spacing: -0.02em;
        }

        .hrd-subtitle {
          font-size: 12px;
          font-weight: 600;
          color: #64748b;
          text-transform: uppercase;
          letter-spacing: 0.05em;
        }

        /* Mobile adjustments */
        @media (max-width: 768px) {
          .floating-hrd-badge {
            bottom: 20px;
            right: 20px;
            right: calc(20px + env(safe-area-inset-right, 0px));
          }

          .hrd-badge-container {
            padding: 12px 16px;
          }

          .hrd-badge-img {
            width: 100px;
          }

          .floating-hrd-badge.is-expanded .hrd-badge-img {
            width: 120px;
          }

          .hrd-badge-text {
            display: none;
          }
        }

        /* Reduce motion */
        @media (prefers-reduced-motion: reduce) {
          .hrd-glow, .hrd-glow-pulse {
            animation: none;
          }
        }
      `}</style>
    </div>
  );
}

// ============================================
// GLOBAL EFFECTS WRAPPER
// ============================================
function GlobalEffects({ children }) {
  useScrollReveal();

  return (
    <>
      <FloatingHRDBadge />
      {children}
    </>
  );
}
