/* Birthday effects — all visible-always pieces. Loaded only when birthday === true. */

const { useEffect, useRef, useState } = React;

/* 1. Persistent confetti drift — sparse + slow, never stops */
function BirthdayDrift() {
  const [pieces] = useState(() => {
    const colors = ['#F5C518', '#B8362B', '#F3E6C4'];
    const shapes = ['rect', 'diamond', 'circle'];
    return Array.from({ length: 14 }, (_, i) => ({
      id: i,
      left: Math.random() * 100,
      delay: Math.random() * 14,
      duration: 16 + Math.random() * 14,
      size: 5 + Math.random() * 7,
      color: colors[i % colors.length],
      shape: shapes[i % shapes.length],
      drift: (Math.random() - 0.5) * 120,
      rot: Math.random() * 360,
      rotEnd: Math.random() * 720
    }));
  });
  return (
    <div aria-hidden="true" style={{
      position: 'fixed', inset: 0, pointerEvents: 'none',
      zIndex: 40, overflow: 'hidden', opacity: 0.55
    }}>
      {pieces.map(p => (
        <span key={p.id} style={{
          position: 'absolute', top: -30, left: `${p.left}%`,
          width: p.size, height: p.shape === 'circle' ? p.size : p.size * 1.4,
          background: p.color,
          borderRadius: p.shape === 'circle' ? '50%' : 1,
          transform: p.shape === 'diamond' ? 'rotate(45deg)' : undefined,
          animation: `bcb-drift ${p.duration}s linear ${p.delay}s infinite`,
          '--drift': `${p.drift}px`,
          '--rot': `${p.rot}deg`,
          '--rotEnd': `${p.rotEnd}deg`
        }} />
      ))}
    </div>
  );
}

/* 2. Bunting — triangle flags strung across the top */
function Bunting() {
  const colors = ['#F5C518', '#B8362B', '#F3E6C4', '#1A1613', '#F5C518', '#B8362B', '#F3E6C4', '#1A1613'];
  const flags = Array.from({ length: 28 }, (_, i) => colors[i % colors.length]);
  // Hangs INTO the hero, below the ribbon. Absolute so it doesn't push layout.
  return (
    <div aria-hidden="true" style={{
      position: 'absolute', left: 0, right: 0, top: 0, zIndex: 4,
      pointerEvents: 'none', height: 42
    }}>
      <svg width="100%" height="32" style={{ position: 'absolute', top: 0, left: 0 }} preserveAspectRatio="none">
        <path d="M 0 2 Q 50% 22, 100% 2" stroke="rgba(243,230,196,0.45)" strokeWidth="1.2" fill="none" />
      </svg>
      <div style={{
        position: 'relative', width: '100%', height: '100%',
        display: 'flex', justifyContent: 'space-around', alignItems: 'flex-start',
        paddingTop: 2
      }}>
        {flags.map((c, i) => (
          <span key={i} style={{
            width: 0, height: 0,
            borderLeft: '9px solid transparent',
            borderRight: '9px solid transparent',
            borderTop: `22px solid ${c}`,
            transform: `translateY(${i % 2 === 0 ? 4 : 10}px) rotate(${(i % 2 === 0 ? -3 : 3)}deg)`,
            filter: 'drop-shadow(2px 2px 0 rgba(0,0,0,0.35))',
            animation: `bcb-flagsway ${3 + (i % 3) * 0.4}s ease-in-out ${i * 0.05}s infinite alternate`
          }} />
        ))}
      </div>
    </div>
  );
}

/* 3. Animated cake logo — little birthday cake with a flickering candle */
function CandleLogo({ size = 28 }) {
  return (
    <span style={{
      width: size, height: size, borderRadius: 999, background: 'var(--mustard)',
      display: 'inline-grid', placeItems: 'center', position: 'relative',
      border: '2px solid var(--ink)'
    }}>
      <svg width={size * 0.78} height={size * 0.78} viewBox="0 0 24 24" aria-hidden="true">
        {/* Plate */}
        <ellipse cx="12" cy="20.5" rx="9" ry="1.2" fill="#1A1613" opacity="0.35" />
        {/* Bottom tier (frosting base) */}
        <rect x="3.5" y="14" width="17" height="6" fill="#F3E6C4" stroke="#1A1613" strokeWidth="0.6" />
        {/* Drip frosting on bottom */}
        <path d="M 3.5 14 Q 5 16, 6.5 14 Q 8 16.5, 9.5 14 Q 11 16, 12.5 14 Q 14 16.5, 15.5 14 Q 17 16, 18.5 14 Q 19.7 15.6, 20.5 14"
              fill="#B8362B" stroke="#1A1613" strokeWidth="0.5" strokeLinejoin="round" />
        {/* Top tier */}
        <rect x="6" y="9" width="12" height="5" fill="#F3E6C4" stroke="#1A1613" strokeWidth="0.6" />
        <path d="M 6 9 Q 7.5 10.8, 9 9 Q 10.5 10.8, 12 9 Q 13.5 10.8, 15 9 Q 16.5 10.8, 18 9"
              fill="#B8362B" stroke="#1A1613" strokeWidth="0.5" strokeLinejoin="round" />
        {/* Cherry on top */}
        <circle cx="12" cy="8" r="0.9" fill="#B8362B" />
        {/* Candle */}
        <rect x="11.3" y="4.5" width="1.4" height="3.2" fill="#1A1613" />
        {/* Flame */}
        <ellipse cx="12" cy="3.3" rx="0.9" ry="1.6" fill="#F5C518">
          <animate attributeName="ry" values="1.6;1.9;1.4;1.7;1.6" dur="1.2s" repeatCount="indefinite" />
          <animate attributeName="fill" values="#F5C518;#FFE27A;#F5C518" dur="1.2s" repeatCount="indefinite" />
        </ellipse>
      </svg>
    </span>
  );
}

/* 4. "+1 YEAR" lapel sticker for the hero corner */
function BirthdaySticker() {
  return (
    <div aria-hidden="true" style={{
      position: 'absolute', top: -81, right: 28, zIndex: 3,
      transform: 'rotate(-8deg)',
      width: 130, height: 130, borderRadius: '50%',
      background: 'var(--mustard)',
      color: 'var(--ink)',
      display: 'grid', placeItems: 'center',
      border: '3px solid var(--ink)',
      boxShadow: '6px 6px 0 var(--brick), inset 0 0 0 2px var(--cream)',
      fontFamily: 'Archivo Black, sans-serif', letterSpacing: 0.5,
      animation: 'bcb-stickerwobble 5s ease-in-out infinite'
    }}>
      <div style={{ textAlign: 'center', lineHeight: 1 }}>
        <div style={{ fontSize: 12, opacity: 0.8, letterSpacing: 1.5 }}>SPECIAL</div>
        <div style={{ fontSize: 32, margin: '2px 0', color: 'var(--brick)' }}>+1</div>
        <div style={{ fontSize: 12, letterSpacing: 1.5 }}>YEAR</div>
      </div>
    </div>
  );
}

/* 5. Edge balloons — slow rising SVG balloons, looping */
function Balloons() {
  const configs = [
    { side: 'left',  x: '2%',  color: '#B8362B', delay: 0,  dur: 22, sway: 30 },
    { side: 'right', x: '94%', color: '#F5C518', delay: 7,  dur: 26, sway: -24 },
    { side: 'left',  x: '8%',  color: '#F3E6C4', delay: 14, dur: 30, sway: 18 },
    { side: 'right', x: '88%', color: '#B8362B', delay: 20, dur: 24, sway: -20 }
  ];
  return (
    <div aria-hidden="true" style={{
      position: 'fixed', inset: 0, pointerEvents: 'none', zIndex: 42, overflow: 'hidden'
    }}>
      {configs.map((c, i) => (
        <div key={i} style={{
          position: 'absolute', bottom: -120, left: c.x,
          animation: `bcb-rise ${c.dur}s linear ${c.delay}s infinite`,
          '--sway': `${c.sway}px`
        }}>
          <svg width="52" height="86" viewBox="0 0 52 86" style={{
            animation: `bcb-balloonsway 3.5s ease-in-out infinite alternate`,
            transformOrigin: '50% 100%'
          }}>
            <ellipse cx="26" cy="30" rx="22" ry="26" fill={c.color}
                     stroke="rgba(0,0,0,0.25)" strokeWidth="1" />
            <ellipse cx="20" cy="22" rx="5" ry="8" fill="rgba(255,255,255,0.35)" />
            <polygon points="23,56 29,56 26,60" fill={c.color} stroke="rgba(0,0,0,0.25)" strokeWidth="0.8" />
            <path d="M 26 60 Q 22 68, 26 76 Q 30 80, 26 86" stroke="rgba(243,230,196,0.75)" strokeWidth="1" fill="none" />
          </svg>
        </div>
      ))}
    </div>
  );
}

/* 6. Section streamer — wavy divider */
function Streamer({ flip = false }) {
  return (
    <div aria-hidden="true" style={{ height: 22, overflow: 'hidden', background: 'var(--ink)', position: 'relative' }}>
      <svg viewBox="0 0 1200 22" preserveAspectRatio="none"
           style={{ width: '100%', height: '100%', transform: flip ? 'scaleY(-1)' : 'none' }}>
        <path d="M0 12 Q 60 -4, 120 12 T 240 12 T 360 12 T 480 12 T 600 12 T 720 12 T 840 12 T 960 12 T 1080 12 T 1200 12 L 1200 22 L 0 22 Z"
              fill="var(--mustard)" />
        <path d="M0 16 Q 60 2, 120 16 T 240 16 T 360 16 T 480 16 T 600 16 T 720 16 T 840 16 T 960 16 T 1080 16 T 1200 16 L 1200 22 L 0 22 Z"
              fill="var(--brick)" opacity="0.8" />
      </svg>
    </div>
  );
}

/* 7. Sparkle glints — small ✦ marks around the Ben headline */
function Sparkles() {
  const s = [
    { top: '8%',  left: '12%', size: 14, delay: 0 },
    { top: '22%', left: '78%', size: 22, delay: 0.6 },
    { top: '55%', left: '6%',  size: 18, delay: 1.1 },
    { top: '70%', left: '82%', size: 14, delay: 1.7 },
    { top: '40%', left: '45%', size: 12, delay: 2.2 }
  ];
  return (
    <div aria-hidden="true" style={{ position: 'absolute', inset: 0, pointerEvents: 'none', zIndex: 2 }}>
      {s.map((p, i) => (
        <svg key={i} width={p.size} height={p.size} viewBox="0 0 24 24"
             style={{
               position: 'absolute', top: p.top, left: p.left,
               animation: `bcb-twinkle 2.4s ease-in-out ${p.delay}s infinite`,
               color: 'var(--mustard)',
               filter: 'drop-shadow(0 0 6px rgba(245,197,24,0.8))'
             }}>
          <path d="M 12 2 L 13.5 10.5 L 22 12 L 13.5 13.5 L 12 22 L 10.5 13.5 L 2 12 L 10.5 10.5 Z"
                fill="currentColor" />
        </svg>
      ))}
    </div>
  );
}

/* 9. Cursor sparkle trail */
function CursorTrail() {
  const [dots, setDots] = useState([]);
  const idRef = useRef(0);
  useEffect(() => {
    let last = 0;
    const onMove = (e) => {
      const now = performance.now();
      if (now - last < 40) return;
      last = now;
      const id = ++idRef.current;
      setDots(d => [...d.slice(-12), { id, x: e.clientX, y: e.clientY }]);
      setTimeout(() => setDots(d => d.filter(x => x.id !== id)), 700);
    };
    window.addEventListener('mousemove', onMove);
    return () => window.removeEventListener('mousemove', onMove);
  }, []);
  return (
    <div aria-hidden="true" style={{
      position: 'fixed', inset: 0, pointerEvents: 'none', zIndex: 95
    }}>
      {dots.map(d => (
        <span key={d.id} style={{
          position: 'fixed', left: d.x - 4, top: d.y - 4,
          width: 8, height: 8, background: 'var(--mustard)', borderRadius: '50%',
          boxShadow: '0 0 8px rgba(245,197,24,0.9)',
          animation: 'bcb-trailfade 700ms ease-out forwards'
        }} />
      ))}
    </div>
  );
}

/* 11. Floating envelope — opens a card overlay */
function BirthdayCard() {
  const [open, setOpen] = useState(false);
  return (
    <>
      <button
        onClick={() => setOpen(true)}
        aria-label="Open birthday card"
        style={{
          position: 'fixed', right: 24, bottom: 24, zIndex: 70,
          width: 64, height: 64, borderRadius: '50%',
          background: 'var(--mustard)', color: 'var(--ink)',
          border: '2px solid var(--ink)',
          boxShadow: '4px 4px 0 var(--brick)',
          cursor: 'pointer', display: 'grid', placeItems: 'center',
          animation: 'bcb-jiggle 3s ease-in-out infinite'
        }}>
        <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
          <rect x="3" y="5" width="18" height="14" rx="1" />
          <path d="M3 7 L12 13 L21 7" />
        </svg>
        <span style={{
          position: 'absolute', top: -6, right: -6,
          width: 20, height: 20, borderRadius: '50%',
          background: 'var(--brick)', color: 'var(--cream)',
          fontFamily: 'Archivo Black, sans-serif', fontSize: 11,
          display: 'grid', placeItems: 'center'
        }}>1</span>
      </button>
      {open && (
        <div role="dialog" aria-modal="true" onClick={() => setOpen(false)}
             style={{
               position: 'fixed', inset: 0, zIndex: 100,
               background: 'rgba(0,0,0,0.7)', display: 'grid', placeItems: 'center',
               padding: 20, backdropFilter: 'blur(4px)',
               animation: 'bcb-fadein 280ms ease'
             }}>
          <div onClick={(e) => e.stopPropagation()}
               style={{
                 maxWidth: 560, background: 'var(--cream)', color: 'var(--ink)',
                 padding: '40px 44px', position: 'relative',
                 border: '2px solid var(--ink)',
                 boxShadow: '14px 14px 0 var(--brick)',
                 fontFamily: 'Inter, sans-serif',
                 animation: 'bcb-cardopen 380ms cubic-bezier(.2,.7,.2,1)'
               }}>
            <button onClick={() => setOpen(false)}
                    style={{
                      position: 'absolute', top: 12, right: 12,
                      background: 'transparent', border: 'none', cursor: 'pointer',
                      fontFamily: 'IBM Plex Mono, monospace', fontSize: 12, letterSpacing: 2
                    }}>CLOSE ✕</button>
            <div style={{
              fontFamily: 'IBM Plex Mono, monospace', fontSize: 11,
              letterSpacing: 2, opacity: 0.6
            }}>FROM THE TEAM · 04.23</div>
            <h3 style={{
              fontFamily: 'Archivo Black, sans-serif', fontSize: 40,
              letterSpacing: -1, margin: '6px 0 14px', lineHeight: 1
            }}>Happy Birthday, <span style={{ color: 'var(--brick)' }}>Ben.</span></h3>
            <p style={{ margin: '0 0 14px', lineHeight: 1.6, fontSize: 15 }}>
              Thanks for the quiet fixes, the calm pages, and the code reviews that
              say more in two lines than most of us say in thirty. The on-call rotation
              feels safer because you're in it.
            </p>
            <p style={{ margin: '0 0 18px', lineHeight: 1.6, fontSize: 15 }}>
              Take today off. We'll be fine. (We'll call if we aren't.)
            </p>
            <div style={{
              paddingTop: 14, borderTop: '1px dashed rgba(0,0,0,0.3)',
              fontFamily: 'IBM Plex Mono, monospace', fontSize: 12, letterSpacing: 1
            }}>
              — Signed, the team · all of us
            </div>
          </div>
        </div>
      )}
    </>
  );
}

/* Bundle them — one component to mount */
function BirthdayLayer() {
  return (
    <>
      <BirthdayDrift />
      <Balloons />
      <CursorTrail />
      <BirthdayCard />
    </>
  );
}

Object.assign(window, {
  BirthdayDrift, Bunting, CandleLogo, BirthdaySticker, Balloons,
  Streamer, Sparkles, CursorTrail, BirthdayCard, BirthdayLayer
});
