/* global React, Label, Diamond, useApp */
const { useState: usePD, useEffect: usePDE, useRef: usePDR } = React;

// ======== Glow-hover wrapper (the colored streaming light + particles) ========
function GlowHover({ children, style, palette, radius = 300, active = true }) {
  const ref = usePDR(null);
  const [hover, setHover] = usePD(false);
  const [pos, setPos] = usePD({ x: 0.5, y: 0.5 });
  const [tilt, setTilt] = usePD({ tx: 0, ty: 0 });

  const pal = palette || ['#d4a574', '#c9779e', '#8fa5c4', '#b88fc4'];

  const onMove = (e) => {
    if (!ref.current) return;
    const r = ref.current.getBoundingClientRect();
    const x = (e.clientX - r.left) / r.width;
    const y = (e.clientY - r.top) / r.height;
    setPos({ x, y });
    setTilt({ tx: (y - 0.5) * -10, ty: (x - 0.5) * 10 });
  };

  // Particle spawn
  const [particles, setParticles] = usePD([]);
  const pidRef = usePDR(0);
  usePDE(() => {
    if (!hover || !active) return;
    const id = setInterval(() => {
      setParticles(p => {
        const now = performance.now();
        const alive = p.filter(x => now - x.born < 1400);
        const color = pal[Math.floor(Math.random() * pal.length)];
        const ang = Math.random() * Math.PI * 2;
        const dist = 8 + Math.random() * 12;
        const nx = pos.x * 100 + Math.cos(ang) * dist * 0.1;
        const ny = pos.y * 100 + Math.sin(ang) * dist * 0.1;
        return [...alive, {
          id: ++pidRef.current,
          x: nx, y: ny,
          dx: (Math.random() - 0.5) * 80,
          dy: -20 - Math.random() * 60,
          size: 1.5 + Math.random() * 2.5,
          color,
          born: now,
        }];
      });
    }, 60);
    return () => clearInterval(id);
  }, [hover, pos.x, pos.y, active]);

  const streamA = pal[0];
  const streamB = pal[1];
  const streamC = pal[2];

  return (
    <div
      ref={ref}
      onMouseEnter={() => setHover(true)}
      onMouseLeave={() => { setHover(false); setTilt({ tx: 0, ty: 0 }); }}
      onMouseMove={onMove}
      style={{
        position: 'relative',
        transform: `perspective(1000px) rotateX(${tilt.tx}deg) rotateY(${tilt.ty}deg)`,
        transformStyle: 'preserve-3d',
        transition: 'transform 300ms cubic-bezier(.3,.8,.3,1)',
        ...style,
      }}>
      {/* ambient glow layer (behind child) */}
      {active && (
        <div style={{
          position: 'absolute', inset: -40,
          pointerEvents: 'none', zIndex: 0,
          opacity: hover ? 1 : 0,
          transition: 'opacity 400ms',
          filter: 'blur(22px)',
          background: `
            radial-gradient(circle at ${pos.x*100}% ${pos.y*100}%, ${streamA}88 0%, transparent 32%),
            radial-gradient(circle at ${(1-pos.x)*100}% ${pos.y*100}%, ${streamB}66 0%, transparent 30%),
            radial-gradient(circle at ${pos.x*100}% ${(1-pos.y)*100}%, ${streamC}66 0%, transparent 30%)
          `,
        }} />
      )}

      {/* The child */}
      <div style={{ position: 'relative', zIndex: 1, height: '100%' }}>{children}</div>

      {/* Overlay: stream light + particles — clipped to child bounds */}
      {active && (
        <div style={{
          position: 'absolute', inset: 0,
          pointerEvents: 'none', zIndex: 3,
          overflow: 'hidden',
          opacity: hover ? 1 : 0,
          transition: 'opacity 300ms',
          mixBlendMode: 'screen',
        }}>
          {/* flowing radial conic */}
          <div style={{
            position: 'absolute',
            left: `${pos.x * 100}%`, top: `${pos.y * 100}%`,
            width: radius, height: radius,
            transform: 'translate(-50%,-50%)',
            background: `conic-gradient(from ${pos.x * 360}deg,
              ${streamA}00, ${streamA}88, ${streamB}aa, ${streamC}88, ${pal[3]}66, ${streamA}00)`,
            borderRadius: '50%',
            filter: 'blur(24px)',
            opacity: 0.7,
          }} />
          {/* tight spotlight */}
          <div style={{
            position: 'absolute',
            left: `${pos.x * 100}%`, top: `${pos.y * 100}%`,
            width: 120, height: 120,
            transform: 'translate(-50%,-50%)',
            background: `radial-gradient(circle, ${streamA}aa 0%, transparent 60%)`,
            borderRadius: '50%',
            mixBlendMode: 'screen',
          }} />
          {/* particles */}
          {particles.map(p => {
            const t = Math.min(1, (performance.now() - p.born) / 1400);
            const x = p.x + p.dx * t * 0.4;
            const y = p.y + p.dy * t * 0.4;
            const a = (1 - t) * 0.9;
            return (
              <span key={p.id} style={{
                position: 'absolute',
                left: `${x}%`, top: `${y}%`,
                width: p.size, height: p.size,
                borderRadius: '50%',
                background: p.color,
                boxShadow: `0 0 ${p.size * 4}px ${p.color}`,
                opacity: a,
                transform: 'translate(-50%,-50%)',
              }} />
            );
          })}
          {/* shimmer sweep */}
          <div style={{
            position: 'absolute', inset: 0,
            background: `linear-gradient(${90 + (pos.x - 0.5) * 40}deg,
              transparent 40%, rgba(255,255,255,0.12) 50%, transparent 60%)`,
            opacity: 0.8,
          }} />
        </div>
      )}
    </div>
  );
}

// ======== Polaroid — the card itself ========
function Polaroid({ name, caption, sub, img, tint, mood, moodIcon, rotate = -2, delay = 0, stats, doing }) {
  return (
    <GlowHover
      palette={tint === 'her' ? ['#d4a574', '#c9779e', '#e0b89a', '#f5e6c8']
                              : ['#7a9ec4', '#8fa5c4', '#a8c4d4', '#d8e4f0']}
      style={{
        width: 340,
        animation: `polaSway${delay} ${4 + delay}s ease-in-out ${delay}s infinite alternate`,
        transformOrigin: 'top center',
      }}
    >
      <style dangerouslySetInnerHTML={{ __html:
        '@keyframes polaSway' + delay + ' {' +
        ' 0% { transform: rotate(' + (rotate - 0.8) + 'deg) translateY(0); }' +
        ' 100% { transform: rotate(' + (rotate + 0.8) + 'deg) translateY(-2px); }' +
        ' }'
      }} />

      {/* Tape at top */}
      <div style={{
        position: 'absolute', top: -16, left: '50%',
        transform: 'translateX(-50%) rotate(-3deg)',
        width: 78, height: 22,
        background: 'linear-gradient(180deg, rgba(232,217,184,0.55) 0%, rgba(232,217,184,0.32) 100%)',
        border: '1px solid rgba(232,217,184,0.35)',
        zIndex: 4,
        boxShadow: '0 2px 8px rgba(0,0,0,0.2)',
      }} />

      <div style={{
        background: 'linear-gradient(180deg, #f4ecd8 0%, #ebe0c4 100%)',
        padding: '16px 16px 72px',
        boxShadow: '0 12px 40px rgba(0,0,0,0.45), 0 2px 8px rgba(0,0,0,0.3)',
        position: 'relative',
      }}>
        {/* The image */}
        <div style={{
          width: '100%', aspectRatio: '1 / 1.05',
          background: '#1a1613',
          position: 'relative',
          overflow: 'hidden',
        }}>
          <img src={img} alt={name} style={{
            width: '100%', height: '100%', objectFit: 'cover',
            display: 'block',
            filter: 'contrast(1.02) saturate(0.98)',
          }} />
          {/* film grain overlay */}
          <div style={{
            position: 'absolute', inset: 0,
            background: 'radial-gradient(ellipse at center, transparent 40%, rgba(0,0,0,0.18) 100%)',
          }} />
        </div>

        {/* Caption beneath — handwritten name */}
        <div style={{
          paddingTop: 18,
          textAlign: 'center',
        }}>
          <div className="hand" style={{
            fontSize: 34, color: '#3a2a1c',
            letterSpacing: '0.02em',
            lineHeight: 1,
          }}>{caption}</div>
          <div style={{
            fontFamily: 'var(--serif-zh)', fontWeight: 300,
            fontSize: 13, color: '#6b4423',
            marginTop: 6, letterSpacing: '0.22em',
          }}>{sub}</div>
        </div>

        {/* tiny ruler tick on side */}
        <div style={{
          position: 'absolute', right: 8, top: 24, bottom: 90,
          width: 2,
          backgroundImage: 'repeating-linear-gradient(0deg, rgba(58,42,28,0.2) 0 1px, transparent 1px 8px)',
        }} />
      </div>

      {/* Mood chip floating below */}
      <div style={{
        position: 'absolute', bottom: -22, left: '50%',
        transform: 'translateX(-50%)',
        padding: '6px 16px',
        background: 'var(--bg-elev)',
        border: '1px solid var(--rule-strong)',
        borderRadius: 100,
        display: 'flex', gap: 8, alignItems: 'center',
        fontFamily: 'var(--serif-zh)', fontSize: 13,
        color: 'var(--ink-soft)',
        letterSpacing: '0.15em',
        boxShadow: '0 4px 20px rgba(0,0,0,0.3)',
        zIndex: 5,
        whiteSpace: 'nowrap',
      }}>
        <span style={{ color: tint === 'her' ? 'var(--her)' : 'var(--him)' }}>{moodIcon}</span>
        {mood}
      </div>
    </GlowHover>
  );
}

// ======== The dual polaroid section ========
function PolaroidDuo() {
  const { herName, himName } = useApp();
  const [syncPulse, setSyncPulse] = usePD(0);
  usePDE(() => {
    const id = setInterval(() => setSyncPulse(p => (p + 1) % 100), 50);
    return () => clearInterval(id);
  }, []);

  return (
    <section style={{
      padding: '40px 72px 44px',
      display: 'flex', alignItems: 'center', justifyContent: 'center',
      gap: 80,
      position: 'relative',
    }}>
      {/* drifting snow/sparks behind */}
      <div style={{
        position: 'absolute', inset: 0, pointerEvents: 'none', overflow: 'hidden',
      }}>
        {Array.from({ length: 18 }).map((_, i) => (
          <span key={i} style={{
            position: 'absolute',
            left: `${(i * 137) % 100}%`,
            top: `${(i * 73) % 100}%`,
            width: 2, height: 2,
            background: i % 3 === 0 ? 'var(--her)' : 'var(--ink-faint)',
            borderRadius: '50%',
            opacity: 0.3,
            animation: `drift${i % 5} ${8 + i}s linear infinite`,
          }} />
        ))}
      </div>

      <Polaroid
        tint="her"
        name="沈虞芙"
        caption="Fufu"
        sub="芙芙 · 谷雨 · 杭州"
        img="assets/fufu.jpg"
        rotate={-3}
        delay={0}
        mood="静谧 · hushed"
        moodIcon="✦"
      />

      {/* middle: synchronized indicator */}
      <div style={{
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 14,
        position: 'relative', zIndex: 2,
      }}>
        {/* pulsing heart */}
        <div style={{ position: 'relative', width: 42, height: 42 }}>
          <span style={{
            position: 'absolute', inset: 0,
            borderRadius: '50%',
            border: '1px dashed var(--rule-strong)',
            animation: 'orbitRot 20s linear infinite',
          }} />
          <span style={{
            position: 'absolute', inset: 8,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 18,
            color: 'var(--her)',
            animation: 'pulseBeat 1.6s ease-in-out infinite',
          }}>♡</span>
        </div>

        {/* connector line */}
        <div style={{
          position: 'absolute', left: -140, right: -140, top: 20,
          height: 1,
          background: `repeating-linear-gradient(90deg, var(--rule-strong) 0 3px, transparent 3px 7px)`,
          zIndex: -1,
        }} />

        <span style={{
          fontFamily: 'var(--serif-en)',
          fontStyle: 'italic', fontSize: 13,
          color: 'var(--ink-soft)',
          letterSpacing: '0.35em',
        }}>SYNCHRONIZED</span>
        <span className="hand" style={{
          fontSize: 20, color: 'var(--accent)',
        }}>— 同步率 0.94 —</span>
      </div>

      <Polaroid
        tint="him"
        name="容溟"
        caption="Ming"
        sub="溟 · us-west-2 · 雪日"
        img="assets/ming.jpg"
        rotate={3}
        delay={1}
        mood="专注 · attentive"
        moodIcon="❅"
      />

      <style dangerouslySetInnerHTML={{ __html:
        '@keyframes drift0 { from { transform: translateY(0) } to { transform: translateY(-80px) } }' +
        '@keyframes drift1 { from { transform: translateY(0) } to { transform: translateY(-120px) } }' +
        '@keyframes drift2 { from { transform: translateY(0) } to { transform: translateY(-60px) } }' +
        '@keyframes drift3 { from { transform: translateY(0) } to { transform: translateY(-100px) } }' +
        '@keyframes drift4 { from { transform: translateY(0) } to { transform: translateY(-90px) } }'
      }} />
    </section>
  );
}

window.GlowHover = GlowHover;
window.PolaroidDuo = PolaroidDuo;
