/* global React, Footer, Wordmark, Eyebrow, Icon */
const { useState: iUseState } = React;

// ═══════════════════════════════════════════════════════════
// SHARED HEADER
// ═══════════════════════════════════════════════════════════
const InsightsHeader = ({ navigate, isMobile, padX, current }) => {
  const [drawerOpen, setDrawerOpen] = React.useState(false);
  return (
  <>
    <div style={{
      display: 'flex', alignItems: 'center', justifyContent: 'space-between',
      padding: isMobile ? '20px 24px' : `24px ${padX}px`,
      borderBottom: '1px solid var(--rule-2)',
    }}>
      <Wordmark size={isMobile ? 20 : 22} />
      <div style={{ display: 'flex', alignItems: 'center', gap: isMobile ? 10 : 16 }}>
        {!isMobile && (
          <button className="btn btn-ghost" onClick={() => navigate('seller-landing')} style={{ fontSize: 13 }}>
            <Icon.ArrowLeft /> Home
          </button>
        )}
        {!isMobile && (
          <button className="btn btn-primary" style={{ padding: '10px 18px', fontSize: 13 }} onClick={() => navigate('seller-wizard')}>
            See your matches
          </button>
        )}
        {isMobile && (
          <>
            <button className="btn btn-primary" style={{ padding: '8px 14px', fontSize: 12 }} onClick={() => navigate('seller-wizard')}>
              See matches
            </button>
            <MobileHamburger onClick={() => setDrawerOpen(true)} />
          </>
        )}
      </div>
    </div>
    {isMobile && <MobileNavDrawer open={drawerOpen} onClose={() => setDrawerOpen(false)} navigate={navigate} currentScreen={current} />}
    {/* Sub-nav for Insights */}
    <div style={{
      display: 'flex', gap: isMobile ? 16 : 32, padding: isMobile ? '14px 24px' : `16px ${padX}px`,
      borderBottom: '1px solid var(--rule)', background: '#faf8f3',
      overflowX: 'auto', whiteSpace: 'nowrap',
    }}>
      <span className="mono" style={{ fontSize: 10, letterSpacing: '0.16em', color: 'var(--ink-5)', textTransform: 'uppercase', alignSelf: 'center' }}>Insights /</span>
      {[
        { id: 'insights-reports', label: 'Market Reports' },
        { id: 'insights-multiples', label: 'Industry Multiples' },
        { id: 'insights-cases', label: 'Case Studies' },
        { id: 'insights-glossary', label: 'Glossary' },
      ].map((s) => (
        <button key={s.id} onClick={() => navigate(s.id)} style={{
          fontSize: 13, color: current === s.id ? 'var(--ink)' : 'var(--ink-3)',
          fontWeight: current === s.id ? 500 : 400,
          borderBottom: current === s.id ? '2px solid var(--ink)' : '2px solid transparent',
          paddingBottom: 4, background: 'none', border: 'none', cursor: 'pointer',
        }}>{s.label}</button>
      ))}
    </div>
  </>
  );
};

// ═══════════════════════════════════════════════════════════
// MARKET REPORTS
// ═══════════════════════════════════════════════════════════
const REPORTS = [
  { q: 'Q1 2026', title: 'LMM M&A Outlook: The Pre-Mandate Seller', pages: 28, date: 'Apr 2026', tag: 'Quarterly', summary: 'Why 73% of sub-$10M EBITDA owners are now starting their exit conversations 12+ months earlier than they did pre-2024.' },
  { q: 'Q4 2025', title: 'HVAC Roll-up Activity Report', pages: 22, date: 'Jan 2026', tag: 'Industry', summary: 'Multiple expansion in HVAC service businesses by region, fund concentration analysis, and the rise of platform-plus-tuck-in plays.' },
  { q: 'Q4 2025', title: 'Search Fund Capital Map 2025', pages: 18, date: 'Dec 2025', tag: 'Buyer-side', summary: 'Where the 210+ funded searchers in our network are looking, by industry and check size. Includes acceptance rates by deal source.' },
  { q: 'Q3 2025', title: 'Family Office Direct Investment Trends', pages: 24, date: 'Oct 2025', tag: 'Buyer-side', summary: "Multi-gen capital is bypassing PE for direct LMM acquisitions. We surveyed 64 family offices on what they're paying for." },
];

const MarketReportsPage = ({ bp, navigate, accent }) => {
  const isMobile = bp === 'mobile';
  const isTablet = bp === 'tablet';
  const padX = isMobile ? 24 : isTablet ? 56 : 80;
  return (
    <div className="viewport-scroll" style={{ background: 'var(--paper)' }}>
      <InsightsHeader navigate={navigate} isMobile={isMobile} padX={padX} current="insights-reports" />
      <section style={{ padding: isMobile ? '48px 24px' : `${isTablet ? 64 : 80}px ${padX}px 32px` }}>
        <Eyebrow>Market Reports</Eyebrow>
        <h1 className="serif" style={{ fontSize: isMobile ? 36 : isTablet ? 52 : 64, fontWeight: 350, letterSpacing: '-0.035em', margin: '20px 0 0', maxWidth: 920, lineHeight: 1.05 }}>
          Quarterly research on the lower-middle market.
        </h1>
        <p style={{ fontSize: isMobile ? 16 : 18, lineHeight: 1.55, color: 'var(--ink-3)', maxWidth: 640, margin: '20px 0 0' }}>
          Published research from our matching data and buyer surveys. Free to download.
        </p>
      </section>
      <section style={{ padding: isMobile ? '32px 24px 64px' : `48px ${padX}px 100px` }}>
        <div style={{ display: 'grid', gap: 1, background: 'var(--rule)', border: '1px solid var(--rule)' }}>
          {REPORTS.map((r, i) => (
            <div key={i} style={{
              background: 'var(--paper)', padding: isMobile ? 24 : 32,
              display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '120px 1fr 200px', gap: isMobile ? 16 : 32, alignItems: 'baseline',
            }}>
              <div>
                <div className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', color: accent, textTransform: 'uppercase' }}>{r.tag}</div>
                <div className="mono" style={{ fontSize: 11, color: 'var(--ink-4)', marginTop: 6 }}>{r.q}</div>
              </div>
              <div>
                <h3 className="serif" style={{ fontSize: isMobile ? 22 : 26, fontWeight: 400, letterSpacing: '-0.02em', margin: 0 }}>{r.title}</h3>
                <p style={{ fontSize: 14, lineHeight: 1.55, color: 'var(--ink-3)', margin: '12px 0 0', maxWidth: 640 }}>{r.summary}</p>
                <div className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', color: 'var(--ink-5)', textTransform: 'uppercase', marginTop: 14 }}>{r.pages} pages · Published {r.date}</div>
              </div>
              <button className="btn btn-secondary btn-arrow" style={{ fontSize: 13, padding: '10px 16px', justifySelf: isMobile ? 'flex-start' : 'flex-end' }}>
                Download PDF
              </button>
            </div>
          ))}
        </div>
      </section>
      <Footer variant="seller" navigate={navigate} />
    </div>
  );
};

// ═══════════════════════════════════════════════════════════
// INDUSTRY MULTIPLES
// ═══════════════════════════════════════════════════════════
const MULTIPLES = [
  { ind: 'HVAC services', low: 4.5, high: 6.8, n: 47, trend: '+0.4× YoY' },
  { ind: 'Specialty distribution', low: 5.2, high: 7.5, n: 38, trend: '+0.2× YoY' },
  { ind: 'Managed IT services (MSP)', low: 5.8, high: 8.4, n: 52, trend: '+0.6× YoY' },
  { ind: 'Commercial roofing', low: 4.2, high: 6.5, n: 29, trend: 'Flat YoY' },
  { ind: 'Pest control', low: 7.5, high: 11.0, n: 22, trend: '+1.1× YoY' },
  { ind: 'Industrial services', low: 5.0, high: 7.2, n: 41, trend: '+0.3× YoY' },
  { ind: 'B2B professional services', low: 4.8, high: 6.9, n: 56, trend: '−0.1× YoY' },
  { ind: 'Healthcare services (non-clinical)', low: 6.2, high: 9.5, n: 33, trend: '+0.5× YoY' },
  { ind: 'Specialty manufacturing', low: 5.5, high: 8.0, n: 44, trend: '+0.2× YoY' },
  { ind: 'Logistics & last-mile', low: 4.5, high: 7.0, n: 36, trend: 'Flat YoY' },
];

const IndustryMultiplesPage = ({ bp, navigate, accent }) => {
  const isMobile = bp === 'mobile';
  const isTablet = bp === 'tablet';
  const padX = isMobile ? 24 : isTablet ? 56 : 80;
  const maxX = 12;
  return (
    <div className="viewport-scroll" style={{ background: 'var(--paper)' }}>
      <InsightsHeader navigate={navigate} isMobile={isMobile} padX={padX} current="insights-multiples" />
      <section style={{ padding: isMobile ? '48px 24px' : `${isTablet ? 64 : 80}px ${padX}px 32px` }}>
        <Eyebrow>Industry Multiples · Q1 2026</Eyebrow>
        <h1 className="serif" style={{ fontSize: isMobile ? 36 : isTablet ? 52 : 64, fontWeight: 350, letterSpacing: '-0.035em', margin: '20px 0 0', maxWidth: 920, lineHeight: 1.05 }}>
          What buyers are paying, by industry.
        </h1>
        <p style={{ fontSize: isMobile ? 15 : 17, lineHeight: 1.55, color: 'var(--ink-3)', maxWidth: 720, margin: '20px 0 0' }}>
          Public-facing valuation ranges drawn from our matching data and closed-deal observations across the LMM ($1–10M EBITDA). Updated quarterly. Your specific range will narrow further once we see your industry, size, geography, and growth profile.
        </p>
      </section>
      <section style={{ padding: isMobile ? '24px 24px 64px' : `40px ${padX}px 100px` }}>
        <div style={{ border: '1px solid var(--rule)' }}>
          {/* Header row */}
          <div style={{
            display: 'grid', gridTemplateColumns: isMobile ? '1fr 80px' : '1fr 1fr 80px 100px',
            gap: 16, padding: isMobile ? '14px 18px' : '16px 24px',
            borderBottom: '1px solid var(--ink)', background: '#efece4',
          }}>
            <div className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-4)' }}>Industry</div>
            {!isMobile && <div className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-4)' }}>Range (× EBITDA)</div>}
            <div className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-4)', textAlign: 'right' }}>Range</div>
            {!isMobile && <div className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--ink-4)', textAlign: 'right' }}>Trend</div>}
          </div>
          {MULTIPLES.map((m, i) => (
            <div key={i} style={{
              display: 'grid', gridTemplateColumns: isMobile ? '1fr 80px' : '1fr 1fr 80px 100px',
              gap: 16, padding: isMobile ? '16px 18px' : '20px 24px',
              borderBottom: i < MULTIPLES.length - 1 ? '1px solid var(--rule)' : 'none',
              alignItems: 'center', background: i % 2 ? '#faf8f3' : 'var(--paper)',
            }}>
              <div>
                <div className="serif" style={{ fontSize: 16, fontWeight: 450, letterSpacing: '-0.012em' }}>{m.ind}</div>
                <div className="mono" style={{ fontSize: 10, color: 'var(--ink-5)', letterSpacing: '0.08em', marginTop: 4, textTransform: 'uppercase' }}>{m.n} comps</div>
              </div>
              {!isMobile && (
                <div style={{ position: 'relative', height: 22 }}>
                  <div style={{ position: 'absolute', left: 0, right: 0, top: 10, height: 1, background: 'var(--rule-2)' }} />
                  <div style={{
                    position: 'absolute', top: 6,
                    left: `${(m.low / maxX) * 100}%`, width: `${((m.high - m.low) / maxX) * 100}%`,
                    height: 10, background: accent, opacity: 0.85,
                  }} />
                </div>
              )}
              <div className="mono tnum" style={{ fontSize: 13, color: 'var(--ink)', textAlign: 'right', fontWeight: 500 }}>{m.low}–{m.high}×</div>
              {!isMobile && <div className="mono" style={{ fontSize: 11, color: m.trend.startsWith('+') ? 'var(--emerald)' : m.trend.startsWith('−') ? '#a04040' : 'var(--ink-4)', textAlign: 'right' }}>{m.trend}</div>}
            </div>
          ))}
        </div>
        <div className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', color: 'var(--ink-5)', textTransform: 'uppercase', marginTop: 16 }}>
          Data: Buyside matching observations Q4 2025 – Q1 2026 · n=398 · LMM only
        </div>
        <div style={{ marginTop: 40, padding: 24, background: '#efece4', display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 16 }}>
          <div style={{ fontSize: 14, color: 'var(--ink-2)', maxWidth: 600 }}>
            These are public ranges. <strong>Your specific range narrows by 30–40%</strong> once we see your industry, size, geography, and growth.
          </div>
          <button className="btn btn-primary btn-arrow" style={{ fontSize: 13, padding: '12px 18px' }} onClick={() => navigate('seller-wizard')}>
            See your range
          </button>
        </div>
      </section>
      <Footer variant="seller" navigate={navigate} />
    </div>
  );
};

// ═══════════════════════════════════════════════════════════
// CASE STUDIES
// ═══════════════════════════════════════════════════════════
const CASES = [
  { tag: 'HVAC', title: "A four-state HVAC operator who didn't want a public listing", size: '$4.2M EBITDA · 187 employees', outcome: '6.4× close · Texas family office · 4-yr earn-out', read: '8 min read', summary: 'Owner had been approached three times by brokers. None of the calls felt right. After a 90-second match flow he saw 11 buyers fit. He spoke to two. He chose the one whose principal had also bought from a founder. Closed in 7 months.' },
  { tag: 'MSP', title: 'A Florida MSP whose owner just wanted to know "the number"', size: '$2.3M EBITDA · 38 employees', outcome: '7.8× close · Search-funded operator', read: '6 min read', summary: 'Curious-not-committed seller. Match flow gave him a range; he talked to a Buyside advisor; he walked away with the number. Six months later, he came back. The match he closed with had been #3 on his original list.' },
  { tag: 'Distribution', title: 'A specialty distributor who matched, talked, and chose to stay', size: '$6.8M EBITDA · 94 employees', outcome: 'Did not transact', read: '4 min read', summary: "Sometimes the answer is no. The owner saw 23 matches, took 4 calls over 8 weeks, and decided market timing wasn't right. Two years of quarterly check-ins later, he's still on platform. Re-engagement when ready." },
];

const CaseStudiesPage = ({ bp, navigate, accent }) => {
  const isMobile = bp === 'mobile';
  const isTablet = bp === 'tablet';
  const padX = isMobile ? 24 : isTablet ? 56 : 80;
  return (
    <div className="viewport-scroll" style={{ background: 'var(--paper)' }}>
      <InsightsHeader navigate={navigate} isMobile={isMobile} padX={padX} current="insights-cases" />
      <section style={{ padding: isMobile ? '48px 24px' : `${isTablet ? 64 : 80}px ${padX}px 32px` }}>
        <Eyebrow>Case Studies</Eyebrow>
        <h1 className="serif" style={{ fontSize: isMobile ? 36 : isTablet ? 52 : 64, fontWeight: 350, letterSpacing: '-0.035em', margin: '20px 0 0', maxWidth: 920, lineHeight: 1.05 }}>
          What actually happened, anonymized.
        </h1>
        <p style={{ fontSize: isMobile ? 15 : 17, lineHeight: 1.55, color: 'var(--ink-3)', maxWidth: 640, margin: '20px 0 0' }}>
          Three matches — two closed, one didn't. All three are useful to read before you start.
        </p>
      </section>
      <section style={{ padding: isMobile ? '24px 24px 64px' : `48px ${padX}px 100px` }}>
        <div style={{ display: 'grid', gap: 32 }}>
          {CASES.map((c, i) => (
            <article key={i} style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '180px 1fr', gap: isMobile ? 16 : 48, paddingTop: 32, borderTop: '1px solid var(--ink)' }}>
              <div>
                <div className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', color: accent, textTransform: 'uppercase' }}>{c.tag}</div>
                <div className="mono" style={{ fontSize: 11, color: 'var(--ink-4)', marginTop: 8 }}>{c.read}</div>
              </div>
              <div>
                <h3 className="serif" style={{ fontSize: isMobile ? 24 : 30, fontWeight: 400, letterSpacing: '-0.022em', margin: 0, lineHeight: 1.2 }}>{c.title}</h3>
                <div className="mono" style={{ fontSize: 10, letterSpacing: '0.12em', color: 'var(--ink-5)', textTransform: 'uppercase', marginTop: 14 }}>{c.size}</div>
                <div className="mono" style={{ fontSize: 11, letterSpacing: '0.06em', color: 'var(--emerald)', marginTop: 6 }}>{c.outcome}</div>
                <p style={{ fontSize: 16, lineHeight: 1.6, color: 'var(--ink-2)', margin: '20px 0 16px', maxWidth: 720 }}>{c.summary}</p>
                <button className="btn btn-ghost" style={{ fontSize: 13, padding: 0 }}>Read full case <Icon.Arrow size={12} /></button>
              </div>
            </article>
          ))}
        </div>
      </section>
      <Footer variant="seller" navigate={navigate} />
    </div>
  );
};

// ═══════════════════════════════════════════════════════════
// GLOSSARY
// ═══════════════════════════════════════════════════════════
const GLOSSARY = [
  { letter: 'E', term: 'EBITDA', short: 'Earnings Before Interest, Taxes, Depreciation & Amortization', def: 'A rough proxy for the cash a business throws off, before financing decisions and accounting choices. The number most LMM buyers price off. Adjusted EBITDA (or "Adjusted EBITDA") adds back owner-specific expenses (excessive salary, personal vehicles, family on payroll). Most owners have higher adjusted EBITDA than reported EBITDA.' },
  { letter: 'L', term: 'LOI', short: 'Letter of Intent', def: `A non-binding agreement that says "we plan to acquire your business at this price, on these terms." Triggers exclusivity (the seller can't talk to other buyers for 30–90 days) and the start of formal due diligence. Most LOIs do close, but the price often moves between LOI and final purchase agreement based on what diligence finds.` },
  { letter: 'Q', term: 'QoE', short: 'Quality of Earnings', def: "A buyer-commissioned analysis (usually $30–100K) that scrubs the seller's financials. Looks for: revenue concentration, earnings volatility, working capital seasonality, owner add-back legitimacy. The result reshapes the deal. A bad QoE can drop price by 0.5–1× EBITDA. A clean QoE smooths the path to close." },
  { letter: 'E', term: 'Earnout', short: 'Performance-based payment', def: 'A portion of the sale price tied to future business performance. Common in deals where the buyer is uncertain about retention (key customer, key employee) or growth claims. Typical structure: 60–80% paid at close, 20–40% over 1–3 years tied to revenue or EBITDA targets. Earnouts are negotiable and frequently disputed.' },
  { letter: 'W', term: 'Working Capital Adjustment', short: 'Net working capital target', def: 'A "true-up" at close that adjusts the purchase price based on whether net working capital (current assets minus current liabilities) is above or below an agreed-upon target. Designed to ensure the buyer receives the business with enough cash and receivables to operate normally. Frequently the source of last-minute price disputes.' },
  { letter: 'R', term: 'Reps & Warranties', short: "Seller's promises about the business", def: 'Statements in the purchase agreement where the seller represents that things are as described — financials are accurate, no undisclosed lawsuits, IP is owned, etc. If a rep turns out false post-close, the seller may be liable. R&W insurance shifts that risk to an underwriter, and is increasingly standard above $5M EBITDA.' },
  { letter: 'I', term: 'IOI', short: 'Indication of Interest', def: `A non-binding letter (before the LOI) where a buyer says "we're interested at roughly this range." More tentative than an LOI, no exclusivity. A way to gauge mutual interest before committing diligence dollars. Buyside introductions often start at the IOI stage.` },
  { letter: 'P', term: 'Platform vs. Add-on', short: 'PE roll-up structure', def: 'A "platform" is the first acquisition in a roll-up — typically the largest, most professionally-managed business, used as the operating spine. "Add-ons" (or "tuck-ins") are smaller follow-on acquisitions that bolt onto the platform. Platforms trade for higher multiples than equivalent add-ons.' },
];

const GlossaryPage = ({ bp, navigate, accent }) => {
  const isMobile = bp === 'mobile';
  const isTablet = bp === 'tablet';
  const padX = isMobile ? 24 : isTablet ? 56 : 80;
  return (
    <div className="viewport-scroll" style={{ background: 'var(--paper)' }}>
      <InsightsHeader navigate={navigate} isMobile={isMobile} padX={padX} current="insights-glossary" />
      <section style={{ padding: isMobile ? '48px 24px' : `${isTablet ? 64 : 80}px ${padX}px 32px` }}>
        <Eyebrow>Glossary</Eyebrow>
        <h1 className="serif" style={{ fontSize: isMobile ? 36 : isTablet ? 52 : 64, fontWeight: 350, letterSpacing: '-0.035em', margin: '20px 0 0', maxWidth: 920, lineHeight: 1.05 }}>
          M&A terms, in plain English.
        </h1>
        <p style={{ fontSize: isMobile ? 15 : 17, lineHeight: 1.55, color: 'var(--ink-3)', maxWidth: 640, margin: '20px 0 0' }}>
          The 8 terms you'll actually encounter. Bookmark this page — you'll need it again.
        </p>
      </section>
      <section style={{ padding: isMobile ? '24px 24px 64px' : `40px ${padX}px 100px` }}>
        <div style={{ display: 'grid', gap: 0 }}>
          {GLOSSARY.map((g, i) => (
            <article key={i} style={{
              display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '120px 1fr',
              gap: isMobile ? 12 : 40, padding: isMobile ? '24px 0' : '32px 0',
              borderTop: '1px solid var(--rule)',
            }}>
              <div>
                <div className="serif" style={{ fontSize: isMobile ? 36 : 56, fontWeight: 300, lineHeight: 1, color: accent, letterSpacing: '-0.04em' }}>{g.letter}</div>
              </div>
              <div>
                <h3 className="serif" style={{ fontSize: isMobile ? 22 : 28, fontWeight: 400, letterSpacing: '-0.02em', margin: 0 }}>{g.term}</h3>
                <div className="mono" style={{ fontSize: 11, color: 'var(--ink-4)', letterSpacing: '0.06em', marginTop: 4 }}>{g.short}</div>
                <p style={{ fontSize: 15, lineHeight: 1.65, color: 'var(--ink-2)', margin: '16px 0 0', maxWidth: 760 }}>{g.def}</p>
              </div>
            </article>
          ))}
        </div>
      </section>
      <Footer variant="seller" navigate={navigate} />
    </div>
  );
};

Object.assign(window, { MarketReportsPage, IndustryMultiplesPage, CaseStudiesPage, GlossaryPage });
