/* Shared components: Starfield, Logo, Reveal, Glyphs */
const { useEffect, useRef, useState, useMemo } = React;

function Starfield({ density = 80, gold = 6, className = '' }) {
  const stars = useMemo(() => {
    return Array.from({ length: density }, (_, i) => ({
      id: i,
      left: Math.random() * 100,
      top: Math.random() * 100,
      size: Math.random() * 2 + 0.5,
      dur: 2 + Math.random() * 4,
      delay: Math.random() * 4,
      gold: i < gold,
    }));
  }, [density, gold]);
  return (
    <div className={`starfield ${className}`}>
      {stars.map((s) => (
        <div
          key={s.id}
          className={`star ${s.gold ? 'gold' : ''}`}
          style={{
            left: `${s.left}%`,
            top: `${s.top}%`,
            width: `${s.size}px`,
            height: `${s.size}px`,
            '--dur': `${s.dur}s`,
            '--delay': `${s.delay}s`,
          }}
        />
      ))}
    </div>
  );
}

function LogoMark({ size = 32 }) {
  // Original mark: diamond/portal — concentric ring with a gold core diamond
  return (
    <svg viewBox="0 0 32 32" width={size} height={size} aria-hidden="true">
      <defs>
        <radialGradient id="logoGold" cx="50%" cy="50%" r="50%">
          <stop offset="0%" stopColor="#FFE38B" />
          <stop offset="60%" stopColor="#F5C842" />
          <stop offset="100%" stopColor="#B8902A" />
        </radialGradient>
      </defs>
      <circle cx="16" cy="16" r="14" fill="none" stroke="rgba(245,200,66,0.35)" strokeWidth="0.5" />
      <circle cx="16" cy="16" r="10.5" fill="none" stroke="rgba(245,200,66,0.55)" strokeWidth="0.7" />
      <g transform="rotate(45 16 16)">
        <rect x="9" y="9" width="14" height="14" fill="url(#logoGold)" />
      </g>
      <circle cx="16" cy="16" r="2.5" fill="#0A0E1A" />
    </svg>
  );
}

function SectionDivider({ label, number }) {
  return (
    <div style={{
      display: 'flex',
      alignItems: 'center',
      gap: 16,
      margin: '120px 0 32px',
      fontFamily: 'JetBrains Mono, monospace',
      fontSize: 11,
      letterSpacing: '0.2em',
      color: 'var(--ink-3)',
      textTransform: 'uppercase',
    }}>
      <span style={{ color: 'var(--gold)' }}>{number}</span>
      <span>{label}</span>
      <span style={{ flex: 1, height: 1, background: 'linear-gradient(90deg, var(--line-strong), transparent)' }} />
    </div>
  );
}

// Intersection-observer-based reveal — with sync fallback + transition bypass
// for hidden-document contexts (screenshots, PDF print) where CSS transitions freeze.
function useReveal() {
  const ref = useRef(null);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;

    const reveal = (instant) => {
      el.classList.add('in');
      if (instant || document.hidden) {
        // Bypass CSS transition — paint immediately
        el.style.transition = 'none';
        el.style.opacity = '1';
        el.style.transform = 'none';
      }
    };

    // If document is hidden (screenshot tools, PDF print), show everything immediately
    if (document.hidden) { reveal(true); return; }

    // Already in viewport → reveal now (still animated)
    const rect = el.getBoundingClientRect();
    if (rect.top < window.innerHeight && rect.bottom > 0) { reveal(false); return; }

    // Safety: force-reveal (instant) after a delay if IO never fires
    const fallback = setTimeout(() => {
      if (!el.classList.contains('in')) reveal(true);
    }, 1800);

    // Also force-reveal if document becomes hidden mid-flight
    const onVis = () => { if (document.hidden) reveal(true); };
    document.addEventListener('visibilitychange', onVis);

    if (typeof IntersectionObserver === 'undefined') {
      reveal(true);
      clearTimeout(fallback);
      document.removeEventListener('visibilitychange', onVis);
      return;
    }

    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) {
          reveal(false);
          io.unobserve(e.target);
          clearTimeout(fallback);
        }
      });
    }, { threshold: 0.05, rootMargin: '0px 0px -5% 0px' });
    io.observe(el);

    return () => {
      io.disconnect();
      clearTimeout(fallback);
      document.removeEventListener('visibilitychange', onVis);
    };
  }, []);
  return ref;
}

function Reveal({ children, delay = 0, as: As = 'div', className = '', style = {} }) {
  const ref = useReveal();
  return (
    <As
      ref={ref}
      className={`reveal ${className}`}
      style={{ transitionDelay: `${delay}ms`, ...style }}
    >
      {children}
    </As>
  );
}

// Tiny inline icon set — geometric / cosmic, original
const Glyph = {
  Sparkle: (p) => (
    <svg viewBox="0 0 24 24" fill="none" {...p}>
      <path d="M12 2 L13.5 10.5 L22 12 L13.5 13.5 L12 22 L10.5 13.5 L2 12 L10.5 10.5 Z" fill="currentColor" />
    </svg>
  ),
  Diamond: (p) => (
    <svg viewBox="0 0 24 24" fill="none" {...p}>
      <path d="M12 2 L22 12 L12 22 L2 12 Z" stroke="currentColor" strokeWidth="1.5" />
    </svg>
  ),
  Layers: (p) => (
    <svg viewBox="0 0 24 24" fill="none" {...p}>
      <path d="M12 3 L22 8 L12 13 L2 8 Z" stroke="currentColor" strokeWidth="1.5" />
      <path d="M2 13 L12 18 L22 13" stroke="currentColor" strokeWidth="1.5" />
    </svg>
  ),
  Shield: (p) => (
    <svg viewBox="0 0 24 24" fill="none" {...p}>
      <path d="M12 2 L20 5 V12 C20 17 16 21 12 22 C8 21 4 17 4 12 V5 Z" stroke="currentColor" strokeWidth="1.5" />
      <path d="M8 12 L11 15 L16 9" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  ),
  Cube: (p) => (
    <svg viewBox="0 0 24 24" fill="none" {...p}>
      <path d="M12 2 L21 7 V17 L12 22 L3 17 V7 Z" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round" />
      <path d="M3 7 L12 12 L21 7 M12 12 V22" stroke="currentColor" strokeWidth="1.5" />
    </svg>
  ),
  Arrow: (p) => (
    <svg viewBox="0 0 24 24" fill="none" {...p}>
      <path d="M5 12 H19 M13 6 L19 12 L13 18" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  ),
  Plus: (p) => (
    <svg viewBox="0 0 24 24" fill="none" {...p}>
      <path d="M12 5 V19 M5 12 H19" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
    </svg>
  ),
  Check: (p) => (
    <svg viewBox="0 0 24 24" fill="none" {...p}>
      <path d="M5 12 L10 17 L19 7" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" />
    </svg>
  ),
  Search: (p) => (
    <svg viewBox="0 0 24 24" fill="none" {...p}>
      <circle cx="11" cy="11" r="7" stroke="currentColor" strokeWidth="1.5" />
      <path d="M20 20 L16 16" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
    </svg>
  ),
  Bell: (p) => (
    <svg viewBox="0 0 24 24" fill="none" {...p}>
      <path d="M6 16 V11 C6 7.7 8.7 5 12 5 C15.3 5 18 7.7 18 11 V16 L20 18 H4 Z" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round" />
      <path d="M10 21 H14" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" />
    </svg>
  ),
  Doc: (p) => (
    <svg viewBox="0 0 24 24" fill="none" {...p}>
      <path d="M6 3 H14 L19 8 V21 H6 Z" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round" />
      <path d="M14 3 V8 H19" stroke="currentColor" strokeWidth="1.5" />
    </svg>
  ),
  Image: (p) => (
    <svg viewBox="0 0 24 24" fill="none" {...p}>
      <rect x="3" y="4" width="18" height="16" rx="1.5" stroke="currentColor" strokeWidth="1.5" />
      <circle cx="8.5" cy="9.5" r="1.5" fill="currentColor" />
      <path d="M3 17 L8 12 L13 17 L17 13 L21 17" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round" />
    </svg>
  ),
  Video: (p) => (
    <svg viewBox="0 0 24 24" fill="none" {...p}>
      <rect x="3" y="6" width="13" height="12" rx="1.5" stroke="currentColor" strokeWidth="1.5" />
      <path d="M16 10 L21 7 V17 L16 14 Z" stroke="currentColor" strokeWidth="1.5" strokeLinejoin="round" />
    </svg>
  ),
  Box: (p) => (
    <svg viewBox="0 0 24 24" fill="none" {...p}>
      <rect x="4" y="4" width="16" height="16" rx="2" stroke="currentColor" strokeWidth="1.5" />
      <path d="M4 9 H20" stroke="currentColor" strokeWidth="1.5" />
    </svg>
  ),
};

Object.assign(window, { Starfield, LogoMark, SectionDivider, Reveal, useReveal, Glyph });
