// Direction A v3 — simplified nav, scroll-driven cards animation
const PortfolioA = () => {
  const [scrollY, setScrollY] = React.useState(0);
  const [navHidden, setNavHidden] = React.useState(false);
  const [heroBottom, setHeroBottom] = React.useState(800);
  const [workTop, setWorkTop] = React.useState(1400);
  const [cardSlots, setCardSlots] = React.useState([]); // measured target slots in work grid
  const lastY = React.useRef(0);
  const rootRef = React.useRef(null);
  const heroRef = React.useRef(null);
  const workRef = React.useRef(null);
  const slotRefs = React.useRef([]);
  const pileRef = React.useRef(null);
  const [pileBox, setPileBox] = React.useState(null);
  const [revealed, setRevealed] = React.useState(new Set());

  const projects = [
    { id: 'luna', tag: 'Cross-platform · 2024', title: 'Couch Gaming', sub: 'A revamped cloud-gaming that offers a wide variety of top-tier games.', metric: '+18% attach', tone: '#3D5A6C', accent: '#DBEAFE', thumb: 'images/luna-thumbnail.png', href: 'luna.html' },
    { id: 'fanquest', tag: 'Campaign · 2025', title: 'Music trivia game', sub: 'A trivia campaign that rewarded music knowledge and fandom.', metric: '2.3M plays · wk 1', tone: '#5B6B4A', accent: '#E8F0DC', thumb: 'images/fq-hero.png', href: 'fanquest.html' },
    { id: 'easter', tag: 'Easter Egg · 2023', title: 'Hidden games', sub: 'A small, deliberate surprise tucked into a familiar surface. ', metric: '12k discovered', tone: '#7C5E3C', accent: '#F5E8D0', thumb: 'images/hidden-games-hero.jpg', href: 'hidden-games.html' },
  ];

  // Organic pile origin transforms (scattered look). Stable per index.
  const pileOrigins = [
    { x: 24,  y: 0,   r: -7 },
    { x: -16, y: 72,  r: 5  },
    { x: 48,  y: 144, r: -3 },
    { x: 12,  y: 216, r: 8  },
  ];

  // Measure target slots and section positions
  const measure = React.useCallback(() => {
    const root = rootRef.current;
    if (!root || !heroRef.current || !workRef.current) return;
    const rootRect = root.getBoundingClientRect();
    const heroRect = heroRef.current.getBoundingClientRect();
    const workRect = workRef.current.getBoundingClientRect();
    setHeroBottom(heroRect.bottom - rootRect.top + root.scrollTop);
    setWorkTop(workRect.top - rootRect.top + root.scrollTop);
    if (pileRef.current) {
      const pr = pileRef.current.getBoundingClientRect();
      setPileBox({
        left: pr.left - rootRect.left,
        top: pr.top - rootRect.top + root.scrollTop,
        width: pr.width,
        height: pr.height,
      });
    }
    const slots = slotRefs.current.map(el => {
      if (!el) return null;
      const r = el.getBoundingClientRect();
      return {
        left: r.left - rootRect.left,
        top: r.top - rootRect.top + root.scrollTop,
        width: r.width,
        height: r.height,
      };
    });
    setCardSlots(slots);
  }, []);

  React.useEffect(() => {
    const root = rootRef.current;
    if (!root) return;
    measure();
    const onScroll = () => {
      const y = root.scrollTop;
      setScrollY(y);
      setNavHidden(y > lastY.current && y > 120);
      lastY.current = y;
    };
    const onResize = () => measure();
    root.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', onResize);
    const ro = new ResizeObserver(onResize);
    ro.observe(root);
    // re-measure after fonts/images settle
    const tA = setTimeout(measure, 100);
    const tB = setTimeout(measure, 400);
    return () => {
      root.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onResize);
      ro.disconnect();
      clearTimeout(tA);
      clearTimeout(tB);
    };
  }, [measure]);

  React.useEffect(() => {
    const root = rootRef.current;
    if (!root) return;
    // Robust reveal: bounding-box check on scroll + initial passes (no IntersectionObserver dependency)
    const checkReveal = () => {
      const h = root.clientHeight;
      const rootTop = root.getBoundingClientRect().top;
      const add = [];
      root.querySelectorAll('[data-reveal]').forEach(el => {
        const r = el.getBoundingClientRect();
        const relTop = r.top - rootTop;
        if (relTop < h * 0.92 && r.bottom - rootTop > 0) add.push(el.dataset.reveal);
      });
      if (add.length) setRevealed(prev => {
        const next = new Set(prev);
        let changed = false;
        add.forEach(k => { if (!next.has(k)) { next.add(k); changed = true; } });
        return changed ? next : prev;
      });
    };
    const onScroll = () => checkReveal();
    root.addEventListener('scroll', onScroll, { passive: true });
    window.addEventListener('resize', checkReveal);
    checkReveal();
    const t1 = setTimeout(checkReveal, 120);
    const t2 = setTimeout(checkReveal, 400);
    return () => {
      root.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', checkReveal);
      clearTimeout(t1); clearTimeout(t2);
    };
  }, []);

  // Compute pile-to-grid progress.
  // Animation runs from scrollY = 0 (full pile) to scrollY = heroBottom - 200 (cards in slots).
  const animEnd = Math.max(400, heroBottom - 200);
  const progress = Math.max(0, Math.min(1, scrollY / animEnd));

  // Pile area (right side of hero) — measured area for cards while in pile
  const pileArea = { left: '54%', top: 220, width: 360, height: 360 }; // visual hint area (CSS positioned)

  return (
    <div ref={rootRef} className="pa-root">
      {/* FLOATING NAV */}
      <nav className={`pa-nav ${navHidden ? 'is-hidden' : ''} ${scrollY > 40 ? 'is-scrolled' : ''}`}>
        <div className="pa-nav-inner">
          <a className="pa-mark" href="#top">
            <span className="pa-mark-avatar">
              <img className="pa-mark-photo" src="images/bhavya-portrait.jpg" alt="Bhavya Parashar" />
            </span>
            <span className="pa-mark-name">Bhavya Parashar</span>
          </a>
          <div className="pa-nav-links">
            <a href="#work">Work</a>
            <a href="#about">About</a>
            <a href="arts.html" className="pa-nav-link-end">Art</a>
          </div>
        </div>
      </nav>

      {/* HERO */}
      <section className="pa-hero" id="top" ref={heroRef}>
        <div className="pa-hero-grid">
          <div className="pa-hero-main">
            <h1 className="pa-h1" data-reveal="h1" data-on={revealed.has('h1')}>
              <span className="pa-h1-line">
                <span className="pa-mask"><span>Creating</span></span>
              </span>
              <span className="pa-h1-line pa-h1-accent">
                <span className="pa-mask"><span>human-centered</span></span>
              </span>
              <span className="pa-h1-line">
                <span className="pa-mask"><span>goodness,</span></span>
              </span>
              <span className="pa-h1-line">
                <span className="pa-mask"><span>from discovery</span></span>
              </span>
              <span className="pa-h1-line">
                <span className="pa-mask"><span>to delivery.</span></span>
              </span>
            </h1>
          </div>

          {/* Pile area — visual placeholder. Cards render absolutely above this. */}
          <div className="pa-hero-pile-area" aria-hidden="true" ref={pileRef}>
            <div className="pa-pile-hint" style={{ opacity: Math.max(0, 1 - progress * 1.5) }}>
              <span className="pa-mono">— Selected work</span>
              <span className="pa-pile-hint-sub">Scroll to deal</span>
            </div>
          </div>
        </div>
      </section>

      {/* WORK */}
      <section className="pa-section" id="work" ref={workRef}>
        <header className="pa-section-head" data-reveal="work-head" data-on={revealed.has('work-head')}>
          <div className="pa-section-tag">
            <span className="pa-mono">Selected work</span>
          </div>
          <h2 className="pa-h2">Three projects, three problems.</h2>
        </header>

        <div className="pa-work-grid">
          {projects.map((p, i) => {
            const cardProgress = progress; // unified for the whole pile -> grid
            const inSlot = cardProgress >= 1;
            return (
              <div
                key={p.id}
                ref={el => slotRefs.current[i] = el}
                className="pa-card-slot"
                data-reveal={`slot-${i}`}
                data-on={revealed.has(`slot-${i}`)}
              >
                {/* Slot is reserved space; the actual visual card flies in via .pa-flying-card overlay. */}
                <div className="pa-card-meta">
                  <div className="pa-card-row">
                    <h3 className="pa-card-title">{p.title}</h3>
                  </div>
                  <p className="pa-card-sub">{p.sub}</p>
                </div>
              </div>
            );
          })}
        </div>
      </section>

      {/* FLYING CARDS LAYER (absolute, lives above hero+work region) */}
      <div className="pa-flying-layer" aria-hidden="true">
        {projects.map((p, i) => {
          const slot = cardSlots[i];
          // Per-card stagger so they don't all settle at once
          const stagger = i * 0.08;
          const localT = Math.max(0, Math.min(1, (progress - stagger) / Math.max(0.001, 1 - stagger)));
          // Easing
          const eased = 1 - Math.pow(1 - localT, 3);
          // Pile target position — anchored to the measured pile-area element
          const root = rootRef.current;
          const rootW = root ? root.clientWidth : 1200;
          const cardW = 320;
          const cardH = 252;
          const baseLeft = pileBox
            ? pileBox.left + (pileBox.width - cardW) / 2
            : rootW - cardW - 80;
          const avgYOffset = pileOrigins.reduce((s, o) => s + (o.y || 0), 0) / pileOrigins.length;
          const baseTop = pileBox
            ? pileBox.top + (pileBox.height - cardH) / 2 - avgYOffset
            : 260;
          const pileBase = {
            x: baseLeft + (pileOrigins[i].x || 0),
            y: baseTop + (pileOrigins[i].y || 0),
            r: pileOrigins[i].r,
            w: cardW,
            h: cardH,
          };
          // Slot target
          const slotPos = slot ? {
            x: slot.left,
            y: slot.top,
            r: 0,
            w: slot.width,
            h: slot.width * 0.72, // lands slightly below ::before (5/4 = 0.8) for breathing room
          } : pileBase;

          const x = pileBase.x + (slotPos.x - pileBase.x) * eased;
          const y = pileBase.y + (slotPos.y - pileBase.y) * eased;
          const w = pileBase.w + (slotPos.w - pileBase.w) * eased;
          const h = pileBase.h + (slotPos.h - pileBase.h) * eased;
          const r = pileBase.r + (slotPos.r - pileBase.r) * eased;

          // Subtle floating motion when in pile
          const floatY = (1 - eased) * Math.sin((Date.now() / 1500) + i) * 0;

          // Reveal inner details only as card approaches its slot
          const detailOpacity = Math.max(0, Math.min(1, (eased - 0.75) / 0.2));
          const settled = eased > 0.95;
          return (
            <a
              key={p.id}
              href={settled ? p.href : undefined}
              className="pa-flying-card"
              data-settled={settled ? 'true' : 'false'}
              style={{
                transform: `translate(${x}px, ${y + floatY}px) rotate(${r}deg)`,
                width: `${w}px`,
                height: `${h}px`,
                background: p.tone,
                zIndex: 10 + (projects.length - 1 - i),
                pointerEvents: settled ? 'auto' : 'none',
                cursor: settled ? 'pointer' : 'default',
                textDecoration: 'none',
              }}
            >
              {p.thumb && (
                <img
                  src={p.thumb}
                  alt=""
                  className="pa-flying-card-img"
                />
              )}
              <div className="pa-card-grid-overlay">
                {Array.from({ length: 48 }).map((_, j) => <span key={j} />)}
              </div>
              <div className="pa-card-thumb-meta" style={{ opacity: detailOpacity }}>
                <div className="pa-card-arrow">
                  <svg width="16" height="16" viewBox="0 0 16 16" fill="none"><path d="M4 12L12 4M12 4H6M12 4V10" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>
                </div>
              </div>
            </a>
          );
        })}
      </div>

      {/* ABOUT */}
      <section className="pa-section pa-about" id="about">
        <div className="pa-about-grid">
          <div className="pa-about-photo" data-reveal="photo" data-on={revealed.has('photo')}>
            <div className="pa-photo-frame">
              <img className="pa-photo-img" src="images/bhavya-portrait.jpg" alt="Portrait of Bhavya Parashar" />
              <div className="pa-photo-cap">
                <span className="pa-mono">BHAVYA PARASHAR</span>
                <span className="pa-mono">Product Designer</span>
              </div>
            </div>
          </div>
          <div className="pa-about-copy" data-reveal="about-copy" data-on={revealed.has('about-copy')}>
            <div className="pa-section-tag">
              <span className="pa-mono">About</span>
            </div>
            <h2 className="pa-h2">
              I'm Bhavya. I lead design <span className="pa-h2-accent">that ships.</span>
            </h2>
            <div className="pa-about-body">
              <p>
                A product designer with seven years shaping consumer experiences across music, entertainment, and enterprise. I <strong>lead programs end-to-end</strong>, from vision to launch, and <strong>build with AI</strong> to move from idea to working prototype in hours.
              </p>
              <p>
                Currently a UX Designer at <strong>Amazon Music</strong>, leading design for in-app artist merchandise. Previously at Airtel, Rivigo, and Think Design.
              </p>
            </div>
            <dl className="pa-facts">
              <div><dt>Now</dt><dd>UX Designer · Amazon Music</dd></div>
              <div><dt>Education</dt><dd>Purdue · M.S. UX Design</dd></div>
              <div><dt>Tools</dt><dd>Figma, Adobe CS, Claude</dd></div>
            </dl>
            <div className="pa-about-cta-row">
              <a href="about.html" className="pa-cta pa-cta-primary">
                <svg width="14" height="14" viewBox="0 0 16 16" fill="none"><path d="M3 13L13 3M13 3H6M13 3V10" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round"/></svg>
                <span>Read full bio</span>
              </a>
              <a href="mailto:bhavya.parashar96@gmail.com" className="pa-cta pa-cta-ghost">Get in touch</a>
            </div>
          </div>
        </div>

        <div className="pa-about-strengths" data-reveal="strengths" data-on={revealed.has('strengths')}>
          <header className="pa-strengths-head">
            <div className="pa-section-tag">
              <span className="pa-mono">My strengths</span>
            </div>
            <h2 className="pa-h2 pa-strengths-h2">Three things I bring to a room.</h2>
          </header>
          <div className="pa-strengths-grid">
            <div className="pa-strength">
              <div className="pa-strength-icon" aria-hidden="true">
                <svg viewBox="0 0 48 48" width="40" height="40" fill="none" stroke="currentColor" strokeWidth="1.5">
                  <circle cx="24" cy="24" r="20" />
                  <circle cx="24" cy="24" r="12" />
                  <circle cx="24" cy="24" r="4" fill="currentColor" stroke="none" />
                </svg>
              </div>
              <div>
                <span className="pa-strength-label">User-centered</span>
              </div>
            </div>
            <div className="pa-strength">
              <div className="pa-strength-icon" aria-hidden="true">
                <svg viewBox="0 0 48 48" width="40" height="40" fill="none" stroke="currentColor" strokeWidth="1.5">
                  <line x1="12" y1="12" x2="36" y2="12" />
                  <line x1="12" y1="12" x2="12" y2="36" />
                  <line x1="36" y1="12" x2="36" y2="36" />
                  <line x1="12" y1="36" x2="36" y2="36" />
                  <line x1="12" y1="12" x2="36" y2="36" />
                  <circle cx="12" cy="12" r="3" fill="currentColor" stroke="none" />
                  <circle cx="36" cy="12" r="3" fill="currentColor" stroke="none" />
                  <circle cx="12" cy="36" r="3" fill="currentColor" stroke="none" />
                  <circle cx="36" cy="36" r="3" fill="currentColor" stroke="none" />
                </svg>
              </div>
              <div>
                <span className="pa-strength-label">Systems thinker</span>
              </div>
            </div>
            <div className="pa-strength">
              <div className="pa-strength-icon" aria-hidden="true">
                <svg viewBox="0 0 48 48" width="40" height="40" fill="none" stroke="currentColor" strokeWidth="1.5">
                  <circle cx="18" cy="24" r="10" />
                  <circle cx="30" cy="24" r="10" />
                </svg>
              </div>
              <div>
                <span className="pa-strength-label">Highly collaborative</span>
              </div>
            </div>
          </div>
        </div>
      </section>

      {/* TESTIMONIALS */}
      <section className="pa-section pa-testi" id="testi">
        <header className="pa-section-head" data-reveal="testi-head" data-on={revealed.has('testi-head')}>
          <div className="pa-section-tag">
            <span className="pa-mono">References</span>
          </div>
          <h2 className="pa-h2">From the people I worked with.</h2>
        </header>
        <div className="pa-testi-grid">
          {[
            { q: "Bhavya is a strong designer with an incredible ability to apply customer insights, understand business goals & needs, and deliver simple, elegant solutions to often complex challenges. Additionally, Bhavya is fun to work with, actively contributes to team discussions & reviews, works fast, and raises the bar with her documentation and deliverables that helps others.", who: 'Brad Pankop', role: 'Product Design Leader', tag: 'Direct report' },
            { q: "Bhavya is a customer-centric product designer who consistently raises the bar on gathering and applying research insights to improve product experiences. During my time working with Bhavya at Amazon Music, we met regularly to exchange knowledge, ideas, and challenges. Bhavya was always receptive to support as well as confident in pursuing research strategies independently using Dscout. She regularly utilized resources like guidance from our Senior UX Researchers to execute self-service studies with high-quality results. Bhavya would then use the research insights to inform and validate design decisions and present them back to product partners and leadership, earning both trust and successful buy-in. The impact of her work was well recognized, leading to advances in how AI was used to generate assets, innovative design solutions to complex problems, and successful customer engagement…", who: 'Lesley Palfreyman', role: 'Principal Design & Research Strategist · Ex-Amazon', tag: 'Amazon Music' },
          ].map((t, i) => (
            <figure
              className="pa-quote"
              key={i}
              data-reveal={`q-${i}`}
              data-on={revealed.has(`q-${i}`)}
              style={{ '--reveal-delay': `${i * 100}ms` }}
            >
              <div className="pa-quote-top">
                <svg className="pa-quote-mark" width="28" height="22" viewBox="0 0 28 22" fill="none">
                  <path d="M0 22V11C0 5 3 0 11 0V5C6 5 5 8 5 11H11V22H0ZM17 22V11C17 5 20 0 28 0V5C23 5 22 8 22 11H28V22H17Z" fill="currentColor"/>
                </svg>
              </div>
              <blockquote>{t.q}</blockquote>
              <figcaption>
                <span className="pa-quote-avatar">{t.who[0]}</span>
                <span>
                  <strong>{t.who}</strong>
                  <em>{t.role}</em>
                </span>
              </figcaption>
            </figure>
          ))}
        </div>
        <p className="pa-testi-note" data-reveal="testi-note" data-on={revealed.has('testi-note')}>
          <a href="https://www.linkedin.com/in/bparashar96/" target="_blank" rel="noopener noreferrer">Original recommendations on LinkedIn ↗</a>
        </p>
      </section>

      {/* FOOTER */}
      <footer className="pa-footer" id="contact">
        <div className="pa-footer-cols">
          <div>
            <span className="pa-mono pa-foot-h6">Sitemap</span>
            <ul>
              <li><a href="#work">Work</a></li>
              <li><a href="#about">About</a></li>
              <li><a href="arts.html">Art</a></li>
            </ul>
          </div>
          <div>
            <span className="pa-mono pa-foot-h6">Contact me</span>
            <ul>
              <li><a href="mailto:bhavya.parashar96@gmail.com">Email ↗</a></li>
              <li><a href="https://www.linkedin.com/in/bparashar96/" target="_blank" rel="noopener noreferrer">LinkedIn ↗</a></li>
            </ul>
          </div>
        </div>
        <div className="pa-footer-base">
          <span className="pa-foot-wordmark">Made with Claude Code and Claude Design, with a dash of human brain power.</span>
          <span className="pa-mono">© 2026 · Bhavya Parashar</span>
        </div>
      </footer>
    </div>
  );
};

window.PortfolioA = PortfolioA;
