/* global React */
const { useState, useEffect, useRef, useMemo, useLayoutEffect } = React;

// ───────────────────────── Icons ─────────────────────────
const Icon = {
  Lock: ({ size = 14 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
      <rect x="5" y="11" width="14" height="10" rx="1.5" />
      <path d="M8 11V8a4 4 0 0 1 8 0v3" />
    </svg>
  ),
  Arrow: ({ size = 14 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
      <path d="M5 12h14M13 6l6 6-6 6" />
    </svg>
  ),
  ArrowLeft: ({ size = 14 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
      <path d="M19 12H5M11 6l-6 6 6 6" />
    </svg>
  ),
  Check: ({ size = 14 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
      <path d="M5 12l5 5L20 7" />
    </svg>
  ),
  Plus: ({ size = 14 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
      <path d="M12 5v14M5 12h14" />
    </svg>
  ),
  Calendar: ({ size = 16 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
      <rect x="3" y="5" width="18" height="16" rx="1.5" />
      <path d="M3 10h18M8 3v4M16 3v4" />
    </svg>
  ),
  Menu: ({ size = 18 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
      <path d="M4 7h16M4 12h16M4 17h16" />
    </svg>
  ),
  Close: ({ size = 18 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
      <path d="M6 6l12 12M18 6L6 18" />
    </svg>
  ),
  Upload: ({ size = 14 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
      <path d="M12 16V4M7 9l5-5 5 5M5 20h14" />
    </svg>
  ),
  Caret: ({ size = 9, open = false }) => (
    <svg width={size} height={size} viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="1.5" style={{ transition: 'transform 0.18s ease', transform: open ? 'rotate(180deg)' : 'rotate(0)' }}>
      <path d="M3 5l3 3 3-3" />
    </svg>
  ),
  ExtLink: ({ size = 12 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
      <path d="M14 4h6v6M20 4l-9 9M18 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h5" />
    </svg>
  ),
  Dot: () => <span style={{display:'inline-block',width:3,height:3,borderRadius:'50%',background:'currentColor',margin:'0 8px',verticalAlign:'3px',opacity:0.5}} />,
  Search: ({ size = 14 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
      <circle cx="11" cy="11" r="6" /><path d="M20 20l-4-4" />
    </svg>
  ),
  Filter: ({ size = 14 }) => (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
      <path d="M4 6h16M7 12h10M10 18h4" />
    </svg>
  ),
};

// ───────────────────────── Wordmark ─────────────────────────
const Wordmark = ({ size = 22, color, capex = false }) => (
  <span className="serif" style={{
    fontSize: size, fontWeight: 400, letterSpacing: '-0.025em',
    color: color || 'currentColor', display: 'inline-flex', alignItems: 'baseline', gap: 0,
  }}>
    <span>Buy</span>
    <span style={{ fontStyle: 'italic', fontWeight: 300, opacity: 0.85 }}>side</span>
    {capex && <span className="mono" style={{ fontSize: size*0.32, marginLeft: 10, letterSpacing: '0.16em', textTransform: 'uppercase', opacity: 0.5 }}>FOR BUYERS</span>}
  </span>
);

// ───────────────────────── Eyebrow / Section header ─────────────────────────
const Eyebrow = ({ children, dot = true, color }) => (
  <div className="eyebrow" style={{ color: color || 'var(--ink-4)' }}>
    {dot && <span className="dot" />}{children}
  </div>
);

// ───────────────────────── Lock pill ─────────────────────────
const LockPill = ({ children = "100% confidential — no listing, no public exposure" }) => (
  <span className="lock-pill">
    <Icon.Lock size={12} />
    <span>{children}</span>
  </span>
);

// ───────────────────────── Mobile status bar ─────────────────────────
const MobileStatusBar = () => (
  <div className="mobile-statusbar">
    <span>9:41</span>
    <div style={{display:'flex',gap:6,alignItems:'center'}}>
      <svg width="16" height="10" viewBox="0 0 16 10" fill="currentColor"><rect x="0" y="6" width="3" height="4" rx="0.5"/><rect x="4" y="4" width="3" height="6" rx="0.5"/><rect x="8" y="2" width="3" height="8" rx="0.5"/><rect x="12" y="0" width="3" height="10" rx="0.5"/></svg>
      <svg width="14" height="10" viewBox="0 0 14 10" fill="none" stroke="currentColor" strokeWidth="1"><path d="M1 4 Q7 -2 13 4 M3 6 Q7 2 11 6 M5.5 8 Q7 6.5 8.5 8" strokeLinecap="round"/></svg>
      <svg width="22" height="10" viewBox="0 0 22 10"><rect x="0" y="0" width="18" height="10" rx="2" fill="none" stroke="currentColor"/><rect x="2" y="2" width="14" height="6" rx="1" fill="currentColor"/><rect x="19" y="3" width="2" height="4" rx="1" fill="currentColor" opacity="0.6"/></svg>
    </div>
  </div>
);

// ───────────────────────── Intent badge ─────────────────────────
const INTENT_META = {
  actively:  { cls: 'intent-actively', label: 'Actively exploring' },
  soon:      { cls: 'intent-soon',     label: 'Planning 6–12 mo' },
  later:     { cls: 'intent-later',    label: 'Planning 1–2 yr' },
  curious:   { cls: 'intent-curious',  label: 'Just curious' },
};
const IntentBadge = ({ kind = 'curious' }) => {
  const m = INTENT_META[kind] || INTENT_META.curious;
  return <span className={`intent-badge ${m.cls}`}><span className="pulse" />{m.label}</span>;
};

// ───────────────────────── Lock tile (anonymous buyer card icon) ─────────────────────────
const LockTile = ({ initials, size = 40 }) => (
  <div className="lock-tile" style={{ width: size, height: size }}>
    {initials ? (
      <span className="serif" style={{ fontSize: size*0.34, color: 'var(--ink)', fontStyle: 'italic' }}>{initials}</span>
    ) : (
      <Icon.Lock size={size*0.42} />
    )}
  </div>
);

// ───────────────────────── Trust strip ─────────────────────────
const TrustStrip = ({ inverse = false }) => (
  <div style={{
    display: 'flex', flexWrap: 'wrap', gap: 28, alignItems: 'center',
    fontFamily: 'var(--mono)', fontSize: 11, letterSpacing: '0.08em',
    textTransform: 'uppercase', color: inverse ? 'rgba(245,243,238,0.6)' : 'var(--ink-4)',
  }}>
    <span><span style={{color: inverse ? 'var(--paper)' : 'var(--ink)'}}>2,400+</span> owners matched</span>
    <span style={{opacity:0.4}}>·</span>
    <span><span style={{color: inverse ? 'var(--paper)' : 'var(--ink)'}}>$4.2B</span> in active buyer mandates</span>
    <span style={{opacity:0.4}}>·</span>
    <span>SOC 2 compliant</span>
  </div>
);

// ───────────────────────── Footer ─────────────────────────
const Footer = ({ variant = 'seller', navigate }) => (
  <div style={{
    padding: 'clamp(40px, 6vw, 64px) clamp(24px, 6vw, 80px) 40px',
    borderTop: '1px solid var(--rule)',
    background: 'var(--paper)',
    color: 'var(--ink-3)',
  }}>
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-end', flexWrap: 'wrap', gap: 24 }}>
      <div>
        <Wordmark size={20} />
        <div style={{ fontSize: 12, marginTop: 8, color: 'var(--ink-4)', maxWidth: 320 }}>
          A confidential matching service.
          {variant === 'seller' ? ' A confidential alternative to listing your business.' : ' For verified institutional buyers.'}
        </div>
      </div>
      <div style={{ display: 'flex', gap: 28, fontSize: 12, flexWrap: 'wrap' }}>
        <a href="#" onClick={(e) => { e.preventDefault(); navigate && navigate('about-story'); }}>Our Story</a>
        <a href="#" onClick={(e) => { e.preventDefault(); navigate && navigate('about-team'); }}>Team</a>
        <a href="#" onClick={(e) => { e.preventDefault(); navigate && navigate('about-contact'); }}>Contact</a>
        {variant === 'seller' && <a href="#" onClick={(e) => { e.preventDefault(); navigate && navigate('data-handling'); }}>What happens next</a>}
        {variant === 'buyer' && <a href="#" onClick={(e) => { e.preventDefault(); navigate && navigate('verification'); }}>Verification standards</a>}
        <a href="#" onClick={(e) => { e.preventDefault(); navigate && navigate('privacy'); }}>Privacy</a>
        <a href="#" onClick={(e) => { e.preventDefault(); navigate && navigate('terms'); }}>Terms</a>
      </div>
    </div>
    <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 32, paddingTop: 20, borderTop: '1px solid var(--rule)', fontSize: 10, fontFamily: 'var(--mono)', letterSpacing: '0.1em', textTransform: 'uppercase', color: 'var(--ink-5)', flexWrap: 'wrap', gap: 12 }}>
      <span>© 2025 Buyside, Inc.</span>
      <span>SOC 2 Type II · CCPA · GDPR</span>
    </div>
  </div>
);

// ───────────────────────── NavMenu (dropdown) ─────────────────────────
const NavMenu = ({ items, navigate, onPick }) => (
  <div style={{
    position: 'absolute', top: 'calc(100% + 14px)', left: -16, minWidth: 280,
    background: 'var(--paper)', border: '1px solid var(--ink)',
    boxShadow: '0 18px 48px -14px rgba(20,20,18,0.22), 0 4px 14px -4px rgba(20,20,18,0.10)',
    zIndex: 50, padding: 6,
  }}>
    {/* little tick mark up top */}
    <div style={{ position: 'absolute', top: -7, left: 28, width: 12, height: 12, background: 'var(--paper)', borderTop: '1px solid var(--ink)', borderLeft: '1px solid var(--ink)', transform: 'rotate(45deg)' }} />
    {items.map((it, i) => (
      <button
        key={i}
        onClick={() => { navigate(it.id); onPick && onPick(); }}
        style={{
          display: 'block', width: '100%', textAlign: 'left',
          padding: '12px 14px', background: 'none', border: 'none', cursor: 'pointer',
          fontFamily: 'inherit', borderBottom: i < items.length - 1 ? '1px solid var(--rule)' : 'none',
        }}
        onMouseEnter={(e) => { e.currentTarget.style.background = '#efece4'; }}
        onMouseLeave={(e) => { e.currentTarget.style.background = 'transparent'; }}
      >
        <div className="serif" style={{ fontSize: 15, fontWeight: 450, letterSpacing: '-0.012em', color: 'var(--ink)' }}>{it.label}</div>
        {it.sub && <div style={{ fontSize: 11, color: 'var(--ink-4)', marginTop: 3 }}>{it.sub}</div>}
      </button>
    ))}
  </div>
);

// ───────────────────────── Mobile Nav Drawer ─────────────────────────
const MobileNavDrawer = ({ open, onClose, navigate, currentScreen }) => {
  if (!open) return null;
  const go = (id) => { navigate(id); onClose(); };
  return (
    <div onClick={onClose} style={{ position: 'absolute', inset: 0, background: 'rgba(20,20,17,0.4)', zIndex: 100, animation: 'fadeIn 200ms ease' }}>
      <div onClick={(e) => e.stopPropagation()} style={{ position: 'absolute', top: 0, right: 0, bottom: 0, width: 'min(86vw, 340px)', background: 'var(--paper)', boxShadow: '-10px 0 40px rgba(0,0,0,0.15)', display: 'flex', flexDirection: 'column', overflow: 'auto', animation: 'slideInRight 280ms cubic-bezier(0.2,0.8,0.2,1)' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '20px 24px', borderBottom: '1px solid var(--rule)' }}>
          <Wordmark size={20} />
          <button onClick={onClose} aria-label="Close" style={{ background: 'none', border: 'none', cursor: 'pointer', padding: 8, display: 'flex' }}>
            <Icon.Close size={16} />
          </button>
        </div>
        <nav style={{ padding: '8px 0', flex: 1 }}>
          {[{id:'seller-landing',label:'Home'},{id:'who-buys',label:'Who buys'}].map(it => (
            <button key={it.id} onClick={() => go(it.id)} style={{ display: 'block', width: '100%', textAlign: 'left', padding: '14px 24px', fontSize: 16, fontFamily: 'var(--serif)', fontWeight: currentScreen === it.id ? 500 : 400, color: 'var(--ink)', background: currentScreen === it.id ? '#efece4' : 'none', border: 'none', cursor: 'pointer', borderBottom: '1px solid var(--rule)' }}>{it.label}</button>
          ))}
          <div className="mono" style={{ fontSize: 10, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--ink-5)', padding: '20px 24px 8px' }}>Insights</div>
          {[{id:'insights-reports',label:'Market Reports'},{id:'insights-multiples',label:'Industry Multiples'},{id:'insights-cases',label:'Case Studies'},{id:'insights-glossary',label:'Glossary'}].map(it => (
            <button key={it.id} onClick={() => go(it.id)} style={{ display: 'block', width: '100%', textAlign: 'left', padding: '12px 24px', fontSize: 14, color: 'var(--ink-2)', fontWeight: currentScreen === it.id ? 500 : 400, background: currentScreen === it.id ? '#efece4' : 'none', border: 'none', cursor: 'pointer' }}>{it.label}</button>
          ))}
          <div className="mono" style={{ fontSize: 10, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--ink-5)', padding: '20px 24px 8px', borderTop: '1px solid var(--rule)', marginTop: 8 }}>About</div>
          {[{id:'about-story',label:'Our Story'},{id:'about-team',label:'Team'},{id:'about-contact',label:'Contact'}].map(it => (
            <button key={it.id} onClick={() => go(it.id)} style={{ display: 'block', width: '100%', textAlign: 'left', padding: '12px 24px', fontSize: 14, color: 'var(--ink-2)', fontWeight: currentScreen === it.id ? 500 : 400, background: currentScreen === it.id ? '#efece4' : 'none', border: 'none', cursor: 'pointer' }}>{it.label}</button>
          ))}
          <div style={{ borderTop: '1px solid var(--rule)', marginTop: 16, padding: '16px 24px' }}>
            <button onClick={() => go('buyer-landing')} style={{ display: 'block', width: '100%', textAlign: 'left', padding: '8px 0', fontSize: 13, color: 'var(--ink-4)', background: 'none', border: 'none', cursor: 'pointer' }}>For buyers →</button>
          </div>
        </nav>
        <div style={{ padding: 24, borderTop: '1px solid var(--rule)', background: '#efece4' }}>
          <button className="btn btn-primary btn-arrow" style={{ width: '100%', padding: '14px', fontSize: 14, justifyContent: 'center' }} onClick={() => go('seller-wizard')}>See your matches</button>
          <p style={{ fontSize: 11, color: 'var(--ink-5)', textAlign: 'center', margin: '10px 0 0' }}>Takes about 90 seconds</p>
        </div>
      </div>
    </div>
  );
};

// Hamburger button — used in any compact header on mobile
const MobileHamburger = ({ onClick }) => (
  <button onClick={onClick} aria-label="Open menu" style={{ background: 'none', border: '1px solid var(--rule-2)', borderRadius: 2, width: 36, height: 36, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column', gap: 4, padding: 0 }}>
    <span style={{ width: 16, height: 1, background: 'var(--ink)' }} />
    <span style={{ width: 16, height: 1, background: 'var(--ink)' }} />
    <span style={{ width: 16, height: 1, background: 'var(--ink)' }} />
  </button>
);

// ───────────────────────── Phone formatter ─────────────────────────
const formatPhone = (value) => {
  const digits = value.replace(/\D/g, '').slice(0, 10);
  if (digits.length <= 3) return digits;
  if (digits.length <= 6) return `(${digits.slice(0, 3)}) ${digits.slice(3)}`;
  return `(${digits.slice(0, 3)}) ${digits.slice(3, 6)}-${digits.slice(6)}`;
};

// ───────────────────────── Submit + Generate ─────────────────────────
const submitAndGenerate = async (answers) => {
  const payload = {
    industry: answers.industry,
    revenue: answers.revenue,
    ebitda: answers.ebitda,
    years_owned: answers.years_owned,
    state: answers.state,
    transition: answers.transition,
    intent: answers.intent,
    email: answers.email,
    phone: answers.phone || '',
  };

  // Fire both requests in parallel
  const [submitRes, generateRes] = await Promise.all([
    fetch('/api/submit', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
    }),
    fetch('/api/generate-results', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
    }),
  ]);

  if (!generateRes.ok) throw new Error('Failed to generate results');
  const results = await generateRes.json();
  return results;
};

// Export to window
Object.assign(window, {
  Icon, Wordmark, Eyebrow, LockPill, MobileStatusBar,
  IntentBadge, INTENT_META, LockTile, TrustStrip, Footer, NavMenu,
  MobileNavDrawer, MobileHamburger, formatPhone, submitAndGenerate,
});
