const { useState, useRef, useEffect, useCallback, useMemo } = React;

// 3D tilt wrapper -- listens to mousemove on element, applies rotateX/rotateY
function Tilt({ max = 14, scale = 1.04, glare = true, children, className = '', style = {}, idle = false }) {
  const wrapRef = useRef(null);
  const cardRef = useRef(null);
  const rafRef = useRef(0);
  const stateRef = useRef({ tx: 0, ty: 0, rx: 0, ry: 0, sc: 1, hot: false });
  const idleRef = useRef(0);

  useEffect(() => {
    const wrap = wrapRef.current;
    const card = cardRef.current;
    if (!wrap || !card) return;

    const onMove = (e) => {
      const r = wrap.getBoundingClientRect();
      const x = (e.clientX - r.left) / r.width - 0.5;
      const y = (e.clientY - r.top) / r.height - 0.5;
      stateRef.current.tx = -y * max;
      stateRef.current.ty = x * max;
      stateRef.current.sc = scale;
      stateRef.current.hot = true;
    };
    const onLeave = () => {
      stateRef.current.tx = 0;
      stateRef.current.ty = 0;
      stateRef.current.sc = 1;
      stateRef.current.hot = false;
    };

    wrap.addEventListener('mousemove', onMove);
    wrap.addEventListener('mouseleave', onLeave);

    const tick = () => {
      const s = stateRef.current;
      s.rx += (s.tx - s.rx) * 0.12;
      s.ry += (s.ty - s.ry) * 0.12;
      let extraY = 0;
      if (idle && !s.hot) {
        idleRef.current += 0.005;
        extraY = Math.sin(idleRef.current) * 6;
      }
      const sc = 1 + (s.sc - 1) * 0.5;
      card.style.transform = `rotateX(${s.rx.toFixed(2)}deg) rotateY(${(s.ry + extraY).toFixed(2)}deg) scale(${sc.toFixed(3)})`;
      if (glare) {
        const gx = 50 + s.ry * 3;
        const gy = 50 - s.rx * 3;
        card.style.setProperty('--gx', `${gx}%`);
        card.style.setProperty('--gy', `${gy}%`);
      }
      rafRef.current = requestAnimationFrame(tick);
    };
    rafRef.current = requestAnimationFrame(tick);
    return () => {
      wrap.removeEventListener('mousemove', onMove);
      wrap.removeEventListener('mouseleave', onLeave);
      cancelAnimationFrame(rafRef.current);
    };
  }, [max, scale, glare, idle]);

  return (
    <div ref={wrapRef} className={`tilt-wrap ${className}`} style={style}>
      <div ref={cardRef} className="tilt-card" style={{ transformStyle: 'preserve-3d' }}>
        {children}
      </div>
    </div>
  );
}

// Magnetic button -- subtly follows the cursor inside a radius
function Magnetic({ children, strength = 18, className = '', as = 'button', ...rest }) {
  const ref = useRef(null);
  const stateRef = useRef({ tx: 0, ty: 0, rx: 0, ry: 0 });
  const rafRef = useRef(0);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const onMove = (e) => {
      const r = el.getBoundingClientRect();
      const cx = r.left + r.width / 2;
      const cy = r.top + r.height / 2;
      stateRef.current.tx = ((e.clientX - cx) / r.width) * strength;
      stateRef.current.ty = ((e.clientY - cy) / r.height) * strength;
    };
    const onLeave = () => { stateRef.current.tx = 0; stateRef.current.ty = 0; };
    el.addEventListener('mousemove', onMove);
    el.addEventListener('mouseleave', onLeave);
    const tick = () => {
      const s = stateRef.current;
      s.rx += (s.tx - s.rx) * 0.18;
      s.ry += (s.ty - s.ry) * 0.18;
      el.style.transform = `translate3d(${s.rx.toFixed(2)}px, ${s.ry.toFixed(2)}px, 0)`;
      rafRef.current = requestAnimationFrame(tick);
    };
    rafRef.current = requestAnimationFrame(tick);
    return () => {
      el.removeEventListener('mousemove', onMove);
      el.removeEventListener('mouseleave', onLeave);
      cancelAnimationFrame(rafRef.current);
    };
  }, [strength]);
  const Comp = as;
  return (
    <Comp ref={ref} data-hot className={className} {...rest}>{children}</Comp>
  );
}

// Counter that animates from 0 to value when in view
function Counter({ value, suffix = '', duration = 1400, format = (n) => n }) {
  const ref = useRef(null);
  const [n, setN] = useState(0);
  useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach((en) => {
        if (en.isIntersecting) {
          const start = performance.now();
          const animate = (t) => {
            const p = Math.min(1, (t - start) / duration);
            const eased = 1 - Math.pow(1 - p, 3);
            setN(Math.round(value * eased));
            if (p < 1) requestAnimationFrame(animate);
          };
          requestAnimationFrame(animate);
          io.disconnect();
        }
      });
    }, { threshold: 0.4 });
    io.observe(el);
    return () => io.disconnect();
  }, [value, duration]);
  return <span ref={ref}>{format(n)}{suffix}</span>;
}

// Section header
function SectionHeader({ tag, title, subtitle, align = 'left' }) {
  return (
    <div className={`reveal mb-12 md:mb-16 ${align === 'center' ? 'text-center mx-auto max-w-3xl' : 'max-w-3xl'}`}>
      <div className="sec-tag mb-4 flex items-center gap-2" style={{ justifyContent: align === 'center' ? 'center' : 'flex-start' }}>
        <span className="inline-block w-6 h-px bg-cyan1 opacity-70"></span>
        <span>{tag}</span>
      </div>
      <h2 className="text-4xl md:text-6xl font-semibold tracking-tight text-white">{title}</h2>
      {subtitle && <p className="text-lg md:text-xl text-white/60 mt-5 max-w-2xl" style={{ marginInline: align === 'center' ? 'auto' : undefined }}>{subtitle}</p>}
    </div>
  );
}

// Real-photo lookup for named agents (video for PRIYA, image for SURESH)
const AGENT_PHOTOS = {
  PRIYA: { video: 'assets/priya.mp4', poster: 'assets/priya.png', tint: 'linear-gradient(160deg, #f5d2c4, #f3a999)' },
  SURESH: { src: 'assets/suresh.png', tint: 'linear-gradient(160deg, #f4d199, #d99a55)' },
};

// Looping video for an animated agent
function PriyaClip({ src, poster }) {
  return (
    <video
      src={src}
      poster={poster}
      muted
      autoPlay
      playsInline
      loop
      style={{
        width: '108%',
        height: '108%',
        objectFit: 'cover',
        objectPosition: 'center top',
        filter: 'drop-shadow(0 8px 18px rgba(0,0,0,0.35))',
      }}
    />
  );
}

// Avatar -- holographic identity tile, with real photo for known agents
function AgentAvatar({ name, hue = 195, size = 'md' }) {
  const initials = (name || '').slice(0, 2);
  const px = size === 'lg' ? 320 : size === 'sm' ? 64 : 132;
  const fs = size === 'lg' ? 88 : size === 'sm' ? 22 : 40;
  const photo = AGENT_PHOTOS[(name || '').toUpperCase()];
  const bg = photo ? photo.tint : `radial-gradient(120% 120% at 30% 25%, hsl(${hue} 90% 60% / .55), transparent 55%),
              radial-gradient(120% 120% at 80% 80%, hsl(${(hue+60)%360} 80% 55% / .45), transparent 55%),
              linear-gradient(160deg, hsl(${hue} 30% 12%), hsl(${(hue+30)%360} 30% 6%))`;

  if (photo) {
    return (
      <div
        className="relative ring-glow rounded-2xl overflow-hidden flex items-end justify-center"
        style={{ width: px, height: px, background: bg }}
      >
        {photo.video ? (
          <PriyaClip src={photo.video} poster={photo.poster} />
        ) : (
          <img
            src={photo.src}
            alt={name}
            style={{
              width: '108%',
              height: '108%',
              objectFit: 'cover',
              objectPosition: 'center top',
              filter: 'drop-shadow(0 8px 18px rgba(0,0,0,0.35))',
            }}
          />
        )}
        {/* corner crosshair */}
        <div className="absolute top-2 left-2 w-3 h-3 border-l border-t border-white/40"></div>
        <div className="absolute top-2 right-2 w-3 h-3 border-r border-t border-white/40"></div>
        <div className="absolute bottom-2 left-2 w-3 h-3 border-l border-b border-white/40"></div>
        <div className="absolute bottom-2 right-2 w-3 h-3 border-r border-b border-white/40"></div>
        {/* subtle vignette to blend with dark UI */}
        <div className="absolute inset-0 pointer-events-none" style={{
          background: 'radial-gradient(120% 80% at 50% 100%, rgba(0,0,0,0.35), transparent 55%)',
        }}></div>
      </div>
    );
  }

  return (
    <div
      className="relative ring-glow rounded-2xl overflow-hidden flex items-center justify-center"
      style={{ width: px, height: px, background: bg }}
    >
      {/* concentric rings */}
      <svg viewBox="0 0 100 100" className="absolute inset-0 w-full h-full opacity-60">
        <defs>
          <radialGradient id={`g-${name}-${hue}`} cx="50%" cy="50%" r="50%">
            <stop offset="0%" stopColor={`hsl(${hue} 90% 70%)`} stopOpacity="0.0" />
            <stop offset="80%" stopColor={`hsl(${hue} 90% 70%)`} stopOpacity="0.35" />
            <stop offset="100%" stopColor={`hsl(${hue} 90% 70%)`} stopOpacity="0.0" />
          </radialGradient>
        </defs>
        <circle cx="50" cy="50" r="44" fill="none" stroke="rgba(255,255,255,0.10)" strokeWidth="0.4" />
        <circle cx="50" cy="50" r="34" fill="none" stroke="rgba(255,255,255,0.08)" strokeWidth="0.4" />
        <circle cx="50" cy="50" r="24" fill="none" stroke="rgba(255,255,255,0.06)" strokeWidth="0.4" />
        <circle cx="50" cy="50" r="48" fill={`url(#g-${name}-${hue})`} />
        {/* equator lines */}
        <ellipse cx="50" cy="50" rx="44" ry="14" fill="none" stroke="rgba(255,255,255,0.10)" strokeWidth="0.3" />
        <ellipse cx="50" cy="50" rx="44" ry="28" fill="none" stroke="rgba(255,255,255,0.06)" strokeWidth="0.3" />
        {/* spark dots */}
        <circle cx="20" cy="30" r="0.8" fill="white" opacity="0.7" />
        <circle cx="78" cy="22" r="0.6" fill="white" opacity="0.5" />
        <circle cx="84" cy="64" r="0.9" fill="white" opacity="0.6" />
      </svg>
      <div
        className="font-display font-semibold relative z-10"
        style={{
          fontSize: fs,
          letterSpacing: '-0.04em',
          color: 'white',
          textShadow: `0 0 24px hsl(${hue} 90% 60% / .8)`,
        }}
      >
        {initials}
      </div>
      {/* corner crosshair */}
      <div className="absolute top-2 left-2 w-3 h-3 border-l border-t border-white/30"></div>
      <div className="absolute top-2 right-2 w-3 h-3 border-r border-t border-white/30"></div>
      <div className="absolute bottom-2 left-2 w-3 h-3 border-l border-b border-white/30"></div>
      <div className="absolute bottom-2 right-2 w-3 h-3 border-r border-b border-white/30"></div>
    </div>
  );
}

Object.assign(window, { Tilt, Magnetic, Counter, SectionHeader, AgentAvatar });
