// Skill stack — sticky-stacking left cards + a right photo card whose caption
// swaps based on which skill is currently in view. The MORPH PHOTO that lives
// in the right column is rendered as a fixed-position element by SiteSplit;
// here we just reserve the column space and broadcast the active index.

function SkillsSticky({ p, lang, onActiveChange }) {
  const ss = window.COPY[lang].split.skillsSection;
  const skills = window.COPY[lang].split.skills;
  const refs = React.useRef([]);

  React.useEffect(() => {
    const obs = new IntersectionObserver((entries) => {
      // Pick the entry whose target center is closest to viewport center —
      // more stable than "first intersecting" when two cards overlap.
      let best = -1, bestDist = Infinity;
      const vc = window.innerHeight / 2;
      refs.current.forEach((el, i) => {
        if (!el) return;
        const r = el.getBoundingClientRect();
        const c = r.top + r.height / 2;
        const d = Math.abs(c - vc);
        if (d < bestDist) { bestDist = d; best = i; }
      });
      if (best >= 0) onActiveChange(best);
    }, { threshold: [0, 0.25, 0.5, 0.75, 1], rootMargin: '-20% 0px -30% 0px' });

    refs.current.forEach((el) => el && obs.observe(el));
    return () => obs.disconnect();
  }, [skills.length, onActiveChange]);

  const { eyebrow: eyebrowLabel, title, titleEm, sub } = ss;

  return (
    <section id="skills" style={{ position: 'relative', zIndex: 1, padding: '80px 56px 80px' }}>
      <div style={{
        display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 80,
        position: 'relative', alignItems: 'start',
      }}>
        {/* LEFT: title + sticky-stacking skill cards */}
        <div>
          {/* Section header — scrolls naturally, then skill cards stack over it */}
          <div style={{
            position: 'sticky', top: 24, zIndex: 10,
            marginBottom: 40,
            paddingBottom: 20,
            background: `linear-gradient(180deg, ${p.bg} 85%, transparent)`,
          }}>
            <div style={{
              fontFamily: '"Caveat", "Patrick Hand", cursive',
              fontSize: 24, color: p.muted, marginBottom: 12,
            }}>
              {eyebrowLabel}
            </div>
            <h2 style={{
              margin: 0, fontFamily: '"Archivo", sans-serif', fontWeight: 900,
              fontSize: 'clamp(42px, 5vw, 76px)', letterSpacing: '-0.035em',
              lineHeight: 1.02,
            }}>
              {title.replace(titleEm, '')}
              <span style={{ color: p.accent }}>{titleEm}</span>
            </h2>
            <p style={{ marginTop: 18, fontSize: 17, lineHeight: 1.55, color: p.muted, maxWidth: 600 }}>
              {sub}
            </p>
          </div>
          {skills.map((s, i) => (
            <SkillCard
              key={i} s={s} i={i} total={skills.length} p={p}
              setRef={(el) => (refs.current[i] = el)}
            />
          ))}
        </div>

        {/* RIGHT: reserves space — the actual morph-photo is fixed-position
            and drawn by SiteSplit. The anchor below is sticky-positioned so
            the morph photo locks at top:140 while the user scrolls the skill
            stack. */}
        <div aria-hidden="true" style={{
          minHeight: skills.length * 460,
          position: 'relative',
        }}>
          <div id="skills-photo-anchor" style={{
            position: 'sticky', top: 24,
            width: 'min(340px, 24vw)', aspectRatio: '4 / 5',
            marginLeft: 'auto',
          }} />
        </div>
      </div>
    </section>
  );
}

function SkillCard({ s, i, total, p, setRef }) {
  const [h, setH] = React.useState(false);
  return (
    <div
      ref={setRef}
      onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      style={{
        position: 'sticky',
        // Stagger top so cards peek out behind each other when stacked.
        // Start below the sticky title (~280px)
        top: `${290 + i * 22}px`,
        marginBottom: i === total - 1 ? 0 : 260,
        zIndex: i + 1,
        padding: '36px 36px 40px',
        borderRadius: 28,
        background: '#fff',
        border: `1px solid ${p.line}`,
        boxShadow: h
          ? '0 40px 60px -22px rgba(0,0,0,0.20), 0 12px 22px -10px rgba(0,0,0,0.12)'
          : '0 22px 40px -18px rgba(0,0,0,0.18), 0 8px 16px -8px rgba(0,0,0,0.10)',
        transition: 'box-shadow .25s, transform .25s',
        transform: h ? 'translateY(-2px)' : 'translateY(0)',
      }}
    >
      <div style={{
        fontFamily: '"Caveat", "Patrick Hand", cursive',
        fontSize: 22, color: p.muted, marginBottom: 28,
      }}>
        {s.label}
      </div>
      <h3 style={{
        margin: 0, fontFamily: '"Archivo", sans-serif', fontWeight: 900,
        fontSize: 'clamp(34px, 3.6vw, 52px)',
        letterSpacing: '-0.03em', lineHeight: 1.02,
      }}>
        <span style={{ color: p.accent }}>{s.n}.</span> {s.t}
      </h3>
      <p style={{
        margin: '24px 0 0', fontSize: 17, lineHeight: 1.55, color: p.muted,
        maxWidth: 520,
      }}>
        {s.d}
      </p>
      <ul style={{
        margin: '36px 0 0', padding: 0, listStyle: 'none',
        color: p.muted, fontSize: 15, lineHeight: 1.85,
      }}>
        {s.tools.map((t) => (
          <li key={t} style={{ paddingLeft: 18, position: 'relative' }}>
            <span style={{
              position: 'absolute', left: 0, top: '0.55em',
              width: 5, height: 5, borderRadius: '50%', background: p.muted,
            }} />
            {t}
          </li>
        ))}
      </ul>
    </div>
  );
}

Object.assign(window, { SkillsSticky });
