// Products — pinned scrollytelling panel. Three tiers reveal as you scroll;
// a mountain trail SVG "grows" higher in altitude with each step.

function AltitudeMountain({ step, total }) {
  // step 0..total. Draws 3-tier mountain; each peak lights up in sequence.
  const active = [step >= 0, step >= 1, step >= 2];
  return (
    <svg viewBox="0 0 600 500" width="100%" height="100%" preserveAspectRatio="xMidYMax meet">
      <defs>
        <linearGradient id="m1" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0" stopColor="#72BAD6" />
          <stop offset="1" stopColor="#3A8CA8" />
        </linearGradient>
        <linearGradient id="m2" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0" stopColor="#2E7A96" />
          <stop offset="1" stopColor="#1F5E7A" />
        </linearGradient>
        <linearGradient id="m3" x1="0" x2="0" y1="0" y2="1">
          <stop offset="0" stopColor="#1F5E7A" />
          <stop offset="1" stopColor="#0D3044" />
        </linearGradient>
        <linearGradient id="blush" x1="0" x2="1" y1="0" y2="1">
          <stop offset="0" stopColor="#F2BBA0" />
          <stop offset="1" stopColor="#B8715A" />
        </linearGradient>
      </defs>

      {/* Peak 1 — Landing */}
      <g data-peak="1" style={{ opacity: active[0] ? 1 : 0.25, transition: 'opacity 0.8s var(--ease-out)' }}>
        <path d="M40 440 L150 280 L260 440 Z" fill="url(#m1)" />
        <path d="M150 280 L175 315 L160 325 L195 322 L205 340 L175 338 L155 340 Z" fill="#F5F0EB" />
        <circle cx="150" cy="280" r="5" fill="#B8715A" />
        <text x="150" y="265" textAnchor="middle" fontFamily="JetBrains Mono" fontSize="9" letterSpacing="1.2" fill="#1A2436" opacity={active[0] ? 0.85 : 0}>01 · LANDING</text>
      </g>

      {/* Peak 2 — Business */}
      <g data-peak="2" style={{ opacity: active[1] ? 1 : 0.25, transition: 'opacity 0.8s var(--ease-out) 0.1s' }}>
        <path d="M180 440 L320 180 L460 440 Z" fill="url(#m2)" />
        <path d="M320 180 L348 215 L332 228 L370 224 L388 250 L352 248 L328 250 L300 225 Z" fill="#F5F0EB" />
        <path d="M320 180 L348 215 L330 220 L355 225 L340 235 L325 228 Z" fill="url(#blush)" opacity="0.7" />
        <circle cx="320" cy="180" r="5" fill="#B8715A" />
        <text x="320" y="163" textAnchor="middle" fontFamily="JetBrains Mono" fontSize="9" letterSpacing="1.2" fill="#1A2436" opacity={active[1] ? 0.85 : 0}>02 · BUSINESS</text>
      </g>

      {/* Peak 3 — Custom */}
      <g data-peak="3" style={{ opacity: active[2] ? 1 : 0.25, transition: 'opacity 0.8s var(--ease-out) 0.2s' }}>
        <path d="M370 440 L510 90 L650 440 Z" fill="url(#m3)" />
        <path d="M510 90 L545 140 L525 155 L565 150 L590 190 L548 188 L518 192 L486 160 Z" fill="#F5F0EB" />
        <path d="M510 90 L545 140 L522 148 L555 155 L540 170 L518 158 Z" fill="url(#blush)" opacity="0.75" />
        <circle cx="510" cy="90" r="5" fill="#B8715A" />
        <text x="510" y="73" textAnchor="middle" fontFamily="JetBrains Mono" fontSize="9" letterSpacing="1.2" fill="#1A2436" opacity={active[2] ? 0.85 : 0}>03 · CUSTOM</text>
      </g>

      {/* Altitude lines */}
      <g stroke="#1A2436" strokeOpacity="0.08" strokeWidth="1" strokeDasharray="3 6">
        <line x1="0" y1="180" x2="600" y2="180" />
        <line x1="0" y1="280" x2="600" y2="280" />
        <line x1="0" y1="380" x2="600" y2="380" />
      </g>
      <g fontFamily="JetBrains Mono" fontSize="9" fill="#1A2436" opacity="0.35" letterSpacing="1.4">
        <text x="8" y="178">2200M</text>
        <text x="8" y="278">1400M</text>
        <text x="8" y="378">800M</text>
      </g>

      {/* trail dashes */}
      <path d="M60 440 Q 100 400 150 280 Q 200 220 260 300 Q 290 340 320 180 Q 380 220 420 280 Q 460 240 510 90" fill="none" stroke="#1A2436" strokeWidth="1.2" strokeDasharray="2 5" opacity="0.35" />
    </svg>
  );
}

function ProductsSection() {
  const stageRef = React.useRef(null);
  const [step, setStep] = React.useState(0);

  React.useEffect(() => {
    const onScroll = () => {
      if (!stageRef.current) return;
      const r = stageRef.current.getBoundingClientRect();
      const vh = window.innerHeight;
      const total = r.height - vh;
      const p = Math.max(0, Math.min(1, -r.top / total));
      // 3 steps over the scroll
      const s = Math.min(2, Math.floor(p * 3));
      setStep(s);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => window.removeEventListener('scroll', onScroll);
  }, []);

  const products = [
    {
      n: '01',
      name: 'Landing',
      price: '$0',
      priceNote: 'Design',
      recur: '$99',
      recurNote: '/mo after launch',
      tag: 'One page. Done well.',
      desc: 'A single, hand-built page for a business that just needs to show up properly online. Content, design, build, deploy. We do the climb. After launch we host, monitor, patch and tune. You forget about it, on purpose.',
      includes: [
        'Custom design, no templates',
        'One-page structure, written with you',
        'Mobile-perfect, fast by default',
        'Hosting, SSL, daily backups',
        'Uptime + performance monitoring',
        'Quarterly content refresh (we call you)',
      ],
      color: 'var(--alpine-500)',
      bg: 'rgba(245, 240, 235, 0.55)',
      featured: false,
    },
    {
      n: '02',
      name: 'Business',
      price: '$0',
      priceNote: 'Design',
      recur: '$399',
      recurNote: '/mo after launch',
      tag: 'Up to three pages, plus a quiet tool that works for you.',
      desc: 'A multi-page site (up to three pages) with a custom quote estimator tuned to how you actually charge. Leads pass through a dashboard you can sign into: see who\'s asked, what they need, and how much you quoted, without digging through email.',
      includes: [
        'Up to 3 pages, custom-designed',
        'Custom quote estimator, built to your pricing',
        'Owner dashboard with login',
        'Lead inbox, notes, and status',
        'Automated reply + follow-up nudges',
        'Monthly review call, in human English',
      ],
      color: 'var(--summit)',
      bg: 'rgba(14, 21, 32, 0.92)',
      featured: true,
    },
    {
      n: '03',
      name: 'Custom',
      price: 'Quote',
      priceNote: 'Scoped together',
      recur: 'Per project',
      recurNote: 'Billed in stages',
      tag: 'Whatever the work is, we scope it honestly.',
      desc: 'A full site, a portal, a booking flow, a directory: anything that doesn\'t fit the shape of the first two. We write a short scope together, in plain English, before any invoice. No decks, no kick-off rituals. Five stages, in order, every time.',
      includes: [
        'Discovery + written scope',
        'Identity or design system, if needed',
        'Multi-page site or bespoke app',
        'CMS, auth, integrations as required',
        'Staged delivery, fixed by scope',
        'Optional $99 / $399 monthly care plans',
      ],
      color: 'var(--alpine-700)',
      bg: 'rgba(245, 240, 235, 0.55)',
      featured: false,
    },
  ];

  return (
    <section id="products" ref={stageRef} className="pin-stage">
      <div className="pin-sticky" style={{ background: 'var(--parchment)' }}>
        <div className="max-w-[1680px] mx-auto px-6 md:px-10 w-full grid grid-cols-1 lg:grid-cols-[0.9fr_1.1fr] gap-10 lg:gap-20 items-center">

          {/* Left: mountain + step nav */}
          <div className="relative products-mountain-col">
            <div className="flex items-center gap-4 mb-8">
              <span className="h-px w-10" style={{ background: 'var(--summit)' }} />
              <span className="mono-label" style={{ color: 'rgba(26,36,54,0.55)' }}>Products · three tiers</span>
            </div>
            <h2 className="font-display font-extrabold mb-10" style={{ fontSize: 'clamp(2.5rem, 5vw, 4.5rem)', lineHeight: 1.04, letterSpacing: '-0.018em', color: 'var(--abyss)' }}>
              Pick your <span className="italic font-normal" style={{ color: 'var(--summit)' }}>altitude</span>.
            </h2>
            <div className="relative aspect-[6/5] max-w-[560px] products-mountain-art">
              <AltitudeMountain step={step} />
              {/* floating climber at current step peak */}
            </div>
            <div className="mt-8 flex items-center gap-2 mono-label" style={{ color: 'rgba(26,36,54,0.55)' }}>
              <span>Stage 0{step + 1} / 03</span>
              <span className="flex-1 h-px ml-3" style={{ background: 'rgba(26,36,54,0.15)' }} />
              <span style={{ color: 'var(--summit)' }}>{['Landing', 'Business', 'Custom'][step]}</span>
            </div>
          </div>

          {/* Right: product card — swaps as step changes (grid stack so parent has intrinsic height) */}
          <div className="relative grid products-stack" style={{ gridTemplateAreas: '"stack"' }}>
            {products.map((p, i) => {
              const isOn = step === i;
              return (
                <div key={p.n}
                  className="transition-all products-step-card"
                  style={{
                    gridArea: 'stack',
                    opacity: isOn ? 1 : 0,
                    transform: `translateY(${isOn ? 0 : 30}px)`,
                    pointerEvents: isOn ? 'auto' : 'none',
                    transitionDuration: '0.7s',
                    transitionTimingFunction: 'cubic-bezier(0.22,1,0.36,1)',
                    zIndex: isOn ? 2 : 1,
                  }}
                  data-nav-dark={p.featured ? 'true' : undefined}
                >
                  <div className="glass rounded-3xl p-8 md:p-10 relative overflow-hidden"
                       style={{
                         background: p.featured ? 'rgba(14, 21, 32, 0.92)' : 'rgba(245, 240, 235, 0.55)',
                         borderColor: p.featured ? 'rgba(245,240,235,0.12)' : 'rgba(245,240,235,0.7)',
                         color: p.featured ? 'var(--parchment)' : 'var(--abyss)',
                       }}>
                    {p.featured && <div className="noise" />}
                    <div className="relative">
                      <div className="flex items-start justify-between mb-6">
                        <div className="flex items-center gap-3">
                          <span className="mono-label" style={{ color: p.featured ? 'rgba(245,240,235,0.55)' : 'rgba(26,36,54,0.4)' }}>{p.n} · {p.name.toUpperCase()}</span>
                          {p.featured && (
                            <span className="chip" style={{ background: 'rgba(184,113,90,0.25)', borderColor: 'rgba(242,187,160,0.4)', color: '#F2BBA0' }}>Most picked</span>
                          )}
                        </div>
                        <div className="w-10 h-10 rounded-full flex items-center justify-center" style={{
                          background: p.featured ? 'var(--summit)' : 'var(--abyss)',
                          color: 'var(--parchment)'
                        }}>
                          <ArrowRightShort />
                        </div>
                      </div>

                      <h3 className="font-display font-semibold mb-5" style={{ fontSize: 'clamp(1.75rem, 2.6vw, 2.4rem)', lineHeight: 1.12, letterSpacing: '-0.014em', color: p.featured ? 'var(--parchment)' : 'var(--abyss)' }}>
                        {p.tag}
                      </h3>
                      <p className="font-body max-w-[56ch] mb-8" style={{ fontSize: '1rem', lineHeight: 1.65, color: p.featured ? 'rgba(245,240,235,0.72)' : 'var(--ridge)' }}>
                        {p.desc}
                      </p>

                      {/* price block */}
                      <div className="flex flex-wrap items-end gap-x-10 gap-y-4 mb-8 pb-8 border-b" style={{ borderColor: p.featured ? 'rgba(245,240,235,0.12)' : 'rgba(26,36,54,0.1)' }}>
                        <div>
                          <span className="mono-label block mb-1.5" style={{ color: p.featured ? 'rgba(245,240,235,0.5)' : 'rgba(26,36,54,0.4)' }}>Design</span>
                          <div className="font-display font-bold" style={{ fontSize: '2.25rem', lineHeight: 1, color: p.featured ? 'var(--parchment)' : 'var(--abyss)' }}>
                            {p.price}
                          </div>
                          <span className="font-display italic font-light" style={{ fontSize: '0.95rem', color: p.featured ? 'rgba(245,240,235,0.55)' : 'rgba(26,36,54,0.5)' }}>{p.priceNote}</span>
                        </div>
                        <div>
                          <span className="mono-label block mb-1.5" style={{ color: p.featured ? 'rgba(245,240,235,0.5)' : 'rgba(26,36,54,0.4)' }}>After launch</span>
                          <div className="font-display font-bold" style={{ fontSize: '2.25rem', lineHeight: 1, color: p.featured ? 'var(--glacier)' : 'var(--summit)' }}>
                            {p.recur}
                          </div>
                          <span className="font-display italic font-light" style={{ fontSize: '0.95rem', color: p.featured ? 'rgba(245,240,235,0.55)' : 'rgba(26,36,54,0.5)' }}>{p.recurNote}</span>
                        </div>
                      </div>

                      {/* includes grid */}
                      <ul className="grid sm:grid-cols-2 gap-x-8 gap-y-3">
                        {p.includes.map((it, j) => (
                          <li key={j} className="flex items-start gap-3 font-body" style={{ fontSize: '0.92rem', color: p.featured ? 'rgba(245,240,235,0.78)' : 'var(--ridge)' }}>
                            <span className="mt-1.5 shrink-0" style={{ color: p.featured ? 'var(--glacier)' : 'var(--summit)' }}>
                              <CheckTrend size={13} />
                            </span>
                            <span>{it}</span>
                          </li>
                        ))}
                      </ul>

                      <div className="mt-9 flex items-center gap-6 flex-wrap">
                        <a href="#contact" className="inline-flex items-center gap-3 pl-2 pr-6 py-2 rounded-full font-display font-medium transition-colors"
                           style={{
                             background: p.featured ? 'var(--parchment)' : 'var(--abyss)',
                             color: p.featured ? 'var(--abyss)' : 'var(--parchment)',
                             fontSize: '0.95rem',
                           }}>
                          <span className="w-9 h-9 rounded-full inline-flex items-center justify-center" style={{ background: 'var(--summit)', color: 'var(--parchment)' }}>
                            <ArrowRightShort />
                          </span>
                          Begin {p.name.toLowerCase()}
                        </a>
                        <a href="#faq" className="font-display italic font-light" style={{ fontSize: '1rem', color: p.featured ? 'rgba(245,240,235,0.7)' : 'rgba(26,36,54,0.65)' }}>
                          <span className="link-u">Questions first?</span>
                        </a>
                      </div>
                    </div>
                  </div>
                </div>
              );
            })}

            {/* step dots on right */}
            <div className="absolute -right-2 top-1/2 -translate-y-1/2 hidden xl:flex flex-col gap-3 items-center" style={{ translate: '100% -50%' }}>
              {products.map((p, i) => (
                <button key={i} onClick={() => {
                  if (!stageRef.current) return;
                  const r = stageRef.current.getBoundingClientRect();
                  const total = r.height - window.innerHeight;
                  const target = (i / 3 + 0.5 / 3) * total + (window.scrollY + r.top);
                  window.scrollTo({ top: target, behavior: 'smooth' });
                }}
                  aria-label={`Go to ${p.name}`}
                  className="rounded-full transition-all"
                  style={{
                    width: step === i ? 12 : 8,
                    height: step === i ? 12 : 8,
                    background: step === i ? 'var(--summit)' : 'rgba(26,36,54,0.25)',
                  }}
                />
              ))}
            </div>
          </div>
        </div>
      </div>
    </section>
  );
}
window.ProductsSection = ProductsSection;
