/* global React, Wordmark, Eyebrow, LockPill, Icon, IntentBadge, LockTile, TrustStrip, Footer, MobileStatusBar, formatPhone, submitAndGenerate */
const { useState, useEffect, useMemo, useRef } = React;

// ═══════════════════════════════════════════════════════════
// PILLARS — animated three-card story
// ═══════════════════════════════════════════════════════════
const Pillars = ({ accent, isMobile }) => {
  const [visible, setVisible] = useState(false);
  const [animKey, setAnimKey] = useState(0);
  const ref = React.useRef(null);
  React.useEffect(() => {
    const node = ref.current;
    if (!node) return;
    // Find the closest scrolling ancestor (viewport-scroll inside the device frame)
    let root = node.parentElement;
    while (root && root !== document.body) {
      const oy = getComputedStyle(root).overflowY;
      if (oy === 'auto' || oy === 'scroll') break;
      root = root.parentElement;
    }
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting) { setVisible(true); setAnimKey((k) => k + 1); }
      });
    }, { root: root === document.body ? null : root, threshold: 0.15 });
    io.observe(node);
    return () => io.disconnect();
  }, []);

  const stagger = (i) => ({ animationDelay: `${0.12 + i * 0.18}s` });
  const cls = (i) => `pillar-card${visible ? ' in' : ''}`;

  return (
    <div ref={ref} key={animKey} style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(3, 1fr)', gap: isMobile ? 16 : 1, background: 'var(--rule)', border: '1px solid var(--rule)' }}>
      {/* Pillar 01 — Stay anonymous */}
      <div className={cls(0)} style={{ ...stagger(0), '--accent': accent }}>
        <div className="pillar-art">
          <div className="redact-doc">
            <div className="redact-line" style={{ width: '40%', animationDelay: '0.25s' }} />
            <div className="redact-line redacted" style={{ width: '78%', animationDelay: '0.55s' }} />
            <div className="redact-line" style={{ width: '62%', animationDelay: '0.75s' }} />
            <div className="redact-line redacted" style={{ width: '54%', animationDelay: '0.95s' }} />
            <div className="redact-line" style={{ width: '70%', animationDelay: '1.15s' }} />
            <div className="redact-line redacted" style={{ width: '38%', animationDelay: '1.30s' }} />
          </div>
          <div className="redact-stamp">CONFIDENTIAL</div>
        </div>
        <div className="pillar-eyebrow">01</div>
        <h3 className="pillar-title">Stay anonymous</h3>
        <p className="pillar-body">No public listing. Your name, your business, your team — never disclosed without your written consent.</p>
      </div>

      {/* Pillar 02 — Real market data */}
      <div className={cls(1)} style={{ ...stagger(1), '--accent': accent }}>
        <div className="pillar-art">
          <div className="bar-grid">
            {[0.35, 0.55, 0.42, 0.78, 0.65, 0.92, 0.71, 0.58, 0.84].map((h, i) => (
              <div key={i} className="bar-cell" style={{ height: `${h * 100}%`, animationDelay: `${0.2 + i * 0.06}s` }} />
            ))}
          </div>
          <div className="bar-axis" />
          <div className="bar-num">23 <span style={{ fontSize: 11, fontFamily: 'var(--mono)', letterSpacing: '0.12em', color: 'var(--ink-5)', textTransform: 'uppercase', marginLeft: 4 }}>matches</span></div>
          <div className="bar-num right">5.4–6.8× <span style={{ fontSize: 11, fontFamily: 'var(--mono)', letterSpacing: '0.12em', color: 'var(--ink-5)', textTransform: 'uppercase', marginLeft: 4 }}>EBITDA</span></div>
        </div>
        <div className="pillar-eyebrow">02</div>
        <h3 className="pillar-title">Real market data</h3>
        <p className="pillar-body">See actual buyer counts, valuation ranges, and deal terms — drawn from current mandates, not estimates.</p>
      </div>

      {/* Pillar 03 — No obligation */}
      <div className={cls(2)} style={{ ...stagger(2), '--accent': accent }}>
        <div className="pillar-art">
          <svg className="pillar-path" viewBox="0 0 280 140" preserveAspectRatio="xMidYMid meet">
            {/* main horizontal path */}
            <path className="p-line" d="M 16 70 L 260 70" style={{ animationDelay: '0.3s' }} />
            {/* branching dashed path going up (continue) */}
            <path className="p-line branch" d="M 140 70 C 180 70, 200 40, 240 30" />
            {/* branching dashed path going down (walk away) */}
            <path className="p-line branch" d="M 140 70 C 180 70, 200 100, 240 110" />
            {/* nodes */}
            <circle className="p-node" cx="16" cy="70" r="6" style={{ animationDelay: '0.4s' }} />
            <circle className="p-node accent" cx="140" cy="70" r="7" style={{ animationDelay: '1.0s' }} />
            <circle className="p-pulse" cx="140" cy="70" r="7" />
            <circle className="p-node" cx="240" cy="30" r="5" style={{ animationDelay: '1.4s' }} />
            <circle className="p-node" cx="240" cy="110" r="5" style={{ animationDelay: '1.5s' }} />
            <text className="p-label" x="16" y="92" style={{ animationDelay: '1.3s' }}>Submit</text>
            <text className="p-label" x="118" y="58" style={{ animationDelay: '1.3s' }}>You decide</text>
            <text className="p-label" x="200" y="22" style={{ animationDelay: '1.5s' }}>Continue</text>
            <text className="p-label" x="200" y="128" style={{ animationDelay: '1.6s' }}>Walk away</text>
          </svg>
        </div>
        <div className="pillar-eyebrow">03</div>
        <h3 className="pillar-title">No obligation</h3>
        <p className="pillar-body">It costs nothing. Walk away with your numbers. Or take the next step on your timeline, not ours.</p>
      </div>
    </div>
  );
};

// ═══════════════════════════════════════════════════════════
// HOW IT WORKS — sequenced timeline with active-step illustrations
// ═══════════════════════════════════════════════════════════
const HOW_STEPS = [
  { n: '01', t: 'Answer questions', b: 'Industry, size, timing. Eight banded multiple-choice fields.', meta: '~90 seconds' },
  { n: '02', t: 'See your match count', b: 'A real number drawn from active buyer mandates today.', meta: 'Live data' },
  { n: '03', t: 'Review valuation range', b: 'Comparable deal multiples specific to your industry & size.', meta: 'Industry comps' },
  { n: '04', t: "Decide what's next", b: 'Schedule a confidential next step — or just keep your numbers.', meta: 'No obligation' },
];

const HowItWorks = ({ accent, isMobile }) => {
  const [active, setActive] = useState(0);
  const [autoplay, setAutoplay] = useState(false);
  const [hasStarted, setHasStarted] = useState(false);
  const ref = useRef(null);

  // Trigger autoplay when section enters view
  useEffect(() => {
    const node = ref.current;
    if (!node) return;
    let root = node.parentElement;
    while (root && root !== document.body) {
      const oy = getComputedStyle(root).overflowY;
      if (oy === 'auto' || oy === 'scroll') break;
      root = root.parentElement;
    }
    const io = new IntersectionObserver((entries) => {
      entries.forEach((e) => {
        if (e.isIntersecting && !hasStarted) {
          setHasStarted(true);
          setAutoplay(true);
        }
      });
    }, { root: root === document.body ? null : root, threshold: 0.25 });
    io.observe(node);
    return () => io.disconnect();
  }, [hasStarted]);

  // Autoplay loop — advance every 2.6s
  useEffect(() => {
    if (!autoplay) return;
    const id = setInterval(() => {
      setActive((a) => (a + 1) % HOW_STEPS.length);
    }, 2600);
    return () => clearInterval(id);
  }, [autoplay]);

  const handleStepClick = (i) => {
    setAutoplay(false);
    setActive(i);
  };

  return (
    <div ref={ref} className={"how-wrap " + (hasStarted ? 'started' : '')}>
      {/* Timeline rail */}
      {!isMobile && (
        <div className="how-rail">
          <div className="how-rail-track" />
          <div className="how-rail-fill" style={{ width: `${(active / (HOW_STEPS.length - 1)) * 100}%` }} />
          {HOW_STEPS.map((_, i) => (
            <button
              key={i}
              className={"how-rail-node" + (i <= active ? ' done' : '') + (i === active ? ' current' : '')}
              style={{ left: `${(i / (HOW_STEPS.length - 1)) * 100}%`, '--accent': accent }}
              onClick={() => handleStepClick(i)}
              aria-label={`Step ${i + 1}: ${HOW_STEPS[i].t}`}
            >
              <span className="how-rail-pulse" />
            </button>
          ))}
        </div>
      )}

      {/* Steps grid */}
      <div className="how-steps" style={{ gridTemplateColumns: isMobile ? '1fr' : 'repeat(4, 1fr)' }}>
        {HOW_STEPS.map((s, i) => {
          const isActive = i === active;
          const isPast = i < active;
          return (
            <div
              key={i}
              className={"how-step" + (isActive ? ' active' : '') + (isPast ? ' past' : '')}
              style={{ '--accent': accent }}
              onClick={() => handleStepClick(i)}
              onMouseEnter={() => !isMobile && handleStepClick(i)}
            >
              <div className="how-step-illus">
                <HowIllus n={i} active={isActive} accent={accent} />
              </div>
              <div className="how-step-num mono">{s.n}</div>
              <h4 className="serif how-step-title">{s.t}</h4>
              <p className="how-step-body">{s.b}</p>
              <div className="how-step-meta mono">{s.meta}</div>
            </div>
          );
        })}
      </div>
    </div>
  );
};

// Per-step illustrations — re-key on 'active' to restart animations
const HowIllus = ({ n, active, accent }) => {
  const key = active ? 'on' : 'off';
  if (n === 0) {
    // Question fields filling in
    return (
      <svg viewBox="0 0 200 90" className={"hi hi-q " + (active ? 'on' : '')} key={key}>
        {[0, 1, 2].map((i) => (
          <g key={i} transform={`translate(0, ${i * 28})`}>
            <rect className="hi-field" x="8" y="8" width="184" height="14" rx="1" />
            <rect className="hi-fill" x="8" y="8" width="184" height="14" rx="1" style={{ animationDelay: `${i * 280}ms`, fill: accent }} />
            <circle className="hi-dot" cx="178" cy="15" r="2.5" style={{ animationDelay: `${i * 280 + 200}ms` }} />
          </g>
        ))}
      </svg>
    );
  }
  if (n === 1) {
    // Match counter ticking up
    return (
      <svg viewBox="0 0 200 90" className={"hi hi-count " + (active ? 'on' : '')} key={key}>
        <text x="100" y="56" textAnchor="middle" className="hi-count-num serif" fill="currentColor">
          <tspan className="hi-digit hi-d1">2</tspan>
          <tspan className="hi-digit hi-d2">3</tspan>
        </text>
        <text x="100" y="74" textAnchor="middle" className="hi-count-label mono">MATCHES</text>
        {[-32, -18, 0, 18, 32].map((dx, i) => (
          <circle key={i} cx={100 + dx} cy="22" r="3" className="hi-count-dot" style={{ animationDelay: `${i * 80}ms`, fill: accent }} />
        ))}
      </svg>
    );
  }
  if (n === 2) {
    // Valuation range bracket sliding in
    return (
      <svg viewBox="0 0 200 90" className={"hi hi-range " + (active ? 'on' : '')} key={key}>
        <line x1="20" y1="50" x2="180" y2="50" className="hi-range-axis" />
        <g className="hi-range-bracket">
          <line x1="60" y1="42" x2="60" y2="58" stroke={accent} strokeWidth="1.5" />
          <line x1="140" y1="42" x2="140" y2="58" stroke={accent} strokeWidth="1.5" />
          <line x1="60" y1="50" x2="140" y2="50" stroke={accent} strokeWidth="2" />
        </g>
        <text x="60" y="34" textAnchor="middle" className="hi-range-num mono">5.4×</text>
        <text x="140" y="34" textAnchor="middle" className="hi-range-num mono" style={{ animationDelay: '300ms' }}>6.8×</text>
        <text x="100" y="78" textAnchor="middle" className="hi-range-label mono">EBITDA</text>
        {[20, 40, 60, 80, 100, 120, 140, 160, 180].map((x, i) => (
          <line key={x} x1={x} y1="48" x2={x} y2="52" className="hi-range-tick" style={{ animationDelay: `${i * 40}ms` }} />
        ))}
      </svg>
    );
  }
  if (n === 3) {
    // Calendar slot getting selected
    return (
      <svg viewBox="0 0 200 90" className={"hi hi-cal " + (active ? 'on' : '')} key={key}>
        {[0, 1, 2, 3].map((row) => (
          [0, 1, 2, 3, 4].map((col) => {
            const idx = row * 5 + col;
            const isPick = row === 2 && col === 3;
            return (
              <rect
                key={idx}
                x={20 + col * 32}
                y={10 + row * 18}
                width="28"
                height="14"
                rx="1"
                className={"hi-cal-slot" + (isPick ? ' pick' : '')}
                style={{ animationDelay: `${idx * 30}ms`, ...(isPick ? { fill: accent } : {}) }}
              />
            );
          })
        ))}
        <text x="100" y="86" textAnchor="middle" className="hi-cal-label mono">CONFIDENTIAL CALL · 30 MIN</text>
      </svg>
    );
  }
  return null;
};

// ═══════════════════════════════════════════════════════════
// SELLER LANDING
// ═══════════════════════════════════════════════════════════
const SellerLanding = ({ bp, navigate, accent, density }) => {
  const isMobile = bp === 'mobile';
  const isTablet = bp === 'tablet';
  const padX = isMobile ? 24 : isTablet ? 56 : 80;

  const [scrolled, setScrolled] = useState(false);
  const [openMenu, setOpenMenu] = useState(null); // 'insights' | 'about' | null
  const [drawerOpen, setDrawerOpen] = useState(false);
  const scrollRef = useRef(null);
  useEffect(() => {
    const el = scrollRef.current;
    if (!el) return;
    const onScroll = () => { setScrolled(el.scrollTop > 200); setOpenMenu(null); };
    el.addEventListener('scroll', onScroll);
    return () => el.removeEventListener('scroll', onScroll);
  }, []);
  useEffect(() => {
    const onClick = (e) => {
      if (!e.target.closest('[data-nav-menu]')) setOpenMenu(null);
    };
    document.addEventListener('click', onClick);
    return () => document.removeEventListener('click', onClick);
  }, []);

  return (
    <div ref={scrollRef} className="viewport-scroll" style={{ background: 'var(--paper)' }}>
      {/* Top nav */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: isMobile ? '20px 24px' : `24px ${padX}px`,
        position: 'sticky', top: 0, zIndex: 10,
        background: 'rgba(245,243,238,0.92)', backdropFilter: 'blur(10px)',
        borderBottom: '1px solid var(--rule-2)',
      }}>
        <Wordmark size={isMobile ? 20 : 22} />
        {isMobile ? (
          <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
            <button className="btn btn-primary" style={{ padding: '8px 14px', fontSize: 12 }} onClick={() => navigate('seller-wizard')}>
              See matches
            </button>
            <MobileHamburger onClick={() => setDrawerOpen(true)} />
          </div>
        ) : (
          <div style={{ display: 'flex', gap: 28, alignItems: 'center', fontSize: 13, color: 'var(--ink-3)' }}>
            <a href="#how" style={{ color: 'var(--ink-3)' }}>How it works</a>
            <a href="#" onClick={(e) => { e.preventDefault(); navigate('who-buys'); }} style={{ color: 'var(--ink-3)' }}>Who buys</a>

            {/* Insights dropdown */}
            <div data-nav-menu style={{ position: 'relative' }}>
              <button
                onClick={(e) => { e.stopPropagation(); setOpenMenu(openMenu === 'insights' ? null : 'insights'); }}
                style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--ink-3)', fontSize: 13, padding: 0, display: 'inline-flex', alignItems: 'center', gap: 4, fontFamily: 'inherit' }}
              >
                Insights <Icon.Caret open={openMenu === 'insights'} />
              </button>
              {openMenu === 'insights' && (
                <NavMenu items={[
                  { id: 'insights-reports', label: 'Market Reports', sub: 'Quarterly LMM research' },
                  { id: 'insights-multiples', label: 'Industry Multiples', sub: 'What buyers are paying' },
                  { id: 'insights-cases', label: 'Case Studies', sub: 'Anonymized closed deals' },
                  { id: 'insights-glossary', label: 'Glossary', sub: 'M&A terms in plain English' },
                ]} navigate={navigate} onPick={() => setOpenMenu(null)} />
              )}
            </div>

            {/* About dropdown */}
            <div data-nav-menu style={{ position: 'relative' }}>
              <button
                onClick={(e) => { e.stopPropagation(); setOpenMenu(openMenu === 'about' ? null : 'about'); }}
                style={{ background: 'none', border: 'none', cursor: 'pointer', color: 'var(--ink-3)', fontSize: 13, padding: 0, display: 'inline-flex', alignItems: 'center', gap: 4, fontFamily: 'inherit' }}
              >
                About <Icon.Caret open={openMenu === 'about'} />
              </button>
              {openMenu === 'about' && (
                <NavMenu items={[
                  { id: 'about-story', label: 'Our Story', sub: 'How Buyside came to be' },
                  { id: 'about-team', label: 'Team', sub: 'Bankers and operators behind it' },
                  { id: 'about-contact', label: 'Contact', sub: 'Austin, TX · hello@buyside.market' },
                ]} navigate={navigate} onPick={() => setOpenMenu(null)} />
              )}
            </div>

            <span style={{ width: 1, height: 18, background: 'var(--rule)' }} />
            <a href="#" onClick={(e) => { e.preventDefault(); navigate('buyer-landing'); }} style={{ color: 'var(--ink-4)', fontSize: 12 }}>For buyers <Icon.ExtLink /></a>
            <button className="btn btn-primary" style={{ padding: '10px 18px', fontSize: 13 }} onClick={() => navigate('seller-wizard')}>
              See your matches
            </button>
          </div>
        )}
      </div>

      {isMobile && <MobileNavDrawer open={drawerOpen} onClose={() => setDrawerOpen(false)} navigate={navigate} currentScreen="seller-landing" />}

      {/* Hero */}
      <section style={{
        minHeight: isMobile ? 'calc(100vh - 64px)' : 'auto',
        padding: isMobile ? '48px 24px 64px' : `${isTablet ? 80 : 120}px ${padX}px ${isTablet ? 80 : 120}px`,
        display: 'flex', flexDirection: 'column', justifyContent: 'center',
        position: 'relative', overflow: 'hidden',
      }}>
        {/* ornament rule */}
        <div style={{ position: 'absolute', top: 0, right: padX, width: 1, height: '60%', background: 'var(--rule)', opacity: 0.5 }} />
        <Eyebrow>Confidential Matching · Est. 2025</Eyebrow>
        <h1 className="serif" style={{
          fontSize: isMobile ? 'clamp(40px, 11vw, 56px)' : isTablet ? 64 : 84,
          lineHeight: 1.02, letterSpacing: '-0.035em', fontWeight: 350,
          margin: '24px 0 0', maxWidth: isMobile ? '100%' : 920,
        }}>
          See if buyers are <em style={{ fontWeight: 300, color: accent }}>interested</em> in your business.
        </h1>
        <p style={{
          fontSize: isMobile ? 16 : 19, lineHeight: 1.55, color: 'var(--ink-3)',
          maxWidth: 620, margin: '28px 0 0', fontWeight: 400,
        }}>
          1,000+ vetted PE firms, search funds, and family offices have told us exactly what they're looking for. Answer a couple of questions and we'll show you how many match — anonymously, free, no listing.
        </p>
        <div style={{ display: 'flex', gap: 16, alignItems: 'center', marginTop: 36, flexWrap: 'wrap' }}>
          <button className="btn btn-primary btn-arrow" style={{ padding: '16px 24px', fontSize: 15 }} onClick={() => navigate('seller-wizard')}>
            See your matches
          </button>
          <span style={{ fontSize: 13, color: 'var(--ink-4)' }}>Takes about 90 seconds.</span>
        </div>

        {/* Trust strip */}
        <div className="mono" style={{
          marginTop: 20, paddingTop: 16, borderTop: '1px solid var(--rule)',
          maxWidth: 620, fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase',
          color: 'var(--ink-5)', display: 'flex', flexWrap: 'wrap', gap: isMobile ? 8 : 14, alignItems: 'center',
        }}>
          <span>Trusted by owners across <span style={{ color: 'var(--ink-3)' }}>47 states</span></span>
          <span style={{ opacity: 0.5 }}>·</span>
          <span><span style={{ color: 'var(--ink-3)' }}>$8.2B</span> in active buyer demand</span>
        </div>

        <div style={{ marginTop: 28 }}>
          <LockPill />
        </div>

        {/* Hero meta-row */}
        {!isMobile && (
          <div style={{
            position: 'absolute', bottom: 32, right: padX,
            fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.14em',
            textTransform: 'uppercase', color: 'var(--ink-5)',
            display: 'flex', gap: 20,
          }}>
            <span>Vol. I</span>
            <span>·</span>
            <span>buyside.market</span>
          </div>
        )}
      </section>

      {/* Press strip */}
      <section style={{ padding: isMobile ? '36px 24px' : `48px ${padX}px`, background: '#efece4', borderTop: '1px solid var(--rule)', borderBottom: '1px solid var(--rule)' }}>
        <div style={{ display: 'flex', flexDirection: isMobile ? 'column' : 'row', alignItems: isMobile ? 'flex-start' : 'center', gap: isMobile ? 24 : 48 }}>
          <span className="mono" style={{ fontSize: 10, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--ink-4)', whiteSpace: 'nowrap' }}>As mentioned in</span>
          {isMobile ? (
            <div style={{ overflow: 'hidden', width: '100%' }}>
              <div style={{
                display: 'flex', alignItems: 'center', gap: 48,
                animation: 'logo-scroll 12s linear infinite',
                width: 'max-content',
              }}>
                {[...Array(2)].map((_, r) => (
                  <React.Fragment key={r}>
                    <img src="assets/logo-masource-dark.png" alt="M&A Source" style={{ height: 40, width: 'auto', objectFit: 'contain', filter: 'grayscale(100%) opacity(0.5)', flexShrink: 0 }} />
                    <img src="assets/logo-axial.png" alt="Axial" style={{ height: 34, width: 'auto', objectFit: 'contain', filter: 'grayscale(100%) opacity(0.5)', flexShrink: 0 }} />
                    <img src="assets/logo-hvac.png" alt="HVAC Insider" style={{ height: 76, width: 'auto', objectFit: 'contain', filter: 'grayscale(100%) opacity(0.5)', flexShrink: 0 }} />
                    <img src="assets/logo-acg.png" alt="ACG" style={{ height: 38, width: 'auto', objectFit: 'contain', filter: 'grayscale(100%) opacity(0.5)', flexShrink: 0 }} />
                  </React.Fragment>
                ))}
              </div>
            </div>
          ) : (
            <div style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 56, flex: 1, justifyContent: 'space-between' }}>
              <img src="assets/logo-masource-dark.png" alt="M&A Source" style={{ height: 52, width: 'auto', objectFit: 'contain', filter: 'grayscale(100%) opacity(0.5)' }} />
              <img src="assets/logo-axial.png" alt="Axial" style={{ height: 44, width: 'auto', objectFit: 'contain', filter: 'grayscale(100%) opacity(0.5)' }} />
              <img src="assets/logo-hvac.png" alt="HVAC Insider" style={{ height: 100, width: 'auto', objectFit: 'contain', filter: 'grayscale(100%) opacity(0.5)' }} />
              <img src="assets/logo-acg.png" alt="ACG" style={{ height: 48, width: 'auto', objectFit: 'contain', filter: 'grayscale(100%) opacity(0.5)' }} />
            </div>
          )}
          <button className="btn btn-ghost" onClick={() => navigate('about-story')} style={{ fontSize: 12, whiteSpace: 'nowrap' }}>Read more <Icon.Arrow size={12} /></button>
        </div>
      </section>

      {/* Three pillars */}
      <section style={{
        padding: isMobile ? '48px 24px' : `80px ${padX}px`,
        borderTop: '1px solid var(--ink)',
        background: 'var(--paper)',
      }}>
        <Pillars accent={accent} isMobile={isMobile} />
      </section>

      {/* How it works */}
      <section id="how" style={{
        padding: isMobile ? '48px 24px' : `100px ${padX}px`,
        background: '#efece4',
        borderTop: '1px solid var(--rule)',
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 48, flexWrap: 'wrap', gap: 16 }}>
          <div>
            <Eyebrow>How it works</Eyebrow>
            <h2 className="serif" style={{ fontSize: isMobile ? 32 : 44, fontWeight: 350, letterSpacing: '-0.025em', margin: '12px 0 0' }}>
              Four steps. Roughly ninety seconds.
            </h2>
          </div>
          <div style={{ fontSize: 13, color: 'var(--ink-4)', maxWidth: 280 }}>
            Designed to be the lowest-friction way to find out where you stand.
          </div>
        </div>
        <HowItWorks accent={accent} isMobile={isMobile} />
      </section>

      {/* Editorial quote / institutional positioning */}
      {!isMobile && (
        <section style={{ padding: `100px ${padX}px`, background: 'var(--paper)', borderTop: '1px solid var(--rule)' }}>
          <div style={{ maxWidth: 880 }}>
            <Eyebrow>Why now</Eyebrow>
            <p className="serif" style={{ fontSize: isTablet ? 28 : 36, lineHeight: 1.25, fontWeight: 350, letterSpacing: '-0.02em', margin: '20px 0 32px', color: 'var(--ink)' }}>
              The traditional path — list publicly, attract calls, lose control of the narrative — was built for a buyer's market. <em style={{ fontWeight: 300 }}>This is the inverse.</em> Buyers tell us what they want. We show you whether you're a fit. You decide what happens next.
            </p>
            <div style={{ display: 'flex', alignItems: 'center', gap: 16, color: 'var(--ink-4)', fontSize: 12, fontFamily: 'var(--mono)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>
              <div style={{ width: 32, height: 1, background: 'var(--ink-4)' }} />
              <span>From the founding letter, 2025</span>
            </div>
          </div>
        </section>
      )}

      {/* Testimonials */}
      <section style={{ padding: isMobile ? '48px 24px' : `80px ${padX}px`, background: 'var(--paper)', borderTop: '1px solid var(--rule)' }}>
        <Eyebrow>From owners who matched</Eyebrow>
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(3, 1fr)', gap: isMobile ? 32 : 40, marginTop: 32 }}>
          {[
            { q: 'I matched 11 buyers and ended up closing with one of them six months later. I never had to put a sign in the window.', who: 'HVAC owner · $4M EBITDA · Texas' },
            { q: "I just wanted to know what my number was. The fact that the answer was real and specific to my industry — that's what got me to call.", who: 'MSP founder · $2.3M EBITDA · Florida' },
            { q: "My CPA recommended Buyside. The most useful 90 seconds I've spent thinking about my exit in the last decade.", who: 'Distribution · $6.8M EBITDA · Georgia' },
          ].map((t, i) => (
            <div key={i} style={{ paddingTop: 20, borderTop: '1px solid var(--ink)' }}>
              <p className="serif" style={{ fontSize: isMobile ? 19 : 22, lineHeight: 1.4, fontWeight: 400, letterSpacing: '-0.012em', margin: 0, color: 'var(--ink)' }}>"{t.q}"</p>
              <div className="mono" style={{ fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ink-4)', marginTop: 16 }}>— {t.who}</div>
            </div>
          ))}
        </div>
      </section>

      {/* Trust strip */}
      <section style={{
        padding: isMobile ? '40px 24px' : `48px ${padX}px`,
        background: 'var(--ink)', color: 'var(--paper)',
      }}>
        <TrustStrip inverse />
      </section>

      {/* Secondary CTA */}
      <section style={{
        padding: isMobile ? '64px 24px' : `120px ${padX}px`,
        textAlign: isMobile ? 'left' : 'center',
        background: 'var(--paper)',
      }}>
        <h2 className="serif" style={{ fontSize: isMobile ? 36 : 56, fontWeight: 350, letterSpacing: '-0.03em', margin: 0, lineHeight: 1.05 }}>
          Find out what your business <em style={{ fontWeight: 300 }}>is worth</em> to today's buyers.
        </h2>
        <div style={{ marginTop: 32, display: 'flex', gap: 16, justifyContent: isMobile ? 'flex-start' : 'center', flexWrap: 'wrap' }}>
          <button className="btn btn-primary btn-arrow" style={{ padding: '16px 24px', fontSize: 15 }} onClick={() => navigate('seller-wizard')}>
            See your matches
          </button>
        </div>
        <div style={{ marginTop: 24, display: 'flex', justifyContent: isMobile ? 'flex-start' : 'center' }}>
          <LockPill>Free · Confidential · No listing</LockPill>
        </div>
      </section>

      <Footer variant="seller" navigate={navigate} />

      {/* Sticky mobile CTA */}
      {isMobile && scrolled && (
        <div style={{
          position: 'sticky', bottom: 0, left: 0, right: 0,
          padding: 16, background: 'rgba(245,243,238,0.96)', backdropFilter: 'blur(12px)',
          borderTop: '1px solid var(--rule)',
          animation: 'fadeUp 0.3s ease',
        }}>
          <button className="btn btn-primary" style={{ width: '100%', padding: '16px' }} onClick={() => navigate('seller-wizard')}>
            See your matches  →
          </button>
        </div>
      )}
    </div>
  );
};

// ═══════════════════════════════════════════════════════════
// SELLER WIZARD — 8 questions
// ═══════════════════════════════════════════════════════════
const WIZARD_QUESTIONS = [
  {
    id: 'industry',
    eyebrow: 'Question 01 of 08',
    title: 'What industry is your business in?',
    subtitle: 'Pick the closest match. We use NAICS to find adjacencies.',
    type: 'select',
    options: ['HVAC / Plumbing / Electrical', 'IT Services / MSP', 'Manufacturing', 'Distribution / Wholesale', 'Healthcare Services', 'Professional Services', 'Construction / Trades', 'Food & Beverage', 'Transportation / Logistics', 'Auto Services / Collision', 'Landscaping / Lawn Care', 'Waste Management / Environmental', 'Staffing / Recruiting', 'Insurance Agency', 'Home Services / Restoration', 'Veterinary / Animal Health', 'Dental / Medical Practice', 'E-Commerce / DTC', 'SaaS / Software', 'Engineering / Architecture', 'Commercial Cleaning / Janitorial', 'Fitness / Wellness', 'Other'],
  },
  {
    id: 'revenue',
    eyebrow: 'Question 02 of 08',
    title: 'Annual revenue range?',
    subtitle: "Trailing twelve months is fine. We don't need exact figures.",
    type: 'select',
    options: ['Under $5M', '$5M – $10M', '$10M – $25M', '$25M – $50M', '$50M – $100M', 'Over $100M'],
  },
  {
    id: 'ebitda',
    eyebrow: 'Question 03 of 08',
    title: 'EBITDA range?',
    subtitle: 'Earnings before interest, taxes, depreciation, and amortization.',
    type: 'select',
    options: ['Under $1M', '$1M – $2M', '$2M – $5M', '$5M – $10M', 'Over $10M', 'Not sure'],
  },
  {
    id: 'years',
    eyebrow: 'Question 04 of 08',
    title: 'How long have you owned the business?',
    type: 'select',
    options: ['Less than 5 years', '5 – 10 years', '10 – 20 years', 'Over 20 years'],
  },
  {
    id: 'state',
    eyebrow: 'Question 05 of 08',
    title: 'What state are you headquartered in?',
    subtitle: 'For buyers with regional focus.',
    type: 'state',
  },
  {
    id: 'transition',
    eyebrow: 'Question 06 of 08',
    title: 'After a sale, how long would you stay involved?',
    subtitle: "There's no wrong answer. Buyers vary widely on this.",
    type: 'select',
    options: ['Walk away immediately', 'Stay 6 – 12 months', 'Stay 1 – 2 years', 'Stay 3+ years', 'Open to anything'],
  },
  {
    id: 'intent',
    eyebrow: 'Question 07 of 08',
    title: 'Where are you in the process?',
    subtitle: 'Just curious is a totally valid answer.',
    type: 'select',
    options: [
      { v: 'curious', label: 'Just curious about the market', sub: "You haven't decided anything yet." },
      { v: 'later',   label: 'Planning to sell in 1 – 2 years', sub: 'Thinking ahead, gathering information.' },
      { v: 'soon',    label: 'Planning to sell in 6 – 12 months', sub: 'Starting to take it seriously.' },
      { v: 'actively',label: 'Actively exploring offers', sub: "You'd talk to the right buyer this week." },
    ],
    rich: true,
  },
  {
    id: 'contact',
    eyebrow: 'Question 08 of 08',
    title: 'Where should we send your results?',
    subtitle: 'We never sell, share, or display this information.',
    type: 'contact',
  },
];

const STATE_LIST = ['California', 'Texas', 'Florida', 'New York', 'Illinois', '— — —', 'Alabama','Alaska','Arizona','Arkansas','Colorado','Connecticut','Delaware','Georgia','Hawaii','Idaho','Indiana','Iowa','Kansas','Kentucky','Louisiana','Maine','Maryland','Massachusetts','Michigan','Minnesota','Mississippi','Missouri','Montana','Nebraska','Nevada','New Hampshire','New Jersey','New Mexico','North Carolina','North Dakota','Ohio','Oklahoma','Oregon','Pennsylvania','Rhode Island','South Carolina','South Dakota','Tennessee','Utah','Vermont','Virginia','Washington','West Virginia','Wisconsin','Wyoming'];

const SellerWizard = ({ bp, navigate, answers, setAnswers, accent, setMatchResults, submitting, setSubmitting }) => {
  const isMobile = bp === 'mobile';
  const isTablet = bp === 'tablet';
  const padX = isMobile ? 24 : isTablet ? 80 : 120;

  const [stepIdx, setStepIdx] = useState(0);
  const step = WIZARD_QUESTIONS[stepIdx];
  const progress = ((stepIdx + 1) / WIZARD_QUESTIONS.length) * 100;

  const value = answers[step.id];
  const canProceed = useMemo(() => {
    if (step.id === 'contact') return answers.email && /^\S+@\S+\.\S+$/.test(answers.email) && answers.phone && answers.phone.replace(/\D/g,'').length >= 10;
    return !!value;
  }, [step, value, answers]);

  const next = async () => {
    if (!canProceed || submitting) return;
    if (stepIdx === WIZARD_QUESTIONS.length - 1) {
      setSubmitting(true);
      try {
        const results = await submitAndGenerate(answers);
        setMatchResults(results);
        navigate('seller-results');
      } catch (e) {
        console.error('Submit failed:', e);
        alert('Something went wrong. Please try again.');
      } finally {
        setSubmitting(false);
      }
    } else {
      setStepIdx(stepIdx + 1);
    }
  };
  const back = () => {
    if (stepIdx === 0) navigate('seller-landing');
    else setStepIdx(stepIdx - 1);
  };

  const setVal = (v) => setAnswers({ ...answers, [step.id]: v });

  return (
    <div className="viewport-scroll" style={{ background: 'var(--paper)', display: 'flex', flexDirection: 'column' }}>
      {/* Top bar */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: isMobile ? '16px 20px' : `20px ${padX}px`,
        borderBottom: '1px solid var(--rule)',
        position: 'sticky', top: 0, background: 'rgba(245,243,238,0.96)', backdropFilter: 'blur(10px)', zIndex: 10,
      }}>
        <Wordmark size={isMobile ? 18 : 20} />
        <div style={{ display: 'flex', alignItems: 'center', gap: 16, fontSize: 12, color: 'var(--ink-4)' }}>
          <Icon.Lock size={12} />
          <span style={{ fontFamily: 'var(--mono)', letterSpacing: '0.1em', textTransform: 'uppercase', fontSize: 10 }}>Confidential</span>
        </div>
      </div>

      {/* Progress */}
      <div style={{ padding: `0 ${padX}px`, marginTop: 20 }}>
        <div className="progress-track">
          <div className="progress-fill" style={{ width: `${progress}%` }} />
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 10, fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ink-4)' }}>
          <span>{step.eyebrow}</span>
          <span>{Math.round(progress)}% complete</span>
        </div>
      </div>

      {/* Question */}
      <div key={stepIdx} className="fade-up" style={{
        flex: 1, padding: isMobile ? '40px 24px 120px' : `64px ${padX}px 80px`,
        maxWidth: isTablet ? 720 : 820, width: '100%', margin: '0 auto',
      }}>
        <h2 className="serif" style={{
          fontSize: isMobile ? 30 : isTablet ? 38 : 44, lineHeight: 1.1,
          letterSpacing: '-0.025em', fontWeight: 400, margin: 0,
        }}>
          {step.title}
        </h2>
        {step.subtitle && (
          <p style={{ fontSize: 16, lineHeight: 1.55, color: 'var(--ink-3)', margin: '16px 0 0', maxWidth: 600 }}>
            {step.subtitle}
          </p>
        )}

        <div style={{ marginTop: 40 }}>
          {step.type === 'select' && !step.rich && (
            <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(2, 1fr)', gap: 10 }}>
              {step.options.map((opt) => {
                const sel = value === opt;
                return (
                  <button key={opt} className={`pill-option ${sel ? 'selected' : ''}`} onClick={() => setVal(opt)}>
                    <span>{opt}</span><span className="check" />
                  </button>
                );
              })}
            </div>
          )}
          {step.type === 'select' && step.rich && (
            <div style={{ display: 'grid', gap: 10 }}>
              {step.options.map((opt) => {
                const sel = value === opt.v;
                const isCurious = opt.v === 'curious';
                return (
                  <button key={opt.v} className={`pill-option ${sel ? 'selected' : ''}`} onClick={() => setVal(opt.v)} style={{ padding: '20px 22px', alignItems: 'flex-start' }}>
                    <div style={{ flex: 1, textAlign: 'left' }}>
                      <div style={{ fontSize: 16, fontWeight: 500, marginBottom: 4 }}>
                        {opt.label}
                        {isCurious && <span className="mono" style={{ fontSize: 9, marginLeft: 10, padding: '2px 6px', background: sel ? 'rgba(245,243,238,0.18)' : 'var(--emerald-soft)', color: sel ? 'var(--paper)' : 'var(--emerald)', borderRadius: 2, letterSpacing: '0.1em', textTransform: 'uppercase', verticalAlign: '2px' }}>Most chosen</span>}
                      </div>
                      <div style={{ fontSize: 13, color: sel ? 'rgba(245,243,238,0.7)' : 'var(--ink-4)' }}>{opt.sub}</div>
                    </div>
                    <span className="check" style={{ marginTop: 4 }} />
                  </button>
                );
              })}
            </div>
          )}
          {step.type === 'state' && (
            <div style={{ display: 'grid', gridTemplateColumns: isMobile ? 'repeat(2, 1fr)' : 'repeat(3, 1fr)', gap: 8 }}>
              {STATE_LIST.map((s, i) => {
                if (s.startsWith('—')) return <div key={i} style={{ gridColumn: '1 / -1', borderTop: '1px dashed var(--rule)', margin: '8px 0' }} />;
                const sel = value === s;
                const isTop = i < 5;
                return (
                  <button key={s} className={`pill-option ${sel ? 'selected' : ''}`} onClick={() => setVal(s)} style={{ padding: '12px 14px', fontSize: 14 }}>
                    <span style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      {isTop && !sel && <span className="mono" style={{ fontSize: 9, color: 'var(--ink-5)' }}>★</span>}
                      {s}
                    </span>
                  </button>
                );
              })}
            </div>
          )}
          {step.type === 'contact' && (
            <div style={{ display: 'grid', gap: 20, maxWidth: 560 }}>
              <div>
                <label className="field-label">Email <span style={{ color: 'var(--intent-red)' }}>*</span></label>
                <input className="field-input" placeholder="you@yourcompany.com" type="email"
                  value={answers.email || ''} onChange={(e) => setAnswers({...answers, email: e.target.value})} />
              </div>
              <div>
                <label className="field-label">Mobile phone <span style={{ color: 'var(--intent-red)' }}>*</span></label>
                <input className="field-input" placeholder="(555) 123-4567" inputMode="tel"
                  value={answers.phone || ''} onChange={(e) => setAnswers({...answers, phone: formatPhone(e.target.value)})}
                  autoComplete="off" />
              </div>
              <div style={{ fontSize: 12, color: 'var(--ink-4)', display: 'flex', gap: 8, alignItems: 'flex-start' }}>
                <Icon.Lock size={12} />
                <span>By submitting, you agree to our <a className="link-emerald" href="#">Privacy Policy</a>. We do not sell or share contact information. Ever.</span>
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Bottom action bar */}
      <div style={{
        position: 'sticky', bottom: 0,
        padding: isMobile ? '16px 24px' : `20px ${padX}px`,
        background: 'rgba(245,243,238,0.96)', backdropFilter: 'blur(10px)',
        borderTop: '1px solid var(--rule)',
        display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12,
      }}>
        <button className="btn btn-ghost" onClick={back}>
          <Icon.ArrowLeft /> {stepIdx === 0 ? 'Back to home' : 'Back'}
        </button>
        <button
          className="btn btn-primary btn-arrow"
          onClick={next}
          disabled={!canProceed}
          style={{ opacity: canProceed ? 1 : 0.35, pointerEvents: canProceed ? 'auto' : 'none' }}
        >
          {submitting ? 'Finding your matches...' : stepIdx === WIZARD_QUESTIONS.length - 1 ? 'Reveal my matches' : 'Continue'}
        </button>
      </div>
    </div>
  );
};

// ═══════════════════════════════════════════════════════════
// SELLER RESULTS — cinematic reveal
// ═══════════════════════════════════════════════════════════
const SAMPLE_BUYERS = [
  { type: 'PE Firm', n: '#147', aum: '$1.2B AUM', focus: 'Industrials roll-ups · Sun Belt', recent: 'Closed 3 deals in last 12 mo', initials: 'PE' },
  { type: 'Search Fund', n: '#89', aum: 'MBA-backed · $40M committed', focus: 'Owner-operator transition · Services', recent: 'New mandate · 2 weeks ago', initials: 'SF' },
  { type: 'Family Office', n: '#34', aum: '$320M family capital', focus: 'Long hold · Recurring revenue', recent: 'Active across 4 verticals', initials: 'FO' },
];

const SellerResults = ({ bp, navigate, answers, accent, reveal = 'cinematic', matchResults }) => {
  const isMobile = bp === 'mobile';
  const isTablet = bp === 'tablet';
  const padX = isMobile ? 24 : isTablet ? 56 : 80;

  // Use API results or fallback to defaults
  const r = matchResults || {};
  const target = r.matchCount || 23;
  const breakdown = r.buyerBreakdown || { pe: 14, searchFunds: 6, familyOffices: 3, strategic: 0 };
  const valuation = r.valuationRange || { lowMultiple: 4.8, highMultiple: 6.2, basis: 'EBITDA' };
  const marketData = r.marketData || { typicalDealStructure: 'Majority buyout', avgTimeToClose: '3–5 months', earnoutPrevalence: '35% of deals include an earnout' };
  const apiBuyers = r.anonymousBuyers || [];

  // Interleave buyer types for variety in the first 6
  const allBuyers = apiBuyers.length > 0 ? (() => {
    const byType = {};
    apiBuyers.forEach(b => { (byType[b.type] = byType[b.type] || []).push(b); });
    const types = Object.keys(byType);
    const result = [];
    let idx = 0;
    while (result.length < apiBuyers.length) {
      const type = types[idx % types.length];
      if (byType[type].length > 0) result.push(byType[type].shift());
      idx++;
      if (types.every(t => byType[t].length === 0)) break;
    }
    return result;
  })() : SAMPLE_BUYERS;

  const [showAllBuyers, setShowAllBuyers] = useState(false);
  const visibleBuyers = showAllBuyers ? allBuyers : allBuyers.slice(0, 6);

  const [count, setCount] = useState(0);

  useEffect(() => {
    if (reveal === 'instant') { setCount(target); return; }
    const dur = reveal === 'subtle' ? 1200 : 1800;
    const start = performance.now();
    let raf;
    const tick = (t) => {
      const p = Math.min(1, (t - start) / dur);
      const eased = 1 - Math.pow(1 - p, 3);
      setCount(Math.round(target * eased));
      if (p < 1) raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [reveal]);

  const stagger = reveal === 'cinematic' ? 0.18 : reveal === 'subtle' ? 0.08 : 0;

  return (
    <div className="viewport-scroll" style={{ background: 'var(--paper)' }}>
      {/* Top bar */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: isMobile ? '16px 20px' : `20px ${padX}px`,
        borderBottom: '1px solid var(--rule)',
      }}>
        <Wordmark size={isMobile ? 18 : 20} />
        <div className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-4)' }}>
          Match Report · {new Date().toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' })}
        </div>
      </div>

      {/* Hero result */}
      <section style={{ padding: isMobile ? '48px 24px 32px' : `${isTablet ? 64 : 96}px ${padX}px 48px` }}>
        <div className="fade-up" style={{ animationDelay: '0s' }}>
          <Eyebrow>Your matches · Generated just now</Eyebrow>
        </div>
        <div style={{
          display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1.1fr 1fr',
          gap: isMobile ? 32 : 64, alignItems: 'flex-end', marginTop: 28,
        }}>
          <div className="fade-up" style={{ animationDelay: `${stagger * 1}s` }}>
            <div className="big-num tnum" style={{ fontSize: isMobile ? 'clamp(96px, 32vw, 140px)' : isTablet ? 200 : 260, color: accent }}>
              {count}
            </div>
            <h1 className="serif" style={{ fontSize: isMobile ? 28 : isTablet ? 36 : 44, fontWeight: 350, letterSpacing: '-0.025em', margin: '8px 0 0', lineHeight: 1.1 }}>
              You match <em style={{ fontWeight: 300 }}>{target} active buyers</em>.
            </h1>
            <p style={{ fontSize: 16, color: 'var(--ink-3)', marginTop: 16, maxWidth: 480, lineHeight: 1.55 }}>
              Based on your industry ({answers.industry || 'HVAC / Plumbing / Electrical'}), size ({answers.revenue || '$10M – $25M'}), and location ({answers.state || 'Texas'}).
            </p>
          </div>
          <div className="fade-up" style={{ animationDelay: `${stagger * 2}s` }}>
            <div style={{
              border: '1px solid var(--rule)', padding: 24, background: '#faf8f3',
              display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 0,
            }}>
              {[
                { n: breakdown.pe, label: 'PE firms' },
                { n: breakdown.searchFunds, label: 'Search funds' },
                { n: (breakdown.familyOffices || 0) + (breakdown.strategic || 0), label: 'Family / Strategic' },
              ].map((b, i) => (
                <div key={i} style={{
                  padding: '0 16px',
                  borderLeft: i > 0 ? '1px solid var(--rule)' : 'none',
                }}>
                  <div className="serif tnum" style={{ fontSize: 40, fontWeight: 300, color: 'var(--ink)', letterSpacing: '-0.03em' }}>{b.n}</div>
                  <div style={{ fontSize: 12, color: 'var(--ink-4)', marginTop: 4 }}>{b.label}</div>
                </div>
              ))}
            </div>
          </div>
        </div>
      </section>

      {/* Market data block */}
      <section className="fade-up" style={{
        animationDelay: `${stagger * 3}s`,
        padding: isMobile ? '32px 24px' : `48px ${padX}px`,
        borderTop: '1px solid var(--rule)',
        background: '#efece4',
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 24, flexWrap: 'wrap', gap: 8 }}>
          <Eyebrow>Market data · {answers.industry || 'HVAC / Plumbing / Electrical'}</Eyebrow>
          <span className="mono" style={{ fontSize: 10, color: 'var(--ink-5)', letterSpacing: '0.1em', textTransform: 'uppercase' }}>n=42 closed comps · last 18 mo</span>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(3, 1fr)', gap: isMobile ? 1 : 1, background: 'var(--rule)' }}>
          {[
            { k: 'Estimated valuation', v: `${valuation.lowMultiple}× – ${valuation.highMultiple}×`, sub: `${valuation.basis} · majority transactions` },
            { k: 'Typical deal structure', v: marketData.typicalDealStructure, sub: marketData.earnoutPrevalence },
            { k: 'Average time to close', v: marketData.avgTimeToClose, sub: 'From mandate to wire' },
          ].map((r, i) => (
            <div key={i} style={{ background: '#efece4', padding: 24 }}>
              <div className="mono" style={{ fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ink-4)' }}>{r.k}</div>
              <div className="serif tnum" style={{ fontSize: isMobile ? 28 : 34, fontWeight: 350, letterSpacing: '-0.02em', margin: '8px 0 4px' }}>{r.v}</div>
              <div style={{ fontSize: 12, color: 'var(--ink-4)' }}>{r.sub}</div>
            </div>
          ))}
        </div>
      </section>

      {/* Anonymous buyer cards */}
      <section style={{ padding: isMobile ? '48px 24px' : `64px ${padX}px`, background: 'var(--paper)', borderTop: '1px solid var(--rule)' }}>
        <div className="fade-up" style={{ animationDelay: `${stagger * 4}s`, display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 28, flexWrap: 'wrap', gap: 8 }}>
          <div>
            <Eyebrow>Matched buyers</Eyebrow>
            <h2 className="serif" style={{ fontSize: isMobile ? 26 : 32, fontWeight: 400, letterSpacing: '-0.02em', margin: '10px 0 0' }}>
              Your {target} matches.
            </h2>
          </div>
          <div style={{ fontSize: 12, color: 'var(--ink-4)', maxWidth: 320 }}>
            Identities are never revealed without your written consent.
          </div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : isTablet ? 'repeat(2, 1fr)' : 'repeat(3, 1fr)', gap: 16 }}>
          {visibleBuyers.map((b, i) => (
            <div key={i} className="fade-up card" style={{
              animationDelay: `${stagger * (5 + Math.min(i, 6))}s`,
              padding: 24,
            }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 18 }}>
                <LockTile />
                <span className="mono" style={{ fontSize: 9, color: 'var(--emerald)', letterSpacing: '0.14em', textTransform: 'uppercase', padding: '3px 8px', border: '1px solid rgba(31,95,74,0.25)', background: 'rgba(31,95,74,0.05)' }}>Verified</span>
              </div>
              <div className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', color: 'var(--ink-5)', textTransform: 'uppercase' }}>{b.type}</div>
              <div className="serif" style={{ fontSize: 24, fontWeight: 400, letterSpacing: '-0.015em', margin: '4px 0 0' }}>{b.label || (b.type + ' ' + (b.n || ''))}</div>
              <div className="rule" style={{ margin: '16px 0' }} />
              <div style={{ display: 'grid', gap: 10, fontSize: 13 }}>
                <div><div className="mono" style={{ fontSize: 9, color: 'var(--ink-5)', letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 2 }}>Capital</div>{b.aum}</div>
                <div><div className="mono" style={{ fontSize: 9, color: 'var(--ink-5)', letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 2 }}>Focus</div>{b.focus}</div>
                <div><div className="mono" style={{ fontSize: 9, color: 'var(--ink-5)', letterSpacing: '0.12em', textTransform: 'uppercase', marginBottom: 2 }}>Recent activity</div>{b.recentActivity || b.recent}</div>
              </div>
            </div>
          ))}
        </div>
        {!showAllBuyers && allBuyers.length > 6 && (
          <div style={{ textAlign: 'center', marginTop: 28 }}>
            <button className="btn" style={{ padding: '14px 32px', fontSize: 14, color: 'var(--ink)', border: '1px solid var(--rule)' }} onClick={() => setShowAllBuyers(true)}>
              Show all {allBuyers.length} buyers
            </button>
          </div>
        )}
      </section>

      {/* Capex CTA */}
      <section className="fade-up" style={{
        animationDelay: `${stagger * 8}s`,
        padding: isMobile ? '48px 24px' : `80px ${padX}px`,
        background: 'var(--ink)', color: 'var(--paper)',
      }}>
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1.2fr 1fr', gap: isMobile ? 32 : 64, alignItems: 'center' }}>
          <div>
            <div className="mono" style={{ fontSize: 10, letterSpacing: '0.16em', color: 'rgba(245,243,238,0.5)', textTransform: 'uppercase' }}>
              <span style={{ display: 'inline-block', width: 6, height: 6, background: 'var(--emerald)', borderRadius: '50%', marginRight: 8, verticalAlign: '1px' }} />
              Capex Advisory · A confidential next step
            </div>
            <h2 className="serif" style={{ fontSize: isMobile ? 30 : isTablet ? 36 : 44, fontWeight: 350, letterSpacing: '-0.025em', margin: '16px 0 16px', lineHeight: 1.15 }}>
              Want to learn more <em style={{ fontWeight: 300 }}>confidentially</em>?
            </h2>
            <p style={{ fontSize: 16, color: 'rgba(245,243,238,0.75)', lineHeight: 1.6, margin: 0, maxWidth: 540 }}>
              Capex Advisory is the sell-side advisory firm that operates Buyside's matching service. A 30-minute confidential call walks you through your specific matches, valuation methodology, and what a real process would look like — at your pace, on your terms.
            </p>
          </div>
          <div style={{ display: 'grid', gap: 12 }}>
            <button className="btn btn-emerald btn-arrow" style={{ padding: '18px 24px', fontSize: 15, justifyContent: 'space-between' }} onClick={() => navigate('booking')}>
              Schedule confidential call
            </button>
<div style={{ marginTop: 8, fontSize: 12, color: 'rgba(245,243,238,0.55)' }}>
              No obligation. Your information is not shared with buyers without your written consent.
            </div>
          </div>
        </div>
      </section>

      <Footer variant="seller" navigate={navigate} />
    </div>
  );
};

// ═══════════════════════════════════════════════════════════
// CONFIDENTIAL CALL BOOKING
// ═══════════════════════════════════════════════════════════
const BookingFlow = ({ bp, navigate, answers, accent }) => {
  const isMobile = bp === 'mobile';
  const isTablet = bp === 'tablet';
  const padX = isMobile ? 24 : isTablet ? 48 : 80;

  const [step, setStep] = useState('schedule'); // schedule | confirm | done
  const [date, setDate] = useState(null);
  const [time, setTime] = useState(null);
  const [note, setNote] = useState('');
  const [booking, setBooking] = useState(false);

  const confirmBooking = async () => {
    setBooking(true);
    try {
      const dateStr = date.toLocaleDateString('en-US', { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric' });
      await fetch('/api/book', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          date: dateStr,
          time,
          note,
          email: answers.email || '',
          phone: answers.phone || '',
          industry: answers.industry || '',
          revenue: answers.revenue || '',
          ebitda: answers.ebitda || '',
        }),
      });
    } catch (e) {
      console.error('Booking email failed:', e);
    }
    setBooking(false);
    setStep('confirm');
  };

  const today = new Date();
  const days = Array.from({length: isMobile ? 7 : 14}, (_, i) => {
    const d = new Date(today); d.setDate(today.getDate() + i + 1);
    return d;
  });
  const times = ['9:00 AM', '10:00 AM', '11:30 AM', '1:00 PM', '2:30 PM', '4:00 PM'];

  return (
    <div className="viewport-scroll" style={{ background: 'var(--paper)' }}>
      {/* Top bar */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: isMobile ? '16px 20px' : `20px ${padX}px`,
        borderBottom: '1px solid var(--rule)',
      }}>
        <Wordmark size={isMobile ? 18 : 20} />
        <button className="btn btn-ghost" onClick={() => navigate('seller-results')} style={{ fontSize: 13 }}>
          <Icon.ArrowLeft /> Back to results
        </button>
      </div>

      {step === 'schedule' && (
        <div style={{ padding: isMobile ? '40px 24px 80px' : `${isTablet ? 56 : 80}px ${padX}px 80px`, maxWidth: 1080, margin: '0 auto' }}>
          <Eyebrow>Confidential Call</Eyebrow>
          <h1 className="serif" style={{ fontSize: isMobile ? 32 : isTablet ? 42 : 52, fontWeight: 350, letterSpacing: '-0.03em', margin: '12px 0 16px', lineHeight: 1.05 }}>
            Schedule a 30-minute call <em style={{ fontWeight: 300 }}>with your advisor</em>.
          </h1>
          <p style={{ fontSize: 16, color: 'var(--ink-3)', maxWidth: 600, margin: 0, lineHeight: 1.55 }}>
            A partner from Capex Advisory — our sell-side partner firm — will walk you through your matches, valuation, and process at your pace.
          </p>

          <div style={{ display: 'grid', gridTemplateColumns: isMobile || isTablet ? '1fr' : '1fr 320px', gap: 32, marginTop: 48 }}>
            <div>
              <div style={{ marginBottom: 32 }}>
                <div className="field-label">Select a date</div>
                <div style={{ display: 'grid', gridTemplateColumns: `repeat(${isMobile ? 4 : 7}, 1fr)`, gap: 6 }}>
                  {days.map((d, i) => {
                    const sel = date && d.toDateString() === date.toDateString();
                    const isWeekend = d.getDay() === 0 || d.getDay() === 6;
                    return (
                      <button
                        key={i}
                        className={`pill-option ${sel ? 'selected' : ''}`}
                        disabled={isWeekend}
                        onClick={() => setDate(d)}
                        style={{ flexDirection: 'column', padding: '12px 6px', opacity: isWeekend ? 0.3 : 1, alignItems: 'center', justifyContent: 'center' }}
                      >
                        <div className="mono" style={{ fontSize: 9, letterSpacing: '0.12em', textTransform: 'uppercase', opacity: 0.6 }}>{d.toLocaleDateString('en-US',{weekday:'short'})}</div>
                        <div className="serif" style={{ fontSize: 22, fontWeight: 350, marginTop: 2 }}>{d.getDate()}</div>
                        <div style={{ fontSize: 9, opacity: 0.6, marginTop: 2 }}>{d.toLocaleDateString('en-US',{month:'short'})}</div>
                      </button>
                    );
                  })}
                </div>
              </div>
              <div>
                <div className="field-label">Select a time {date && <span style={{ textTransform: 'none', letterSpacing: 0, color: 'var(--ink-3)', fontFamily: 'var(--sans)', fontSize: 12, marginLeft: 8 }}>· {date.toLocaleDateString('en-US',{weekday:'long', month:'long', day:'numeric'})}</span>}</div>
                <div style={{ display: 'grid', gridTemplateColumns: isMobile ? 'repeat(2, 1fr)' : 'repeat(3, 1fr)', gap: 6, opacity: date ? 1 : 0.4, pointerEvents: date ? 'auto' : 'none' }}>
                  {times.map((t) => (
                    <button key={t} className={`pill-option ${time === t ? 'selected' : ''}`} onClick={() => setTime(t)} style={{ padding: '14px', justifyContent: 'center' }}>
                      <span>{t}</span>
                    </button>
                  ))}
                </div>
                <div style={{ marginTop: 8, fontSize: 11, color: 'var(--ink-5)', fontFamily: 'var(--mono)', letterSpacing: '0.08em' }}>All times shown in your local timezone (CT)</div>
              </div>
              <div style={{ marginTop: 32 }}>
                <div className="field-label">Anything you want your advisor to know? (optional)</div>
                <textarea
                  className="field-input"
                  rows="3"
                  placeholder="e.g., We've had two unsolicited offers in the last 6 months and want to understand if those numbers are real."
                  value={note}
                  onChange={(e) => setNote(e.target.value)}
                  style={{ resize: 'vertical', fontFamily: 'var(--sans)' }}
                />
              </div>
              <button className="btn btn-emerald btn-arrow" style={{ marginTop: 24, padding: '16px 24px' }} disabled={!date || !time || booking} onClick={confirmBooking}>
                {booking ? 'Confirming...' : 'Confirm appointment'}
              </button>
            </div>

            {/* Sidebar — appointment summary */}
            {!isMobile && !isTablet && (
              <div style={{ padding: 24, background: '#faf8f3', border: '1px solid var(--rule)', alignSelf: 'start', position: 'sticky', top: 100 }}>
                <Eyebrow>Your appointment</Eyebrow>
                <div style={{ marginTop: 16, display: 'grid', gap: 14, fontSize: 13 }}>
                  <div>
                    <div className="mono" style={{ fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ink-5)' }}>Format</div>
                    <div style={{ marginTop: 2 }}>30-minute video call · Zoom</div>
                  </div>
                  <div>
                    <div className="mono" style={{ fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ink-5)' }}>Date & time</div>
                    <div style={{ marginTop: 2, color: date && time ? 'var(--ink)' : 'var(--ink-5)' }}>
                      {date && time ? `${date.toLocaleDateString('en-US',{weekday:'long', month:'long', day:'numeric'})} at ${time}` : 'Not yet selected'}
                    </div>
                  </div>
                  <div>
                    <div className="mono" style={{ fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ink-5)' }}>Sell-side advisor (Capex Advisory)</div>
                    <div style={{ marginTop: 2 }}>Auto-assigned by industry · You'll meet your advisor on confirmation.</div>
                  </div>
                </div>
                <hr className="rule" style={{ margin: '24px 0' }} />
                <LockPill>Confidential · No data shared</LockPill>
              </div>
            )}
          </div>
        </div>
      )}

      {step === 'confirm' && (
        <div className="fade-up" style={{ padding: isMobile ? '40px 24px' : `${isTablet ? 80 : 120}px ${padX}px`, maxWidth: 720, margin: '0 auto' }}>
          <div style={{
            width: 56, height: 56, borderRadius: '50%', background: 'var(--emerald-soft)',
            display: 'flex', alignItems: 'center', justifyContent: 'center', color: 'var(--emerald)',
          }}>
            <Icon.Check size={22} />
          </div>
          <h1 className="serif" style={{ fontSize: isMobile ? 32 : 48, fontWeight: 350, letterSpacing: '-0.025em', margin: '24px 0 12px', lineHeight: 1.1 }}>
            Confirmed.
          </h1>
          <p style={{ fontSize: 17, color: 'var(--ink-3)', lineHeight: 1.55, margin: 0 }}>
            We've held your spot. A calendar invite is on its way to <span style={{ color: 'var(--ink)' }}>{answers.email || 'you'}</span>.
          </p>

          <div className="card" style={{ marginTop: 32, padding: 28, display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '120px 1fr', gap: 24, alignItems: 'flex-start' }}>
            <img src="team/adam.png" alt="Adam Al-Sulaiti" style={{ width: 120, height: 120, borderRadius: 2, objectFit: 'cover' }} />
            <div>
              <Eyebrow>Your sell-side advisor</Eyebrow>
              <h3 className="serif" style={{ fontSize: 28, fontWeight: 400, letterSpacing: '-0.02em', margin: '8px 0 4px' }}>Adam Al-Sulaiti</h3>
              <div style={{ fontSize: 13, color: 'var(--ink-3)' }}>Managing Director · Capex Advisory · Industrials & Services</div>
              <div className="rule" style={{ margin: '20px 0' }} />
              <div style={{ display: 'grid', gap: 10, fontSize: 14 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                  <span style={{ color: 'var(--ink-4)' }}>When</span>
                  <span>{date && time ? `${date.toLocaleDateString('en-US',{weekday:'long', month:'short', day:'numeric'})} · ${time}` : 'Tue, Mar 12 · 2:30 PM'}</span>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                  <span style={{ color: 'var(--ink-4)' }}>Email</span>
                  <a className="link-emerald" href="mailto:ak@cap-ex.ai">ak@cap-ex.ai</a>
                </div>
                <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                  <span style={{ color: 'var(--ink-4)' }}>Direct line</span>
                  <span>(929) 640 · 3359</span>
                </div>
              </div>
            </div>
          </div>

          <div style={{ marginTop: 32, padding: 20, background: 'rgba(31,95,74,0.05)', border: '1px solid rgba(31,95,74,0.15)', borderRadius: 2, display: 'flex', gap: 14, alignItems: 'flex-start' }}>
            <Icon.Lock size={16} />
            <div style={{ fontSize: 13, color: 'var(--ink-2)', lineHeight: 1.55 }}>
              <strong style={{ fontWeight: 500 }}>This is a confidential conversation.</strong> Adam won't be sharing your information with any buyer. The call is for you to understand what's possible — nothing more, unless you decide otherwise.
            </div>
          </div>

          <div style={{ display: 'flex', gap: 12, marginTop: 32, flexWrap: 'wrap' }}>
            <button className="btn btn-secondary" onClick={() => navigate('seller-results')}>Back to my results</button>
            <button className="btn btn-ghost" onClick={() => setStep('schedule')}>Reschedule</button>
          </div>
        </div>
      )}
    </div>
  );
};

Object.assign(window, { SellerLanding, SellerWizard, SellerResults, BookingFlow, WIZARD_QUESTIONS, SAMPLE_BUYERS });
