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

// ═══════════════════════════════════════════════════════════
// BUYER LANDING
// ═══════════════════════════════════════════════════════════
const BuyerLanding = ({ 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)' }}>
      {/* 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} capex={!isMobile} />
        {!isMobile && (
          <div style={{ display: 'flex', gap: 32, alignItems: 'center', fontSize: 13, color: 'var(--ink-3)' }}>
            <a href="#" onClick={(e) => { e.preventDefault(); navigate('seller-landing'); }}>For sellers <Icon.ExtLink /></a>
            <a href="#" onClick={(e) => { e.preventDefault(); navigate('buyer-signin'); }}>Sign in</a>
            <button className="btn btn-primary" style={{ padding: '10px 18px', fontSize: 13 }} onClick={() => navigate('buyer-mandate')}>
              Submit mandate
            </button>
          </div>
        )}
      </div>

      {/* Hero */}
      <section style={{
        padding: isMobile ? '56px 24px 64px' : `${isTablet ? 80 : 120}px ${padX}px ${isTablet ? 80 : 120}px`,
        position: 'relative', overflow: 'hidden',
      }}>
        <Eyebrow>Institutional Buyer Access</Eyebrow>
        <h1 className="serif" style={{
          fontSize: isMobile ? 'clamp(36px, 10vw, 52px)' : isTablet ? 60 : 80,
          lineHeight: 1.05, letterSpacing: '-0.035em', fontWeight: 350,
          margin: '24px 0 0', maxWidth: 1000,
        }}>
          Proprietary deal flow from owners <em style={{ fontWeight: 300, color: accent }}>not yet on the market</em>.
        </h1>
        <p style={{
          fontSize: isMobile ? 16 : 19, lineHeight: 1.55, color: 'var(--ink-3)',
          maxWidth: 680, margin: '28px 0 0',
        }}>
          Submit your mandate. We'll match you with confidential sellers actively exploring exits — before they engage a banker.
        </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('buyer-mandate')}>
            Submit your mandate
          </button>
          <button className="btn btn-ghost" style={{ fontSize: 14 }}>
            See sample matches <Icon.Arrow />
          </button>
        </div>
        <div style={{ marginTop: 28, display: 'flex', gap: 24, alignItems: 'center', flexWrap: 'wrap' }}>
          <span className="mono" style={{ fontSize: 11, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--ink-4)' }}>
            <span style={{ color: accent }}>●</span> Free to register · No subscription · Verified counter-parties only
          </span>
        </div>
      </section>

      {/* Why buyside — 4 points */}
      <section style={{
        padding: isMobile ? '48px 24px' : `80px ${padX}px`,
        background: 'var(--ink)', color: 'var(--paper)',
      }}>
        <Eyebrow color="rgba(245,243,238,0.5)">Why Buyside</Eyebrow>
        <h2 className="serif" style={{ fontSize: isMobile ? 30 : 42, fontWeight: 350, letterSpacing: '-0.025em', margin: '12px 0 48px', maxWidth: 720 }}>
          A different kind of deal pipeline — narrower, warmer, and never public.
        </h2>
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : 'repeat(2, 1fr)', gap: isMobile ? 32 : 48, maxWidth: 1100 }}>
          {[
            { n: '01', t: 'Pre-mandate sellers', b: "Owners arrive curious, not committed. Most haven't engaged a banker. You see them before the auction starts." },
            { n: '02', t: 'No subscription fee', b: 'Buyside is free for verified buyers. We monetize through sell-side advisory partnerships, not buyer subscriptions.' },
            { n: '03', t: 'Anonymous double-blind', b: 'Sellers stay confidential until mutual interest is confirmed. You stay confidential until they say yes.' },
            { n: '04', t: 'Advisor-facilitated', b: 'Every introduction is brokered by a partner advisor. No cold outreach. No leaked information. Clean process.' },
          ].map((p, i) => (
            <div key={i}>
              <div className="mono" style={{ fontSize: 11, letterSpacing: '0.16em', color: accent }}>{p.n}</div>
              <h3 className="serif" style={{ fontSize: 24, fontWeight: 400, letterSpacing: '-0.015em', margin: '12px 0 10px' }}>{p.t}</h3>
              <p style={{ fontSize: 15, lineHeight: 1.6, color: 'rgba(245,243,238,0.7)', margin: 0 }}>{p.b}</p>
            </div>
          ))}
        </div>
      </section>

      {/* Buyer types */}
      <section style={{ padding: isMobile ? '48px 24px' : `80px ${padX}px`, background: '#efece4' }}>
        <Eyebrow>Who we work with</Eyebrow>
        <h2 className="serif" style={{ fontSize: isMobile ? 28 : 38, fontWeight: 350, letterSpacing: '-0.02em', margin: '12px 0 40px' }}>
          Verified institutional buyers across four categories.
        </h2>
        <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : isTablet ? 'repeat(2, 1fr)' : 'repeat(4, 1fr)', gap: 1, background: 'var(--rule)', border: '1px solid var(--rule)' }}>
          {[
            { t: 'PE Firms', b: 'Lower & middle-market. Industry-focused or generalist. Platform & add-on mandates welcome.' },
            { t: 'Search Funds', b: 'Self-funded, traditional, and accelerator-backed searchers. Most active category on Buyside.' },
            { t: 'Family Offices', b: 'Single & multi-family. Long-hold, dividend-oriented, or strategic operating capital.' },
            { t: 'Strategic Acquirers', b: 'Operating companies with M&A teams pursuing tuck-ins, regional expansion, or vertical integration.' },
          ].map((c, i) => (
            <div key={i} style={{ background: '#efece4', padding: isMobile ? 24 : 28 }}>
              <div className="mono" style={{ fontSize: 10, letterSpacing: '0.14em', color: 'var(--ink-5)', textTransform: 'uppercase' }}>0{i+1}</div>
              <h3 className="serif" style={{ fontSize: 22, fontWeight: 400, letterSpacing: '-0.015em', margin: '12px 0 10px' }}>{c.t}</h3>
              <p style={{ fontSize: 13, lineHeight: 1.6, color: 'var(--ink-3)', margin: 0 }}>{c.b}</p>
            </div>
          ))}
        </div>
      </section>

      {/* CTA */}
      <section style={{ padding: isMobile ? '64px 24px' : `100px ${padX}px`, textAlign: isMobile ? 'left' : 'center' }}>
        <h2 className="serif" style={{ fontSize: isMobile ? 32 : 52, fontWeight: 350, letterSpacing: '-0.03em', margin: 0, lineHeight: 1.05 }}>
          Submit a mandate in <em style={{ fontWeight: 300 }}>under five minutes</em>.
        </h2>
        <p style={{ fontSize: 16, color: 'var(--ink-3)', maxWidth: 580, margin: isMobile ? '20px 0 0' : '20px auto 0', lineHeight: 1.55 }}>
          Verification typically completes within 24–48 hours. Once active, you'll see live matches as new sellers complete the flow.
        </p>
        <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('buyer-mandate')}>
            Submit your mandate
          </button>
        </div>
      </section>

      {/* Verification statement */}
      <section style={{ padding: isMobile ? '32px 24px 48px' : `48px ${padX}px 80px`, borderTop: '1px solid var(--rule)' }}>
        <div className="mono" style={{ fontSize: 11, letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ink-4)', maxWidth: 720, lineHeight: 1.7 }}>
          <span style={{ color: 'var(--ink)' }}>Verification statement.</span> All buyers are verified for legitimacy and capital before mandates are activated. Submission does not guarantee inclusion. Buyside reserves the right to decline mandates that do not meet platform standards.
        </div>
      </section>

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

// ═══════════════════════════════════════════════════════════
// BUYER MANDATE INTAKE FORM
// ═══════════════════════════════════════════════════════════
const BuyerMandate = ({ bp, navigate, accent }) => {
  const isMobile = bp === 'mobile';
  const isTablet = bp === 'tablet';
  const padX = isMobile ? 24 : isTablet ? 56 : 80;

  const [section, setSection] = useState(0);
  const sections = [
    { id: 'firm', label: 'Firm details' },
    { id: 'criteria', label: 'Buy-box criteria' },
    { id: 'verify', label: 'Verification' },
    { id: 'contact', label: 'Contact' },
  ];

  const [data, setData] = useState({
    firmName: '', firmType: 'PE', aum: '', recentDeals: '',
    industries: [], revMin: '', revMax: '', ebitdaMin: '', ebitdaMax: '',
    geography: [], structure: 'Majority', transition: 'Open', hold: '',
    docs: [], name: '', title: '', email: '', phone: '',
  });

  const toggleArr = (key, v) => {
    const arr = data[key].includes(v) ? data[key].filter(x => x !== v) : [...data[key], v];
    setData({ ...data, [key]: arr });
  };

  const INDUSTRIES = ['HVAC / Plumbing / Electrical', 'IT Services / MSP', 'Manufacturing', 'Distribution', 'Healthcare Services', 'Professional Services', 'Construction', 'Food & Beverage', 'Logistics', 'Consumer'];
  const STATES_GRID = ['CA','TX','FL','NY','IL','PA','OH','GA','NC','MI','NJ','VA','WA','AZ','MA','TN','IN','MO','MD','WI','CO','MN','SC','AL','LA','KY','OR','OK','CT','UT','IA','NV','AR','MS','KS','NM','NE','WV','ID','HI','NH','ME','MT','RI','DE','SD','ND','AK','VT','WY'];

  return (
    <div className="viewport-scroll" style={{ background: 'var(--paper)' }}>
      <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} capex={!isMobile} />
        <button className="btn btn-ghost" onClick={() => navigate('buyer-landing')} style={{ fontSize: 13 }}>
          <Icon.ArrowLeft /> Cancel
        </button>
      </div>

      <div style={{ padding: isMobile ? '32px 24px 80px' : `${isTablet ? 48 : 64}px ${padX}px 80px`, maxWidth: 1100, margin: '0 auto' }}>
        <div style={{ display: 'grid', gridTemplateColumns: isMobile || isTablet ? '1fr' : '220px 1fr', gap: 48 }}>
          {/* Sidebar nav */}
          <div style={{ position: isMobile || isTablet ? 'static' : 'sticky', top: 100, alignSelf: 'start' }}>
            <Eyebrow>Mandate intake</Eyebrow>
            <div style={{ marginTop: 12, marginBottom: 24 }}>
              <h1 className="serif" style={{ fontSize: 28, fontWeight: 400, letterSpacing: '-0.02em', margin: 0, lineHeight: 1.15 }}>Define your buy-box.</h1>
            </div>
            <div style={{ display: isMobile || isTablet ? 'flex' : 'block', gap: 0, overflowX: 'auto' }}>
              {sections.map((s, i) => (
                <button key={s.id} onClick={() => setSection(i)} style={{
                  display: 'flex', alignItems: 'center', gap: 12,
                  padding: isMobile ? '8px 14px' : '10px 0',
                  width: isMobile || isTablet ? 'auto' : '100%',
                  borderLeft: !isMobile && !isTablet ? `2px solid ${section === i ? 'var(--ink)' : 'var(--rule)'}` : 'none',
                  borderBottom: isMobile || isTablet ? `2px solid ${section === i ? 'var(--ink)' : 'transparent'}` : 'none',
                  paddingLeft: !isMobile && !isTablet ? 14 : undefined,
                  color: section === i ? 'var(--ink)' : 'var(--ink-4)',
                  fontSize: 13, justifyContent: 'flex-start', whiteSpace: 'nowrap',
                }}>
                  <span className="mono" style={{ fontSize: 10, letterSpacing: '0.12em', opacity: 0.6 }}>0{i+1}</span>
                  <span>{s.label}</span>
                </button>
              ))}
            </div>
          </div>

          {/* Form */}
          <div>
            {section === 0 && (
              <div className="fade-up" style={{ display: 'grid', gap: 24 }}>
                <div>
                  <label className="field-label">Firm name</label>
                  <input className="field-input" placeholder="Permanent Equity, e.g." value={data.firmName} onChange={e=>setData({...data, firmName: e.target.value})} />
                </div>
                <div>
                  <label className="field-label">Firm type</label>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(140px, 1fr))', gap: 8 }}>
                    {['PE Firm', 'Search Fund', 'Family Office', 'Strategic', 'HNW Individual'].map(t => (
                      <button key={t} className={`pill-option ${data.firmType === t ? 'selected' : ''}`} onClick={()=>setData({...data, firmType: t})} style={{ padding: '12px 14px', fontSize: 13, justifyContent: 'center' }}>
                        {t}
                      </button>
                    ))}
                  </div>
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 16 }}>
                  <div>
                    <label className="field-label">AUM / Fund size</label>
                    <input className="field-input" placeholder="$250M committed" value={data.aum} onChange={e=>setData({...data, aum: e.target.value})} />
                  </div>
                  <div>
                    <label className="field-label">Recent closed deals</label>
                    <input className="field-input" placeholder="3 platforms in last 18 mo" value={data.recentDeals} onChange={e=>setData({...data, recentDeals: e.target.value})} />
                  </div>
                </div>
              </div>
            )}

            {section === 1 && (
              <div className="fade-up" style={{ display: 'grid', gap: 32 }}>
                <div>
                  <label className="field-label">Industries targeted (multi-select)</label>
                  <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr 1fr' : 'repeat(3, 1fr)', gap: 6 }}>
                    {INDUSTRIES.map(ind => (
                      <button key={ind} className={`pill-option ${data.industries.includes(ind) ? 'selected' : ''}`} onClick={() => toggleArr('industries', ind)} style={{ padding: '10px 14px', fontSize: 13 }}>
                        <span>{ind}</span>
                      </button>
                    ))}
                  </div>
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                  <div>
                    <label className="field-label">Revenue (min)</label>
                    <input className="field-input" placeholder="$5M" value={data.revMin} onChange={e=>setData({...data, revMin: e.target.value})} />
                  </div>
                  <div>
                    <label className="field-label">Revenue (max)</label>
                    <input className="field-input" placeholder="$50M" value={data.revMax} onChange={e=>setData({...data, revMax: e.target.value})} />
                  </div>
                  <div>
                    <label className="field-label">EBITDA (min)</label>
                    <input className="field-input" placeholder="$1M" value={data.ebitdaMin} onChange={e=>setData({...data, ebitdaMin: e.target.value})} />
                  </div>
                  <div>
                    <label className="field-label">EBITDA (max)</label>
                    <input className="field-input" placeholder="$10M" value={data.ebitdaMax} onChange={e=>setData({...data, ebitdaMax: e.target.value})} />
                  </div>
                </div>
                <div>
                  <label className="field-label">Geography ({data.geography.length} of 50 selected)</label>
                  <div style={{ display: 'flex', gap: 8, marginBottom: 8, flexWrap: 'wrap' }}>
                    <button className="btn btn-ghost" style={{ fontSize: 12, padding: '4px 0' }} onClick={() => setData({...data, geography: STATES_GRID})}>Select all</button>
                    <span style={{ color: 'var(--ink-5)' }}>·</span>
                    <button className="btn btn-ghost" style={{ fontSize: 12, padding: '4px 0' }} onClick={() => setData({...data, geography: []})}>Clear</button>
                  </div>
                  <div style={{ display: 'grid', gridTemplateColumns: `repeat(${isMobile ? 5 : 10}, 1fr)`, gap: 4 }}>
                    {STATES_GRID.map(s => (
                      <button key={s} onClick={() => toggleArr('geography', s)} className="mono" style={{
                        padding: '8px 4px', fontSize: 11, letterSpacing: '0.04em',
                        border: '1px solid var(--rule)',
                        background: data.geography.includes(s) ? 'var(--ink)' : 'transparent',
                        color: data.geography.includes(s) ? 'var(--paper)' : 'var(--ink-3)',
                        borderColor: data.geography.includes(s) ? 'var(--ink)' : 'var(--rule)',
                        borderRadius: 2, cursor: 'pointer',
                      }}>{s}</button>
                    ))}
                  </div>
                </div>
                <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 16 }}>
                  <div>
                    <label className="field-label">Deal structure</label>
                    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 6 }}>
                      {['Majority', 'Minority', 'Full', 'Open'].map(t => (
                        <button key={t} className={`pill-option ${data.structure === t ? 'selected' : ''}`} onClick={()=>setData({...data, structure: t})} style={{ padding: '10px', fontSize: 13, justifyContent: 'center' }}>{t}</button>
                      ))}
                    </div>
                  </div>
                  <div>
                    <label className="field-label">Owner transition preference</label>
                    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 6 }}>
                      {['0 mo', '6–12 mo', '1–2 yr', '3+ yr', 'Open'].map(t => (
                        <button key={t} className={`pill-option ${data.transition === t ? 'selected' : ''}`} onClick={()=>setData({...data, transition: t})} style={{ padding: '10px', fontSize: 13, justifyContent: 'center' }}>{t}</button>
                      ))}
                    </div>
                  </div>
                </div>
                <div>
                  <label className="field-label">Hold period</label>
                  <input className="field-input" placeholder="5–7 years typical" value={data.hold} onChange={e=>setData({...data, hold: e.target.value})} />
                </div>
              </div>
            )}

            {section === 2 && (
              <div className="fade-up" style={{ display: 'grid', gap: 24 }}>
                <p style={{ fontSize: 14, color: 'var(--ink-3)', lineHeight: 1.6, margin: 0 }}>
                  Verification typically completes in 24–48 hours. Documents are reviewed by our verification team and stored encrypted. They are never shown to sellers.
                </p>
                {[
                  { t: 'Fund proof', d: 'LP commitment letter, fund formation docs, or audited financials.' },
                  { t: 'AUM proof', d: 'Most recent capital account statement or Form ADV.' },
                  { t: 'LinkedIn / bio', d: 'For individuals or first-time searchers.' },
                ].map((d, i) => (
                  <div key={i} style={{ padding: 20, border: '1px dashed var(--rule)', borderRadius: 2, display: 'flex', gap: 16, alignItems: 'center', justifyContent: 'space-between' }}>
                    <div>
                      <div style={{ fontWeight: 500, fontSize: 14 }}>{d.t}</div>
                      <div style={{ fontSize: 12, color: 'var(--ink-4)', marginTop: 2 }}>{d.d}</div>
                    </div>
                    <button className="btn btn-secondary" style={{ fontSize: 12, padding: '8px 14px' }}>
                      <Icon.Upload size={12} /> Upload
                    </button>
                  </div>
                ))}
              </div>
            )}

            {section === 3 && (
              <div className="fade-up" style={{ display: 'grid', gap: 16, maxWidth: 600 }}>
                <div style={{ display: 'grid', gridTemplateColumns: isMobile ? '1fr' : '1fr 1fr', gap: 16 }}>
                  <div>
                    <label className="field-label">Full name</label>
                    <input className="field-input" placeholder="Jane Doe" value={data.name} onChange={e=>setData({...data, name: e.target.value})} />
                  </div>
                  <div>
                    <label className="field-label">Title</label>
                    <input className="field-input" placeholder="Partner" value={data.title} onChange={e=>setData({...data, title: e.target.value})} />
                  </div>
                </div>
                <div>
                  <label className="field-label">Work email</label>
                  <input className="field-input" placeholder="jane@firm.com" value={data.email} onChange={e=>setData({...data, email: e.target.value})} />
                </div>
                <div>
                  <label className="field-label">Direct phone</label>
                  <input className="field-input" placeholder="(555) 123-4567" value={data.phone} onChange={e=>setData({...data, phone: formatPhone(e.target.value)})} />
                </div>
              </div>
            )}

            {/* Nav */}
            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 48, paddingTop: 24, borderTop: '1px solid var(--rule)', gap: 12, flexWrap: 'wrap' }}>
              <button className="btn btn-ghost" onClick={() => section === 0 ? navigate('buyer-landing') : setSection(section - 1)}>
                <Icon.ArrowLeft /> {section === 0 ? 'Cancel' : 'Previous'}
              </button>
              {section < sections.length - 1 ? (
                <button className="btn btn-primary btn-arrow" onClick={() => setSection(section + 1)}>
                  Continue · {sections[section + 1].label}
                </button>
              ) : (
                <button className="btn btn-emerald btn-arrow" onClick={() => navigate('buyer-dashboard')}>
                  Submit for verification
                </button>
              )}
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

// ═══════════════════════════════════════════════════════════
// BUYER DASHBOARD
// ═══════════════════════════════════════════════════════════
const SELLER_MATCHES = [
  { id: 'QM-2847', industry: 'HVAC / Plumbing / Electrical', state: 'TX', years: '15 yrs', rev: '$18M', ebitda: '$3.2M', transition: 'Stay 6–12 mo', intent: 'actively', score: 94, isNew: true,  rep: 'R. Alvarado' },
  { id: 'QM-2841', industry: 'IT Services / MSP',           state: 'FL', years: '11 yrs', rev: '$24M', ebitda: '$5.1M', transition: 'Walk away',     intent: 'soon',     score: 91, isNew: true,  rep: 'D. Mensah' },
  { id: 'QM-2838', industry: 'Distribution',                 state: 'GA', years: '22 yrs', rev: '$42M', ebitda: '$6.8M', transition: 'Stay 1–2 yr',  intent: 'soon',     score: 88, isNew: false, rep: 'R. Alvarado' },
  { id: 'QM-2829', industry: 'Manufacturing',                state: 'NC', years: '18 yrs', rev: '$31M', ebitda: '$4.5M', transition: 'Open',         intent: 'later',    score: 84, isNew: false, rep: 'R. Alvarado' },
  { id: 'QM-2821', industry: 'HVAC / Plumbing / Electrical', state: 'TN', years: '8 yrs',  rev: '$11M', ebitda: '$2.1M', transition: 'Stay 3+ yr',   intent: 'curious',  score: 79, isNew: false, rep: 'D. Mensah' },
  { id: 'QM-2814', industry: 'Healthcare Services',          state: 'TX', years: '14 yrs', rev: '$22M', ebitda: '$4.0M', transition: 'Stay 6–12 mo', intent: 'soon',     score: 76, isNew: false, rep: 'R. Alvarado' },
  { id: 'QM-2806', industry: 'Professional Services',        state: 'IL', years: '20 yrs', rev: '$15M', ebitda: '$2.8M', transition: 'Walk away',     intent: 'curious',  score: 72, isNew: false, rep: 'D. Mensah' },
  { id: 'QM-2799', industry: 'Construction / Trades',        state: 'AZ', years: '12 yrs', rev: '$28M', ebitda: '$3.9M', transition: 'Stay 1–2 yr',  intent: 'later',    score: 68, isNew: false, rep: 'R. Alvarado' },
];

const BuyerDashboard = ({ bp, navigate, accent }) => {
  const isMobile = bp === 'mobile';
  const isTablet = bp === 'tablet';
  const padX = isMobile ? 16 : isTablet ? 32 : 48;

  const [tab, setTab] = useState('matches');
  const [filter, setFilter] = useState('all');
  const [interestedIds, setInterestedIds] = useState([]);

  const filtered = useMemo(() => {
    if (filter === 'all') return SELLER_MATCHES;
    return SELLER_MATCHES.filter(s => s.intent === filter);
  }, [filter]);

  return (
    <div className="viewport-scroll" style={{ background: '#f0ede5' }}>
      {/* Top header */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: isMobile ? '14px 16px' : `16px ${padX}px`,
        borderBottom: '1px solid var(--rule)', background: 'var(--paper)',
        position: 'sticky', top: 0, zIndex: 10,
      }}>
        <Wordmark size={isMobile ? 18 : 20} capex={!isMobile} />
        <div style={{ display: 'flex', alignItems: 'center', gap: 16, fontSize: 13 }}>
          {!isMobile && (
            <span className="mono" style={{ fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ink-4)' }}>
              <span style={{ color: accent }}>●</span> Verified buyer
            </span>
          )}
          <div style={{
            width: 32, height: 32, borderRadius: '50%', background: 'var(--ink)', color: 'var(--paper)',
            display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'var(--serif)', fontSize: 14,
          }}>P</div>
        </div>
      </div>

      {/* Firm header */}
      <section style={{ padding: isMobile ? '24px 16px 16px' : `36px ${padX}px 24px`, background: 'var(--paper)', borderBottom: '1px solid var(--rule)' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 24, flexWrap: 'wrap' }}>
          <div>
            <Eyebrow>PE Firm · Verified Mar 2026</Eyebrow>
            <h1 className="serif" style={{ fontSize: isMobile ? 28 : 38, fontWeight: 400, letterSpacing: '-0.025em', margin: '8px 0 0' }}>
              Permanent Equity
            </h1>
            <div style={{ fontSize: 13, color: 'var(--ink-4)', marginTop: 4 }}>$1.2B AUM · Lower-middle market industrials</div>
          </div>
          <button className="btn btn-secondary" style={{ fontSize: 13 }} onClick={() => navigate('buyer-mandate')}>
            <Icon.Plus /> New mandate
          </button>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: `repeat(${isMobile ? 2 : 4}, 1fr)`, gap: 1, background: 'var(--rule)', border: '1px solid var(--rule)', marginTop: 24 }}>
          {[
            { v: '3', k: 'Active mandates' },
            { v: '12', k: 'Matches this month', accent: true },
            { v: '4', k: 'Conversations open' },
            { v: '1', k: 'Under LOI' },
          ].map((s, i) => (
            <div key={i} style={{ background: 'var(--paper)', padding: isMobile ? 14 : 18 }}>
              <div className="serif tnum" style={{ fontSize: 30, fontWeight: 350, color: s.accent ? accent : 'var(--ink)', letterSpacing: '-0.025em' }}>{s.v}</div>
              <div className="mono" style={{ fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ink-4)', marginTop: 2 }}>{s.k}</div>
            </div>
          ))}
        </div>
      </section>

      {/* Tabs */}
      <div style={{ display: 'flex', padding: `0 ${padX}px`, background: 'var(--paper)', borderBottom: '1px solid var(--rule)', overflowX: 'auto' }}>
        {[
          { id: 'matches', label: 'Live matches', count: filtered.length },
          { id: 'mandates', label: 'My mandates', count: 3 },
          { id: 'how', label: 'How matching works' },
        ].map(t => (
          <button key={t.id} onClick={() => setTab(t.id)} style={{
            padding: '14px 0', marginRight: 28, fontSize: 13,
            color: tab === t.id ? 'var(--ink)' : 'var(--ink-4)',
            borderBottom: `2px solid ${tab === t.id ? 'var(--ink)' : 'transparent'}`,
            display: 'flex', gap: 8, alignItems: 'center', whiteSpace: 'nowrap',
          }}>
            {t.label}
            {t.count !== undefined && <span className="mono" style={{ fontSize: 10, letterSpacing: '0.08em', color: 'var(--ink-5)' }}>{t.count}</span>}
          </button>
        ))}
      </div>

      {tab === 'matches' && (
        <section style={{ padding: isMobile ? '20px 16px 40px' : `28px ${padX}px 60px` }}>
          {/* Filter row */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 20, flexWrap: 'wrap' }}>
            <Icon.Filter size={14} />
            <span className="mono" style={{ fontSize: 10, letterSpacing: '0.12em', textTransform: 'uppercase', color: 'var(--ink-4)', marginRight: 4 }}>Intent:</span>
            {[{id:'all',l:'All'},{id:'actively',l:'Active'},{id:'soon',l:'6–12mo'},{id:'later',l:'1–2yr'},{id:'curious',l:'Curious'}].map(f => (
              <button key={f.id} onClick={() => setFilter(f.id)} style={{
                fontSize: 12, padding: '6px 12px', borderRadius: 999,
                background: filter === f.id ? 'var(--ink)' : 'transparent',
                color: filter === f.id ? 'var(--paper)' : 'var(--ink-3)',
                border: '1px solid', borderColor: filter === f.id ? 'var(--ink)' : 'var(--rule)',
              }}>{f.l}</button>
            ))}
            <div style={{ flex: 1 }} />
            <span className="mono" style={{ fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--ink-5)' }}>{filtered.length} matches · sorted by score</span>
          </div>

          {/* Match cards */}
          <div style={{ display: 'grid', gap: 8 }}>
            {filtered.map((s) => {
              const expressed = interestedIds.includes(s.id);
              return (
                <div key={s.id} className="card-elev" style={{
                  borderRadius: 2, padding: isMobile ? 16 : 20, background: '#fff',
                  display: 'grid',
                  gridTemplateColumns: isMobile ? '1fr' : isTablet ? '1fr auto' : 'minmax(0, 1fr) 200px 170px',
                  gap: isMobile ? 12 : 20, alignItems: 'center',
                }}>
                  {/* Left: score + identity */}
                  <div style={{ display: 'flex', alignItems: 'center', gap: 14, minWidth: 0 }}>
                    <div style={{
                      width: 56, height: 56, borderRadius: 2,
                      background: s.score >= 90 ? 'var(--emerald)' : s.score >= 80 ? 'var(--ink)' : '#efece4',
                      color: s.score >= 80 ? 'var(--paper)' : 'var(--ink)',
                      display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
                      flexShrink: 0,
                    }}>
                      <div className="serif tnum" style={{ fontSize: 22, fontWeight: 400, lineHeight: 1, letterSpacing: '-0.02em' }}>{s.score}</div>
                      <div className="mono" style={{ fontSize: 7, letterSpacing: '0.14em', opacity: 0.7, marginTop: 2 }}>FIT</div>
                    </div>
                    <div style={{ minWidth: 0, flex: 1 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4, flexWrap: 'wrap' }}>
                        <span className="mono" style={{ fontSize: 11, letterSpacing: '0.1em', color: 'var(--ink)', whiteSpace: 'nowrap' }}>SELLER {s.id}</span>
                        {s.isNew && <span className="mono" style={{ fontSize: 9, padding: '2px 6px', background: accent, color: 'var(--paper)', letterSpacing: '0.14em', borderRadius: 1 }}>NEW</span>}
                      </div>
                      <div className="serif" style={{ fontSize: 17, fontWeight: 400, letterSpacing: '-0.01em' }}>{s.industry}</div>
                      <div style={{ fontSize: 12, color: 'var(--ink-4)', marginTop: 2 }}>
                        {s.state} <Icon.Dot /> {s.years} owned <Icon.Dot /> {s.rev} rev / {s.ebitda} EBITDA
                      </div>
                    </div>
                  </div>

                  {/* Middle: intent + transition + rep */}
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 6, alignItems: isMobile ? 'flex-start' : isTablet ? 'flex-end' : 'flex-start', minWidth: 0 }}>
                    <div style={{ whiteSpace: 'nowrap' }}><IntentBadge kind={s.intent} /></div>
                    <div style={{ fontSize: 11, color: 'var(--ink-4)', whiteSpace: 'nowrap' }}>Transition: {s.transition}</div>
                    <div className="mono" style={{ fontSize: 10, letterSpacing: '0.08em', color: 'var(--ink-5)', whiteSpace: 'nowrap' }}>Advisor: {s.rep}</div>
                  </div>

                  {/* Right: CTA */}
                  {!isTablet && (
                    <div style={{ display: 'flex', gap: 6, alignSelf: 'center', justifyContent: 'flex-end' }}>
                      {expressed ? (
                        <button className="btn" style={{ fontSize: 12, padding: '10px 14px', background: 'var(--emerald-soft)', color: 'var(--emerald)', border: '1px solid rgba(31,95,74,0.2)', whiteSpace: 'nowrap' }}>
                          <Icon.Check size={12} /> Interest expressed
                        </button>
                      ) : (
                        <button className="btn btn-primary" style={{ fontSize: 12, padding: '10px 14px', whiteSpace: 'nowrap' }} onClick={() => setInterestedIds([...interestedIds, s.id])}>
                          Express interest
                        </button>
                      )}
                    </div>
                  )}
                  {/* Tablet/mobile CTA full width */}
                  {(isMobile || isTablet) && (
                    <div style={{ gridColumn: isTablet ? '1 / -1' : 'auto', display: 'flex', justifyContent: 'flex-end' }}>
                      {expressed ? (
                        <button className="btn" style={{ fontSize: 12, padding: '10px 14px', background: 'var(--emerald-soft)', color: 'var(--emerald)', border: '1px solid rgba(31,95,74,0.2)', whiteSpace: 'nowrap' }}>
                          <Icon.Check size={12} /> Interest expressed
                        </button>
                      ) : (
                        <button className="btn btn-primary" style={{ fontSize: 12, padding: '10px 14px', whiteSpace: 'nowrap' }} onClick={() => setInterestedIds([...interestedIds, s.id])}>
                          Express interest
                        </button>
                      )}
                    </div>
                  )}
                </div>
              );
            })}
          </div>
        </section>
      )}

      {tab === 'mandates' && (
        <section style={{ padding: isMobile ? '20px 16px 40px' : `28px ${padX}px 60px`, display: 'grid', gap: 16 }}>
          {[
            { name: 'Industrials platform · Sun Belt', industries: 'HVAC, Manufacturing, Construction', size: '$15M–$50M rev · $3M–$10M EBITDA', geo: '12 states', status: 'active', perf: '47 matches · 8 conversations' },
            { name: 'IT Services tuck-in', industries: 'IT Services / MSP', size: '$10M–$25M rev · $2M–$6M EBITDA', geo: 'Nationwide', status: 'active', perf: '23 matches · 3 conversations' },
            { name: 'Healthcare services platform', industries: 'Healthcare Services', size: '$20M–$60M rev', geo: '8 states', status: 'paused', perf: '11 matches · 1 under LOI' },
          ].map((m, i) => (
            <div key={i} className="card-elev" style={{ padding: 20, background: '#fff' }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', flexWrap: 'wrap', gap: 12 }}>
                <div>
                  <div style={{ display: 'flex', gap: 10, alignItems: 'center', marginBottom: 6 }}>
                    <h3 className="serif" style={{ fontSize: 19, fontWeight: 450, letterSpacing: '-0.015em', margin: 0 }}>{m.name}</h3>
                    <span className="mono" style={{ fontSize: 9, letterSpacing: '0.14em', textTransform: 'uppercase', padding: '2px 8px', borderRadius: 999, background: m.status === 'active' ? 'rgba(31,95,74,0.1)' : 'rgba(168,106,42,0.1)', color: m.status === 'active' ? 'var(--emerald)' : 'var(--intent-orange)' }}>{m.status}</span>
                  </div>
                  <div style={{ fontSize: 13, color: 'var(--ink-3)' }}>{m.industries} <Icon.Dot /> {m.size} <Icon.Dot /> {m.geo}</div>
                </div>
                <div style={{ display: 'flex', gap: 8 }}>
                  <button className="btn btn-ghost" style={{ fontSize: 12, padding: '6px 10px' }}>Pause</button>
                  <button className="btn btn-secondary" style={{ fontSize: 12, padding: '8px 12px' }}>Edit</button>
                </div>
              </div>
              <div className="rule" style={{ margin: '14px 0' }} />
              <div className="mono" style={{ fontSize: 10, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--ink-4)' }}>{m.perf}</div>
            </div>
          ))}
        </section>
      )}

      {tab === 'how' && (
        <section style={{ padding: isMobile ? '32px 16px 60px' : `48px ${padX}px 80px`, maxWidth: 880 }}>
          <h2 className="serif" style={{ fontSize: isMobile ? 28 : 36, fontWeight: 350, letterSpacing: '-0.025em', margin: '0 0 32px' }}>
            How matching works.
          </h2>
          <div style={{ display: 'grid', gap: 24 }}>
            {[
              { n: '01', t: 'Sellers complete an 8-question match flow', b: 'Industry, size, location, owner-transition preference, and crucially — intent. Sellers stay anonymous; we only see what they tell us.' },
              { n: '02', t: 'We compute fit against every active mandate', b: 'Industry & adjacency · EBITDA fit · Geography · Transition compatibility · Intent boost. Score is 0–100, sorted on your dashboard.' },
              { n: '03', t: 'You express interest', b: 'A partner advisor reaches out to the seller on your behalf. They surface mutual interest before any identifying information is exchanged.' },
              { n: '04', t: 'A licensed advisor facilitates the introduction', b: 'NDA → IOI → LOI → diligence → close. Buyside is never the broker. A vetted sell-side advisory partner holds all licensure and runs the process.' },
            ].map((s) => (
              <div key={s.n} style={{ display: 'flex', gap: 24, paddingBottom: 24, borderBottom: '1px solid var(--rule)' }}>
                <div className="mono" style={{ fontSize: 11, letterSpacing: '0.16em', color: accent, flexShrink: 0, paddingTop: 6 }}>{s.n}</div>
                <div>
                  <h3 className="serif" style={{ fontSize: 22, fontWeight: 400, letterSpacing: '-0.015em', margin: 0 }}>{s.t}</h3>
                  <p style={{ fontSize: 14, lineHeight: 1.6, color: 'var(--ink-3)', margin: '8px 0 0' }}>{s.b}</p>
                </div>
              </div>
            ))}
          </div>
        </section>
      )}
    </div>
  );
};

// ═══════════════════════════════════════════════════════════
// BUYER SIGN IN
// ═══════════════════════════════════════════════════════════
const BuyerSignIn = ({ bp, navigate, accent }) => {
  const isMobile = bp === 'mobile';
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [method, setMethod] = useState('password'); // 'password' | 'magic'
  const [magicSent, setMagicSent] = useState(false);

  return (
    <div className="viewport-scroll" style={{ background: 'var(--paper)', minHeight: '100%', display: 'flex', flexDirection: 'column' }}>
      {/* Header */}
      <div style={{
        display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        padding: isMobile ? '20px 24px' : '24px 80px',
        borderBottom: '1px solid var(--rule-2)',
      }}>
        <Wordmark size={isMobile ? 20 : 22} capex={!isMobile} />
        <button className="btn btn-ghost" onClick={() => navigate('buyer-landing')} style={{ fontSize: 13 }}>
          <Icon.ArrowLeft size={12} /> Back
        </button>
      </div>

      {/* Sign in card */}
      <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', padding: isMobile ? '40px 24px' : '64px 24px' }}>
        <div style={{ width: '100%', maxWidth: 400 }}>
          <div style={{ textAlign: 'center', marginBottom: 36 }}>
            <h1 className="serif" style={{ fontSize: isMobile ? 26 : 30, fontWeight: 400, letterSpacing: '-0.02em', margin: '0 0 8px' }}>
              Sign in
            </h1>
            <p style={{ fontSize: 14, color: 'var(--ink-4)', margin: 0 }}>
              Access your buyer dashboard and live matches.
            </p>
          </div>

          {/* Method toggle */}
          <div style={{ display: 'flex', marginBottom: 24, border: '1px solid var(--rule)', borderRadius: 'var(--radius)' }}>
            <button
              onClick={() => { setMethod('password'); setMagicSent(false); }}
              style={{
                flex: 1, padding: '10px 0', fontSize: 13, fontWeight: 500, textAlign: 'center',
                background: method === 'password' ? 'var(--ink)' : 'transparent',
                color: method === 'password' ? 'var(--paper)' : 'var(--ink-3)',
                border: 'none', cursor: 'pointer',
              }}
            >
              Password
            </button>
            <button
              onClick={() => setMethod('magic')}
              style={{
                flex: 1, padding: '10px 0', fontSize: 13, fontWeight: 500, textAlign: 'center',
                background: method === 'magic' ? 'var(--ink)' : 'transparent',
                color: method === 'magic' ? 'var(--paper)' : 'var(--ink-3)',
                border: 'none', cursor: 'pointer',
              }}
            >
              Magic link
            </button>
          </div>

          {/* Email field */}
          <div style={{ marginBottom: 16 }}>
            <label className="field-label">Email</label>
            <input
              className="field-input"
              type="email"
              placeholder="partner@firm.com"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              style={{ width: '100%' }}
            />
          </div>

          {/* Password field (only in password mode) */}
          {method === 'password' && (
            <div style={{ marginBottom: 8 }}>
              <label className="field-label">Password</label>
              <div style={{ position: 'relative' }}>
                <input
                  className="field-input"
                  type={showPassword ? 'text' : 'password'}
                  placeholder="••••••••••"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  style={{ width: '100%', paddingRight: 44 }}
                />
                <button
                  onClick={() => setShowPassword(!showPassword)}
                  style={{
                    position: 'absolute', right: 12, top: '50%', transform: 'translateY(-50%)',
                    background: 'none', border: 'none', cursor: 'pointer',
                    fontSize: 12, color: 'var(--ink-4)', fontFamily: 'var(--mono)',
                  }}
                >
                  {showPassword ? 'hide' : 'show'}
                </button>
              </div>
              <div style={{ textAlign: 'right', marginTop: 8 }}>
                <a href="#" onClick={(e) => e.preventDefault()} style={{ fontSize: 12, color: 'var(--ink-4)' }}>
                  Forgot password?
                </a>
              </div>
            </div>
          )}

          {/* Magic link sent confirmation */}
          {method === 'magic' && magicSent && (
            <div style={{
              padding: '16px 20px', marginBottom: 16,
              background: 'var(--emerald-soft)', border: '1px solid var(--emerald)',
              fontSize: 13, color: 'var(--emerald-2)', lineHeight: 1.5,
            }}>
              <strong>Check your inbox.</strong> We sent a sign-in link to {email || 'your email'}. It expires in 10 minutes.
            </div>
          )}

          {/* Submit */}
          <button
            className="btn btn-primary"
            onClick={() => {
              if (method === 'magic') {
                setMagicSent(true);
              } else {
                navigate('buyer-dashboard');
              }
            }}
            style={{
              width: '100%', padding: '14px 0', fontSize: 15, marginTop: 16,
              opacity: email ? 1 : 0.5, pointerEvents: email ? 'auto' : 'none',
            }}
          >
            {method === 'magic' ? (magicSent ? 'Resend link' : 'Send magic link') : 'Sign in'}
          </button>

          {/* Divider */}
          <div style={{ display: 'flex', alignItems: 'center', gap: 16, margin: '28px 0' }}>
            <div style={{ flex: 1, height: 1, background: 'var(--rule)' }} />
            <span style={{ fontSize: 11, color: 'var(--ink-5)', fontFamily: 'var(--mono)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>New to Buyside?</span>
            <div style={{ flex: 1, height: 1, background: 'var(--rule)' }} />
          </div>

          <button
            className="btn"
            onClick={() => navigate('buyer-mandate')}
            style={{
              width: '100%', padding: '13px 0', fontSize: 14,
              border: '1px solid var(--ink)', color: 'var(--ink)',
            }}
          >
            Submit a mandate to get started
          </button>

          {/* Trust note */}
          <div style={{ textAlign: 'center', marginTop: 32, fontSize: 11, color: 'var(--ink-5)', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 6 }}>
            <Icon.Lock size={11} /> Encrypted connection · SOC 2 compliant
          </div>
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { BuyerLanding, BuyerMandate, BuyerDashboard, BuyerSignIn });
