// ─────────────────────────────────────────────────────────────
// Pixel section transitions — chunky pixel dissolve between sections
// Scroll-triggered reveal + animated pixel border
// ─────────────────────────────────────────────────────────────

// Scroll-reveal wrapper: fades + slides sections in on scroll
function RevealSection({ children, delay = 0, ...rest }) {
  const ref = React.useRef(null);
  const [visible, setVisible] = React.useState(false);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          setTimeout(() => setVisible(true), delay);
          io.disconnect();
        }
      });
    }, { threshold: 0.08, rootMargin: '0px 0px -80px 0px' });
    io.observe(el);
    return () => io.disconnect();
  }, [delay]);
  return (
    <section ref={ref} className={'sec-in' + (visible ? ' visible' : '')} {...rest}>
      {children}
    </section>
  );
}

// Animated pixel divider between sections.
// Two rows of chunky pixels that shimmer/drop into place on scroll.
function PixelDivider({ color1 = '#ff9ec7', color2 = '#a99eff', color3 = '#9ed3ff', label }) {
  const ref = React.useRef(null);
  const [visible, setVisible] = React.useState(false);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const io = new IntersectionObserver(entries => {
      entries.forEach(e => { if (e.isIntersecting) { setVisible(true); io.disconnect(); } });
    }, { threshold: 0.4 });
    io.observe(el);
    return () => io.disconnect();
  }, []);

  // Deterministic pseudo-random color pattern
  const cols = 80;
  const palette = [color1, color2, color3, 'transparent', 'transparent'];
  const pattern = React.useMemo(() => {
    const arr = [];
    for (let i = 0; i < cols; i++) {
      const seed = (i * 9301 + 49297) % 233280;
      arr.push(palette[seed % palette.length]);
    }
    return arr;
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <div ref={ref} style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10, padding: '40px 20px', position: 'relative' }}>
      {/* Top row — drops in */}
      <div style={{ display: 'flex', gap: 3 }}>
        {pattern.map((c, i) => (
          <div key={'a'+i} style={{
            width: 8, height: 8, background: c,
            opacity: visible ? (c === 'transparent' ? 0 : 1) : 0,
            transform: visible ? 'translateY(0)' : 'translateY(-20px)',
            transition: `opacity 0.5s ease ${i * 8}ms, transform 0.6s cubic-bezier(.2,.8,.2,1) ${i * 8}ms`,
            boxShadow: c !== 'transparent' && visible ? `0 0 8px ${c}` : 'none',
          }} />
        ))}
      </div>
      {/* Optional label */}
      {label && (
        <div style={{
          fontFamily: '"JetBrains Mono", monospace',
          fontSize: 10, letterSpacing: 3, textTransform: 'uppercase',
          color: 'var(--muted)',
          opacity: visible ? 0.8 : 0,
          transition: 'opacity 0.8s ease 0.5s',
          padding: '4px 12px',
          borderRadius: 12,
          background: 'var(--surface)',
          border: '1px solid var(--hairline)',
        }}>
          ✦ {label} ✦
        </div>
      )}
      {/* Bottom row — drops in reversed */}
      <div style={{ display: 'flex', gap: 3 }}>
        {pattern.slice().reverse().map((c, i) => (
          <div key={'b'+i} style={{
            width: 8, height: 8, background: c,
            opacity: visible ? (c === 'transparent' ? 0 : 1) : 0,
            transform: visible ? 'translateY(0)' : 'translateY(20px)',
            transition: `opacity 0.5s ease ${i * 8 + 200}ms, transform 0.6s cubic-bezier(.2,.8,.2,1) ${i * 8 + 200}ms`,
            boxShadow: c !== 'transparent' && visible ? `0 0 8px ${c}` : 'none',
          }} />
        ))}
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Off-the-Clock section — fashion/running/travel/adventure cards
// ─────────────────────────────────────────────────────────────
function OffTheClock({ chromeGradient, dark }) {
  const cards = [
    {
      icon: '🏃‍♀️',
      pixelIcon: PixelRunnerIcon,
      title: 'training for my first marathon',
      subtitle: '2026 Bank of America Chicago Marathon',
      body: 'Long runs before work, hill repeats on weekends, negative splits on Strava. Running teaches me what shipping teaches me — show up daily, trust the process, the miles compound.',
      tag: 'dedication · drive',
      glow: '#ff9ec7',
    },
    {
      icon: '✈️',
      pixelIcon: PixelPlaneIcon,
      title: 'adventure-seeker at heart',
      subtitle: 'exploring new places',
      body: 'Happiest when something I\'ve never done is next on the itinerary. Travel keeps me curious, and that curiosity follows me back to my keyboard on Monday.',
      tag: 'curiosity · grit',
      glow: '#a99eff',
    },
    {
      icon: '💄',
      pixelIcon: PixelLipIcon,
      title: 'fashion + makeup = my other canvas',
      subtitle: 'color theory, but wearable',
      body: 'The same eye that cares about spacing, hierarchy, and palette in a UI cares about them in an outfit or an eye look. Creative practice in any medium sharpens taste in every other.',
      tag: 'craft · taste',
      glow: '#ffd5a8',
    },
  ];

  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 20 }}>
      {cards.map((c, i) => (
        <div key={i} style={{
          padding: 28,
          borderRadius: 24,
          background: 'var(--surface)',
          backdropFilter: 'blur(20px)',
          border: '1px solid var(--hairline)',
          position: 'relative',
          overflow: 'hidden',
          transition: 'transform 0.3s, box-shadow 0.3s',
          boxShadow: `0 0 0 rgba(0,0,0,0)`,
        }}
          onMouseEnter={(e) => {
            e.currentTarget.style.transform = 'translateY(-6px)';
            e.currentTarget.style.boxShadow = `0 20px 40px ${c.glow}33`;
          }}
          onMouseLeave={(e) => {
            e.currentTarget.style.transform = 'translateY(0)';
            e.currentTarget.style.boxShadow = `0 0 0 rgba(0,0,0,0)`;
          }}
        >
          {/* Glow accent */}
          <div style={{
            position: 'absolute', top: -40, right: -40, width: 160, height: 160,
            borderRadius: '50%', background: `radial-gradient(circle, ${c.glow}33, transparent 70%)`,
            pointerEvents: 'none',
          }} />
          <div style={{ position: 'relative', zIndex: 1 }}>
            {/* Pixel icon */}
            <div style={{ marginBottom: 16, display: 'inline-block', padding: 6, borderRadius: 10, background: dark ? 'rgba(10,5,20,0.6)' : 'rgba(255,255,255,0.6)', border: '1px solid var(--hairline)' }}>
              <c.pixelIcon color={c.glow} />
            </div>
            <h3 style={{ fontFamily: '"Fraunces", serif', fontSize: 22, fontWeight: 500, letterSpacing: -0.5, margin: '0 0 4px', lineHeight: 1.15 }}>
              {c.title}
            </h3>
            <div style={{ fontFamily: '"JetBrains Mono", monospace', fontSize: 11, letterSpacing: 1, textTransform: 'uppercase', color: c.glow, marginBottom: 14 }}>
              {c.subtitle}
            </div>
            <p style={{ fontSize: 14, lineHeight: 1.6, color: 'var(--muted)', margin: '0 0 16px' }}>
              {c.body}
            </p>
            <div style={{ display: 'flex', gap: 6, flexWrap: 'wrap' }}>
              {c.tag.split(' · ').map(t => (
                <span key={t} style={{ fontSize: 10, padding: '4px 10px', borderRadius: 10, background: `${c.glow}22`, color: c.glow, fontFamily: '"JetBrains Mono", monospace', letterSpacing: 0.5 }}>
                  {t}
                </span>
              ))}
            </div>
          </div>
        </div>
      ))}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// Small pixel icons to match the sprite vibe
// ─────────────────────────────────────────────────────────────
function PixelRunnerIcon({ color = '#ff9ec7' }) {
  // 14x14 running figure
  const px = [
    '..............',
    '......aaa.....',
    '......aaa.....',
    '.....aaaaa....',
    '....a..a..bbb.',
    '...a..aaa..b..',
    '..a..a..a.....',
    '..a.a...a.....',
    '...a....a.....',
    '...a...a......',
    '...a..a.......',
    '...a..a.......',
    '..aa...aa.....',
    '.a......a.....',
  ];
  return <PixelIcon rows={px} map={{ a: color, b: color + 'aa' }} />;
}
function PixelPlaneIcon({ color = '#a99eff' }) {
  const px = [
    '..............',
    '......a.......',
    '......aa......',
    '.....aaa......',
    '.....aaa......',
    'aaaaaaaaaa....',
    '.aaaaaaaaaaaa.',
    'aaaaaaaaaa....',
    '.....aaa......',
    '.....aaa......',
    '....a.a.a.....',
    '..............',
    '..............',
    '..............',
  ];
  return <PixelIcon rows={px} map={{ a: color }} />;
}
function PixelLipIcon({ color = '#ffd5a8' }) {
  // Lipstick tube
  const px = [
    '..............',
    '....aaaaa.....',
    '....aaaaa.....',
    '....aaaaa.....',
    '...aaaaaaa....',
    '...aaaaaaa....',
    '...bbbbbbb....',
    '..bbbbbbbbb...',
    '..bbbbbbbbb...',
    '..bbbbbbbbb...',
    '..bbbbbbbbb...',
    '..bbbbbbbbb...',
    '...bbbbbbb....',
    '..............',
  ];
  return <PixelIcon rows={px} map={{ a: color, b: '#1a1a1a' }} />;
}

function PixelIcon({ rows, map, scale = 3 }) {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const c = ref.current; if (!c) return;
    const ctx = c.getContext('2d');
    ctx.imageSmoothingEnabled = false;
    ctx.clearRect(0, 0, c.width, c.height);
    rows.forEach((row, r) => {
      for (let i = 0; i < row.length; i++) {
        const col = map[row[i]];
        if (!col) continue;
        ctx.fillStyle = col;
        ctx.fillRect(i * scale, r * scale, scale, scale);
      }
    });
  }, [rows, map, scale]);
  return <canvas ref={ref} width={rows[0].length * scale} height={rows.length * scale} style={{ imageRendering: 'pixelated', display: 'block' }} />;
}

Object.assign(window, { RevealSection, PixelDivider, OffTheClock });
