// live-shared.jsx — Shared brand system + components for the Live Video Inspection A/B/C test.
// Logo-only header (NO site nav), sticky CTA, the live-call hero mock, trust block, FAQ,
// testimonials, how-it-works, price/risk-reversal, photo slots, and tracking hooks.

const { useState, useEffect, useRef } = React;

// ===== BRAND TOKENS (Lemon Squad) =====
const LV = {
  red: '#E63B2E', redDark: '#C42E22', redBg: '#FEF2F2', redBorder: '#FBD5D0',
  yellow: '#F5A623', yellowBg: '#FFF8EB', yellowText: '#92400E', yellowBorder: '#FCE4B6',
  ink: '#16202E', charcoal: '#1A202C', navy: '#222C3C', navyDeep: '#141B26',
  green: '#0F9D58', greenBg: '#ECFDF3', greenBorder: '#B7E4C7',
  g50: '#F8FAFB', g100: '#F1F4F7', g200: '#E4E9EF', g300: '#D2DAE3',
  g400: '#9AA6B4', g500: '#697686', g600: '#4D5969', g700: '#3A4453',
  white: '#FFFFFF'
};
const FONT = "'Plus Jakarta Sans', system-ui, -apple-system, sans-serif";
const MAXW = 480; // mobile-first column
const MAXW_D = 1120; // desktop content cap

// Responsive hook: true when viewport is desktop-wide.
function useIsWide(bp = 920) {
  const force = typeof window !== 'undefined' && /[?&]forcewide/.test(window.location.search);
  const [wide, setWide] = useState(force || (typeof window !== 'undefined' && window.innerWidth >= bp));
  useEffect(() => {
    if (force) { setWide(true); return; }
    const f = () => setWide(window.innerWidth >= bp);
    f();
    window.addEventListener('resize', f);
    return () => window.removeEventListener('resize', f);
  }, [bp, force]);
  return wide;
}

const phoneNumber = '(888) 231-7965';

// ===== ICONS (simple stroke paths only) =====
function Icon({ d, size = 20, color = 'currentColor', sw = 2, fill = 'none', style }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill={fill} stroke={color}
    strokeWidth={sw} strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0, ...style }}>
      {Array.isArray(d) ? d.map((p, i) => <path key={i} d={p} />) : <path d={d} />}
    </svg>);

}
const ICON = {
  check: 'M20 6L9 17l-5-5',
  shield: 'M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z',
  shieldCheck: ['M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z', 'M9 12l2 2 4-4'],
  video: ['M23 7l-7 5 7 5V7z', 'M14 5H3a2 2 0 00-2 2v10a2 2 0 002 2h11a2 2 0 002-2V7a2 2 0 00-2-2z'],
  phone: 'M22 16.92v3a2 2 0 01-2.18 2 19.79 19.79 0 01-8.63-3.07 19.5 19.5 0 01-6-6 19.79 19.79 0 01-3.07-8.67A2 2 0 014.11 2h3a2 2 0 012 1.72c.13.96.36 1.9.7 2.81a2 2 0 01-.45 2.11L8.09 9.91a16 16 0 006 6l1.27-1.27a2 2 0 012.11-.45c.91.34 1.85.57 2.81.7A2 2 0 0122 16.92z',
  car: ['M5 17h14M6 17l-1.5-4.5A2 2 0 016.4 10h11.2a2 2 0 011.9 1.5L21 17', 'M7 17v2M17 17v2'],
  user: ['M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2', 'M12 3a4 4 0 100 8 4 4 0 000-8z'],
  clock: ['M12 22a10 10 0 100-20 10 10 0 000 20z', 'M12 7v5l3 2'],
  arrow: 'M5 12h14M13 6l6 6-6 6',
  chevron: 'M9 18l6-6-6-6',
  chevronDown: 'M6 9l6 6 6-6',
  star: 'M12 2l3 6.5 7 .9-5 4.8 1.2 7-6.4-3.4L5.6 21l1.2-7-5-4.8 7-.9L12 2z',
  spark: 'M12 2l2.4 7.2L22 12l-7.6 2.8L12 22l-2.4-7.2L2 12l7.6-2.8L12 2z',
  mic: ['M12 1a3 3 0 00-3 3v8a3 3 0 006 0V4a3 3 0 00-3-3z', 'M19 10v2a7 7 0 01-14 0v-2M12 19v4'],
  send: ['M22 2L11 13', 'M22 2l-7 20-4-9-9-4 20-7z'],
  map: ['M21 10c0 7-9 13-9 13s-9-6-9-13a9 9 0 0118 0z', 'M12 13a3 3 0 100-6 3 3 0 000 6z'],
  eye: ['M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7z', 'M12 15a3 3 0 100-6 3 3 0 000 6z'],
  award: ['M12 15a7 7 0 100-14 7 7 0 000 14z', 'M8.2 13.9L7 22l5-3 5 3-1.2-8.1'],
  link: ['M10 13a5 5 0 007.5.5l3-3a5 5 0 00-7-7l-1.7 1.7', 'M14 11a5 5 0 00-7.5-.5l-3 3a5 5 0 007 7l1.7-1.7'],
  refresh: ['M23 4v6h-6', 'M1 20v-6h6', 'M3.5 9a9 9 0 0114.9-3.4L23 10M1 14l4.6 4.4A9 9 0 0020.5 15'],
  wallet: ['M21 12V7H5a2 2 0 010-4h14v4', 'M3 5v14a2 2 0 002 2h16v-5', 'M18 12a2 2 0 000 4h4v-4h-4z']
};

// ===== STARS =====
function Stars({ value = 5, size = 14, gap = 1 }) {
  return (
    <div style={{ display: 'flex', gap }}>
      {[1, 2, 3, 4, 5].map((i) =>
      <Icon key={i} d={ICON.star} size={size} fill={i <= Math.round(value) ? LV.yellow : LV.g200} color={i <= Math.round(value) ? LV.yellow : LV.g200} sw={0} />
      )}
    </div>);

}

// ===== AVATAR (monogram) =====
const AV_TONES = [
['#FDE7E3', '#C42E22'], ['#FEF0D6', '#92400E'], ['#E2F1EA', '#0F7A47'],
['#E4ECF7', '#2B4C7E'], ['#EDE6F5', '#5B3E86'], ['#F6E5EC', '#9B3B63']];

function Avatar({ name = 'A B', size = 44, ring = false }) {
  const init = name.split(' ').map((w) => w[0]).slice(0, 2).join('').toUpperCase();
  const tone = AV_TONES[(name.charCodeAt(0) + (name.charCodeAt(name.length - 1) || 0)) % AV_TONES.length];
  return (
    <div style={{
      width: size, height: size, borderRadius: '50%', flexShrink: 0,
      background: tone[0], color: tone[1], display: 'flex', alignItems: 'center', justifyContent: 'center',
      fontWeight: 700, fontSize: size * 0.38, letterSpacing: '0.01em',
      border: ring ? '2px solid #fff' : 'none', boxShadow: ring ? '0 0 0 1px ' + LV.g200 : 'none'
    }}>{init}</div>);

}

// ===== PHOTO SLOT (clearly-marked, swappable placeholder) =====
function PhotoSlot({ label, ratio = '4 / 3', radius = 14, dark = false, warm = false, tag = 'PHOTO', minH, style, icon }) {
  const bg = dark ?
  'repeating-linear-gradient(135deg, #20293A 0 14px, #232E41 14px 28px)' :
  warm ?
  'linear-gradient(150deg, #F6E2D2 0%, #EFD3C0 55%, #E7C6AE 100%)' :
  'repeating-linear-gradient(135deg, #EEF2F6 0 14px, #E6ECF2 14px 28px)';
  const tagColor = dark ? 'rgba(255,255,255,0.55)' : warm ? 'rgba(120,78,52,0.7)' : LV.g400;
  const labelColor = dark ? 'rgba(255,255,255,0.7)' : warm ? '#8A5A3C' : LV.g500;
  return (
    <div style={{
      position: 'relative', width: '100%', aspectRatio: minH ? undefined : ratio, minHeight: minH,
      borderRadius: radius, overflow: 'hidden', background: bg,
      border: '1px dashed ' + (dark ? 'rgba(255,255,255,0.18)' : warm ? 'rgba(150,95,60,0.35)' : LV.g300),
      display: 'flex', alignItems: 'center', justifyContent: 'center', textAlign: 'center', padding: 16,
      ...style
    }}>
      <div>
        {icon && <div style={{ marginBottom: 8, display: 'flex', justifyContent: 'center' }}><Icon d={icon} size={26} color={labelColor} /></div>}
        <div style={{
          fontFamily: 'ui-monospace, SFMono-Regular, Menlo, monospace', fontSize: 9.5, letterSpacing: '0.12em',
          fontWeight: 700, color: tagColor, marginBottom: 4
        }}>{tag}</div>
        <div style={{ fontSize: 12, color: labelColor, lineHeight: 1.4, maxWidth: 220 }}>{label}</div>
      </div>
    </div>);

}

// ===== HEADER (logo only — NO site nav) =====
function LiveHeader({ dark = false, showPhone = true, ctaLabel, onCta, track = 'header-cta' }) {
  return (
    <header style={{
      position: 'sticky', top: 0, zIndex: 40,
      padding: '12px 20px', background: dark ? LV.navyDeep : 'rgba(255,255,255,0.92)',
      backdropFilter: 'saturate(180%) blur(8px)', WebkitBackdropFilter: 'saturate(180%) blur(8px)',
      borderBottom: '1px solid ' + (dark ? 'rgba(255,255,255,0.08)' : LV.g200)
    }}>
     <div style={{ maxWidth: 820, margin: '0 auto', width: '100%', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
      <a href="https://www.lemonsquad.com" aria-label="Lemon Squad home" data-track="header-logo">
        <img src={dark ? window.LS_LOGO_WHITE : window.LS_LOGO_COLOR} alt="Lemon Squad" style={{ height: 26, display: 'block' }} />
      </a>
      {ctaLabel ?
      <button data-track={track} onClick={onCta} style={{
        border: 'none', cursor: 'pointer', fontFamily: FONT, fontWeight: 700, fontSize: 13.5,
        padding: '9px 16px', borderRadius: 9, background: LV.red, color: '#fff'
      }}>{ctaLabel}</button> :
      showPhone ?
      <a href={`tel:${phoneNumber.replace(/[^0-9]/g, '')}`} data-track="header-call" style={{
        display: 'flex', alignItems: 'center', gap: 6, textDecoration: 'none',
        color: dark ? '#fff' : LV.charcoal, fontWeight: 700, fontSize: 13.5
      }}>
          <Icon d={ICON.phone} size={15} color={LV.red} />
          {phoneNumber}
        </a> :
      null}
     </div>
    </header>);

}

// ===== PRICE + RISK REVERSAL line =====
function PriceLine({ dark = false, align = 'center', compact = false }) {
  const sub = dark ? 'rgba(255,255,255,0.72)' : LV.g600;
  return (
    <div style={{
      display: 'flex', alignItems: 'baseline', gap: 8, justifyContent: align === 'center' ? 'center' : 'flex-start',
      flexWrap: 'wrap'
    }}>
      <span style={{ fontWeight: 800, fontSize: compact ? 22 : 26, color: dark ? '#fff' : LV.ink, letterSpacing: '-0.01em' }}>$59.99</span>
      <span style={{ fontSize: 13.5, color: sub, fontWeight: 600 }}>· You're only charged after your session</span>
    </div>);

}

// ===== TRUST CUE PILL (single, for above the fold) — no review ratings =====
function TrustPill({ dark = false }) {
  return (
    <div style={{
      display: 'inline-flex', alignItems: 'center', gap: 8, padding: '7px 14px', borderRadius: 999,
      background: dark ? 'rgba(255,255,255,0.08)' : LV.white,
      border: '1px solid ' + (dark ? 'rgba(255,255,255,0.14)' : LV.g200),
      boxShadow: dark ? 'none' : '0 1px 3px rgba(20,30,45,0.05)'
    }}>
      <Icon d={ICON.shieldCheck} size={15} color={LV.green} />
      <span style={{ fontSize: 12.5, fontWeight: 800, color: dark ? '#fff' : LV.ink, whiteSpace: 'nowrap' }}>America’s Largest &amp; Most Trusted</span>
      <span style={{ fontSize: 12, color: dark ? 'rgba(255,255,255,0.6)' : LV.g500, whiteSpace: 'nowrap' }}>· since 2005</span>
    </div>);

}

// ===== THE LIVE-CALL HERO MOCK =====
// A believable live video-inspection call. Photo content is a clearly-marked, swappable slot;
// the call chrome (LIVE badge, timer, inspector lower-third, controls) + cycling inspector
// captions sell the concept in ~3 seconds with sound off.
const CALL_CAPTIONS = [
"Okay — pop the hood and pan slowly across the engine for me.",
"See that seam? Factory paint. No accident on this corner — good sign.",
"Now show me the driver-side front tire… tread's getting low there.",
"Start it up and point at the dash — checking for warning lights.",
"No leaks underneath. This one's looking solid so far."];

function VideoCallMock({ rounded = 24, cycle = true, label = "Live: you film the car, the inspector guides you", inspector = "Marcus T." }) {
  const [cap, setCap] = useState(0);
  const [secs, setSecs] = useState(252);
  useEffect(() => {
    if (!cycle) return;
    const a = setInterval(() => setCap((c) => (c + 1) % CALL_CAPTIONS.length), 3200);
    const b = setInterval(() => setSecs((s) => s + 1), 1000);
    return () => {clearInterval(a);clearInterval(b);};
  }, [cycle]);
  const mm = String(Math.floor(secs / 60)).padStart(2, '0');
  const ss = String(secs % 60).padStart(2, '0');
  return (
    <div data-track="hero-visual" aria-label="Live video inspection demo" style={{
      position: 'relative', width: '100%', aspectRatio: '3 / 4', borderRadius: rounded, overflow: 'hidden',
      background: 'linear-gradient(160deg,#2A3647,#171F2B)', boxShadow: '0 24px 60px -24px rgba(15,23,35,0.55)',
      border: '1px solid rgba(255,255,255,0.08)'
    }}>
      {/* the "video" of the car (swappable) */}
      <div style={{ position: 'absolute', inset: 0 }}>
        <PhotoSlot dark label="Buyer's phone camera — the car being inspected" tag="LIVE VIDEO" minH="100%" radius={0} style={{ height: '100%' }} />
      </div>
      {/* moving scan highlight */}
      <div style={{
        position: 'absolute', left: '8%', right: '8%', height: 2, top: 0,
        background: 'linear-gradient(90deg,transparent,rgba(245,166,35,0.9),transparent)',
        animation: 'lvScan 3.6s ease-in-out infinite'
      }} />
      {/* top status bar */}
      <div style={{ position: 'absolute', top: 0, left: 0, right: 0, padding: '12px 13px', display: 'flex', alignItems: 'center', justifyContent: 'space-between',
        background: 'linear-gradient(180deg,rgba(10,15,22,0.7),transparent)' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 7, padding: '5px 10px', borderRadius: 999, background: 'rgba(230,59,46,0.95)' }}>
          <span style={{ width: 7, height: 7, borderRadius: '50%', background: '#fff', animation: 'lvPulse 1.4s infinite' }} />
          <span style={{ color: '#fff', fontWeight: 800, fontSize: 11, letterSpacing: '0.06em' }}>LIVE</span>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, color: '#fff', fontSize: 12, fontWeight: 600, fontVariantNumeric: 'tabular-nums', background: 'rgba(0,0,0,0.35)', padding: '4px 9px', borderRadius: 999 }}>
          <Icon d={ICON.clock} size={12} color="#fff" /> {mm}:{ss}
        </div>
      </div>
      {/* inspector PiP */}
      <div style={{ position: 'absolute', top: 52, right: 13, width: 92, borderRadius: 12, overflow: 'hidden', border: '2px solid rgba(255,255,255,0.85)', boxShadow: '0 6px 18px rgba(0,0,0,0.35)' }}>
        <div style={{ position: 'relative', aspectRatio: '3 / 4' }}>
          <PhotoSlot dark label="Inspector" tag="INSPECTOR" minH="100%" radius={0} style={{ height: '100%' }} />
          <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, padding: '10px 6px 5px', background: 'linear-gradient(180deg,transparent,rgba(0,0,0,0.7))', color: '#fff', fontSize: 9, fontWeight: 700, textAlign: 'center' }}>{inspector}</div>
        </div>
      </div>
      {/* caption lower-third (inspector speaking) */}
      <div style={{ position: 'absolute', left: 13, right: 13, bottom: 70 }}>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, marginBottom: 7, padding: '4px 9px', borderRadius: 999, background: 'rgba(15,23,35,0.62)', backdropFilter: 'blur(4px)' }}>
          <Icon d={ICON.shieldCheck} size={12} color={LV.yellow} />
          <span style={{ color: '#fff', fontSize: 10.5, fontWeight: 700 }}>{inspector} · Certified Inspector</span>
        </div>
        <div key={cap} style={{
          background: 'rgba(15,23,35,0.78)', backdropFilter: 'blur(6px)', color: '#fff', padding: '11px 13px',
          borderRadius: 13, fontSize: 13.5, lineHeight: 1.42, fontWeight: 500, animation: 'lvFade 0.5s ease',
          border: '1px solid rgba(255,255,255,0.08)'
        }}>“{CALL_CAPTIONS[cap]}”</div>
      </div>
      {/* call controls */}
      <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, padding: '14px 13px 16px', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 16,
        background: 'linear-gradient(0deg,rgba(10,15,22,0.78),transparent)' }}>
        <div style={{ width: 38, height: 38, borderRadius: '50%', background: 'rgba(255,255,255,0.16)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon d={ICON.mic} size={16} color="#fff" />
        </div>
        <div style={{ width: 48, height: 48, borderRadius: '50%', background: LV.red, display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 6px 16px rgba(230,59,46,0.5)' }}>
          <Icon d={ICON.video} size={20} color="#fff" />
        </div>
        <div style={{ width: 38, height: 38, borderRadius: '50%', background: 'rgba(255,255,255,0.16)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon d={ICON.refresh} size={16} color="#fff" />
        </div>
      </div>
      {/* honest caption */}
      <div style={{ position: 'absolute', top: 8, left: '50%', transform: 'translateX(-50%)', display: 'none' }}>{label}</div>
    </div>);

}

// ===== REAL EXPLAINER VIDEO (YouTube) =====
// The actual on-page explainer that's outperforming expectations. Two modes:
//  - "ambient": silent autoplay + loop, no controls (Variant A "show it" hero)
//  - "facade":  branded poster + play button; tapping loads the iframe with sound
const YT_ID = '-nhxJclhPHk';
const YT_THUMB = `https://i.ytimg.com/vi/${YT_ID}/hqdefault.jpg`;

// Lightweight analytics hook: pushes to dataLayer (GA4) AND fires a DOM event.
// Claude Code maps these to GA4 events at integration time (see dev handoff notes).
function lvTrack(event, params) {
  try {
    const detail = Object.assign({ event: event }, params || {});
    (window.dataLayer = window.dataLayer || []).push(detail);
    window.dispatchEvent(new CustomEvent('lv-track', { detail: detail }));
  } catch (e) {}
}

function ExplainerVideo({ mode = 'ambient', rounded = 18, label = 'See how it works', sub = '60-second explainer', variant = '' }) {
  // Native HTML5 player. Behavior: autoplay ONCE muted on view → on end, return to a
  // start screen with a Play button → tapping plays from the start WITH sound.
  const vref = useRef(null);
  const wrapRef = useRef(null);
  const [phase, setPhase] = useState('idle'); // 'idle' | 'intro' (muted once) | 'cover' (start screen) | 'playing' (sound)
  const poster = window.LS_VIDEO_POSTER || YT_THUMB;
  const srcAvail = !!window.LS_VIDEO_SRC;
  const seen = useRef({ q25: false, q50: false, q75: false, started: false });

  // Autoplay muted once when scrolled into view (better for mobile + battery).
  useEffect(() => {
    const v = vref.current,w = wrapRef.current;
    if (!v || !w || !srcAvail) return;
    let started = false;
    const io = new IntersectionObserver((ents) => {
      ents.forEach((e) => {
        if (e.isIntersecting && !started) {
          started = true;
          v.muted = true;v.currentTime = 0;
          const p = v.play();
          if (p && p.catch) p.catch(() => setPhase('cover'));
          setPhase('intro');
          lvTrack('video_autoplay_start', { variant: variant, muted: true });
        }
      });
    }, { threshold: 0.5 });
    io.observe(w);
    return () => io.disconnect();
  }, [srcAvail]);

  const onEnded = () => {
    lvTrack('video_complete', { variant: variant, with_sound: phase === 'playing' });
    setPhase('cover');
  };
  const onTime = () => {
    const v = vref.current;if (!v || !v.duration) return;
    const pct = v.currentTime / v.duration;
    const s = seen.current;
    if (pct >= 0.25 && !s.q25) {s.q25 = true;lvTrack('video_progress', { variant: variant, pct: 25 });}
    if (pct >= 0.5 && !s.q50) {s.q50 = true;lvTrack('video_progress', { variant: variant, pct: 50 });}
    if (pct >= 0.75 && !s.q75) {s.q75 = true;lvTrack('video_progress', { variant: variant, pct: 75 });}
  };
  const playWithSound = () => {
    const v = vref.current;if (!v) return;
    v.muted = false;v.currentTime = 0;
    setPhase('playing');
    lvTrack('video_sound_on', { variant: variant });
    const p = v.play();if (p && p.catch) p.catch(() => {});
  };

  return (
    <div ref={wrapRef} data-track="explainer-video" style={{ position: 'relative', width: '100%', aspectRatio: '16 / 9', borderRadius: rounded, overflow: 'hidden', background: '#0c1118', boxShadow: '0 24px 60px -28px rgba(15,23,35,0.55)', border: '1px solid rgba(255,255,255,0.08)' }}>
      {srcAvail ?
      <video
        ref={vref}
        src={window.LS_VIDEO_SRC}
        poster={poster}
        playsInline
        muted={phase !== 'playing'}
        preload="metadata"
        controls={phase === 'playing'}
        onEnded={onEnded}
        onTimeUpdate={onTime}
        style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', objectFit: 'cover', background: '#0c1118' }} /> :


      <iframe
        title="Live Video Inspection — how it works"
        src={`https://www.youtube.com/embed/${YT_ID}?autoplay=1&mute=1&loop=1&playlist=${YT_ID}&controls=0&modestbranding=1&rel=0&playsinline=1&showinfo=0`}
        allow="autoplay; encrypted-media; picture-in-picture"
        allowFullScreen
        style={{ position: 'absolute', inset: 0, width: '100%', height: '100%', border: 'none' }} />
      }

      {/* fallback (no native file yet): show a live badge over the looping embed */}
      {!srcAvail &&
      <div style={{ position: 'absolute', top: 11, left: 11, display: 'flex', alignItems: 'center', gap: 7, padding: '5px 10px', borderRadius: 999, background: 'rgba(230,59,46,0.95)', pointerEvents: 'none' }}>
          <span style={{ width: 7, height: 7, borderRadius: '50%', background: '#fff', animation: 'lvPulse 1.4s infinite' }} />
          <span style={{ color: '#fff', fontWeight: 800, fontSize: 11, letterSpacing: '0.06em' }}>SEE HOW IT WORKS</span>
        </div>
      }

      {/* INTRO: muted auto-play once — show a live badge + tap-for-sound */}
      {srcAvail && phase === 'intro' &&
      <React.Fragment>
          <div style={{ position: 'absolute', top: 11, left: 11, display: 'flex', alignItems: 'center', gap: 7, padding: '5px 10px', borderRadius: 999, background: 'rgba(230,59,46,0.95)', pointerEvents: 'none' }}>
            <span style={{ width: 7, height: 7, borderRadius: '50%', background: '#fff', animation: 'lvPulse 1.4s infinite' }} />
            <span style={{ color: '#fff', fontWeight: 800, fontSize: 11, letterSpacing: '0.06em' }}>SEE HOW IT WORKS</span>
          </div>
          <button data-track="explainer-sound" onClick={playWithSound} style={{
          position: 'absolute', bottom: 11, right: 11, display: 'flex', alignItems: 'center', gap: 6,
          padding: '7px 12px', borderRadius: 999, background: 'rgba(15,23,35,0.7)', backdropFilter: 'blur(4px)',
          color: '#fff', border: '1px solid rgba(255,255,255,0.16)', cursor: 'pointer', fontFamily: FONT, fontSize: 12, fontWeight: 700
        }}>
            <Icon d={['M11 5L6 9H2v6h4l5 4V5z', 'M23 9l-6 6M17 9l6 6']} size={14} color="#fff" />
            Tap for sound
          </button>
        </React.Fragment>
      }

      {/* COVER: start screen with a Play button (idle before view, or after the silent play-through) */}
      {srcAvail && (phase === 'idle' || phase === 'cover') &&
      <button data-track="explainer-play" onClick={playWithSound} aria-label="Play explainer video with sound" style={{
        position: 'absolute', inset: 0, width: '100%', height: '100%', border: 'none', cursor: 'pointer', padding: 0,
        backgroundColor: '#0c1118', backgroundImage: 'url("' + poster + '")', backgroundSize: 'cover', backgroundPosition: 'center',
        display: 'flex', alignItems: 'center', justifyContent: 'center', fontFamily: FONT
      }}>
          <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg,rgba(12,17,24,0.28),rgba(12,17,24,0.72))' }} />
          <div style={{ position: 'relative', display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12 }}>
            <div style={{ width: 64, height: 64, borderRadius: '50%', background: LV.red, display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 10px 26px rgba(230,59,46,0.55)' }}>
              <svg width="23" height="23" viewBox="0 0 24 24" fill="#fff"><path d="M8 5v14l11-7z" /></svg>
            </div>
            <div style={{ textAlign: 'center', padding: '0 16px' }}>
              <div style={{ color: '#fff', fontWeight: 800, fontSize: 16 }}>{phase === 'cover' ? 'Watch with sound' : label}</div>
              <div style={{ color: 'rgba(255,255,255,0.72)', fontSize: 12.5, marginTop: 2 }}>{sub}</div>
            </div>
          </div>
        </button>
      }
    </div>);

}

// ===== STICKY CTA BAR =====
function StickyCTA({ label = 'Book your Live Inspection', price = true, onClick, track = 'sticky-cta', secondary }) {
  return (
    <div style={{
      position: 'fixed', left: 0, right: 0, bottom: 0, zIndex: 50,
      padding: '10px 14px calc(10px + env(safe-area-inset-bottom))',
      background: 'rgba(255,255,255,0.96)', backdropFilter: 'blur(10px)',
      borderTop: '1px solid ' + LV.g200, boxShadow: '0 -6px 24px -12px rgba(20,30,45,0.18)'
    }}>
      <div style={{ maxWidth: MAXW, margin: '0 auto', display: 'flex', alignItems: 'center', gap: 10 }}>
        {price &&
        <div style={{ flexShrink: 0 }}>
            <div style={{ fontWeight: 800, fontSize: 18, color: LV.ink, lineHeight: 1 }}>$59.99</div>
            <div style={{ fontSize: 10, color: LV.g500, fontWeight: 600, marginTop: 2 }}>only after it happens</div>
          </div>
        }
        <button data-track={track} onClick={onClick} style={{
          flex: 1, border: 'none', cursor: 'pointer', fontFamily: FONT,
          padding: '9px 14px', borderRadius: 12, background: LV.red, color: '#fff',
          display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', gap: 2,
          boxShadow: '0 8px 20px -8px rgba(230,59,46,0.6)'
        }}>
          <span style={{ display: 'flex', alignItems: 'center', gap: 8, fontWeight: 800, fontSize: 15, whiteSpace: 'nowrap' }}>{label} <Icon d={ICON.arrow} size={17} color="#fff" /></span>
          <span style={{ fontSize: 10.5, fontWeight: 600, opacity: 0.92, whiteSpace: 'nowrap' }}>{COPY.ctaSub}</span>
        </button>
      </div>
      {secondary}
    </div>);

}

// ===== HOW IT WORKS (3-step) =====
function HowItWorks({ accent = LV.red, compact = false }) {
  const steps = [
  { ic: ICON.wallet, t: 'Book in 2 minutes', d: 'Reserve your session online. Use it now, or save the link for when you go see the car.' },
  { ic: ICON.video, t: 'Connect on video — no app', d: 'Tap one link in your phone’s browser. A certified inspector joins you live.' },
  { ic: ICON.eye, t: 'Walk the car together', d: 'Up to 20 minutes. They guide every check and point out what an untrained eye would miss.' }];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      {steps.map((s, i) =>
      <div key={i} style={{ display: 'flex', gap: 14, alignItems: 'flex-start', padding: compact ? 0 : 4 }}>
          <div style={{ position: 'relative', flexShrink: 0 }}>
            <div style={{ width: 44, height: 44, borderRadius: 12, background: LV.redBg, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
              <Icon d={s.ic} size={21} color={accent} />
            </div>
            <div style={{ position: 'absolute', top: -6, left: -6, width: 20, height: 20, borderRadius: '50%', background: LV.ink, color: '#fff', fontSize: 11, fontWeight: 800, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{i + 1}</div>
          </div>
          <div style={{ paddingTop: 1 }}>
            <div style={{ fontWeight: 700, fontSize: 15.5, color: LV.ink, marginBottom: 3 }}>{s.t}</div>
            <div style={{ fontSize: 13.5, lineHeight: 1.5, color: LV.g600 }}>{s.d}</div>
          </div>
        </div>
      )}
    </div>);

}

// ===== TRUST / PROOF BLOCK =====
function TrustStats() {
  const stats = [
  { n: 'America’s #1', l: 'largest & most trusted' },
  { n: 'Since 2005', l: '20 years on buyers’ side' },
  { n: 'All 50 states', l: 'nationwide coverage' },
  { n: 'Specialists', l: 'pre-purchase is all they do' }];

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 1, background: LV.g200, borderRadius: 16, overflow: 'hidden', border: '1px solid ' + LV.g200 }}>
      {stats.map((s, i) =>
      <div key={i} style={{ background: '#fff', padding: '16px 14px', textAlign: 'center' }}>
          <div style={{ fontWeight: 800, fontSize: 19, color: LV.ink, letterSpacing: '-0.01em' }}>{s.n}</div>
          <div style={{ fontSize: 12, color: LV.g500, marginTop: 2 }}>{s.l}</div>
        </div>
      )}
    </div>);

}

// ===== TESTIMONIALS =====
const TESTIMONIALS = [
{ name: 'Dana R.', loc: 'Austin, TX', stars: 5, text: 'I was buying a car three states away and couldn’t fly out. The inspector walked the whole car with the seller on video and caught a repaint I’d never have spotted. Best $60 I’ve spent.' },
{ name: 'Marie L.', loc: 'Columbus, OH', stars: 5, text: 'I’m not a “car person” at all. Having a real expert on the call asking the seller the right questions made me feel like I finally had someone in my corner. Calm, kind, and clear.' },
{ name: 'Robert P.', loc: 'Phoenix, AZ', stars: 5, text: 'Booked it the night before I drove out to see the truck. Tapped the link in the lot, no app, connected in about a minute. Found a coolant leak — I walked away and saved myself a headache.' },
{ name: 'Sandra K.', loc: 'Tampa, FL', stars: 5, text: 'At 61, I dreaded buying a used car alone. The certified inspector was patient and explained everything in plain language. I bought with total confidence.' }];

function TestimonialCard({ t }) {
  return (
    <div style={{ background: '#fff', border: '1px solid ' + LV.g200, borderRadius: 16, padding: 18 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 10 }}>
        <Stars value={t.stars} size={14} />
        <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 10.5, fontWeight: 700, color: LV.green, background: LV.greenBg, padding: '3px 8px', borderRadius: 999 }}>
          <Icon d={ICON.check} size={11} color={LV.green} /> Verified buyer
        </span>
      </div>
      <div style={{ fontSize: 14, lineHeight: 1.55, color: LV.g700, marginBottom: 14 }}>“{t.text}”</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
        <Avatar name={t.name} size={38} />
        <div>
          <div style={{ fontWeight: 700, fontSize: 13.5, color: LV.ink }}>{t.name}</div>
          <div style={{ fontSize: 12, color: LV.g500 }}>{t.loc}</div>
        </div>
      </div>
    </div>);

}
function Testimonials({ items = TESTIMONIALS }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      {items.map((t, i) => <TestimonialCard key={i} t={t} />)}
    </div>);

}

// ===== FAQ =====
const FAQ_ITEMS = [
{ q: 'Is this legit? Who am I actually talking to?', a: 'Yes. You’re joined by a professional, certified inspection specialist — many are former mechanics who now do pre-purchase inspections full-time. It’s all they do, which makes them sharper at spotting problems than a general mechanic. Lemon Squad is America’s largest and most trusted vehicle inspection company, doing pre-purchase inspections since 2005.' },
{ q: 'Do I need to download an app?', a: 'No app required. You join right from your phone’s web browser — just tap the link we send and you’re connected.' },
{ q: 'What if the seller flakes, or I need to cancel?', a: 'You’re only charged after the session happens. If it doesn’t go through, you’re not billed — and you can reschedule for free.' },
{ q: 'Can the inspector tell me whether to buy it?', a: 'They’ll point out exactly what they see — wear, damage, red flags, and what repairs might cost — so you can decide from a position of strength. The call is your expert second opinion; the decision stays yours.' },
{ q: 'Can I upgrade to a full in-person inspection later?', a: 'Absolutely. A Live Video Inspection is the fast, lower-cost option at $59.99. Full on-site inspections start at $220 if you want hands-on diagnostics.' }];

function FAQItem({ item, open, onToggle, idx }) {
  return (
    <div style={{ borderBottom: '1px solid ' + LV.g200 }}>
      <button data-track={`faq-${idx}`} onClick={onToggle} style={{
        width: '100%', background: 'none', border: 'none', cursor: 'pointer', fontFamily: FONT,
        display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12,
        padding: '17px 2px', textAlign: 'left'
      }}>
        <span style={{ fontWeight: 700, fontSize: 14.5, color: LV.ink, lineHeight: 1.4 }}>{item.q}</span>
        <Icon d={ICON.chevronDown} size={18} color={LV.g400} style={{ transform: open ? 'rotate(180deg)' : 'none', transition: 'transform .2s', flexShrink: 0 }} />
      </button>
      <div style={{ maxHeight: open ? 320 : 0, overflow: 'hidden', transition: 'max-height .28s ease' }}>
        <div style={{ fontSize: 13.5, lineHeight: 1.6, color: LV.g600, padding: '0 2px 17px' }}>{item.a}</div>
      </div>
    </div>);

}
function FAQ({ items = FAQ_ITEMS }) {
  const [open, setOpen] = useState(0);
  return (
    <div>
      {items.map((it, i) =>
      <FAQItem key={i} item={it} idx={i} open={open === i} onToggle={() => setOpen(open === i ? -1 : i)} />
      )}
    </div>);

}

// ===== SECTION SHELL =====
function Section({ children, bg = '#fff', pad = '40px 20px', id, label }) {
  return (
    <section id={id} style={{ background: bg, padding: pad }}>
      <div style={{ maxWidth: MAXW, margin: '0 auto' }}>{children}</div>
    </section>);

}
function Eyebrow({ children, color = LV.red }) {
  return <div style={{ fontSize: 12, fontWeight: 800, letterSpacing: '0.1em', textTransform: 'uppercase', color, marginBottom: 8 }}>{children}</div>;
}
function H2({ children, dark = false, style }) {
  return <h2 style={{ fontSize: 24, fontWeight: 800, lineHeight: 1.18, letterSpacing: '-0.02em', color: dark ? '#fff' : LV.ink, margin: 0, textWrap: 'balance', ...style }}>{children}</h2>;
}

// ===== BENEFIT BULLET =====
function Benefit({ children, accent = LV.red }) {
  return (
    <div style={{ display: 'flex', gap: 11, alignItems: 'flex-start' }}>
      <div style={{ width: 22, height: 22, borderRadius: 7, background: LV.redBg, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, marginTop: 1 }}>
        <Icon d={ICON.check} size={14} color={accent} sw={2.5} />
      </div>
      <div style={{ fontSize: 14.5, lineHeight: 1.5, color: LV.g700 }}>{children}</div>
    </div>);

}

// ===== FOOTER (minimal, no nav) =====
function LiveFooter() {
  const link = { fontSize: 13, color: 'rgba(255,255,255,0.82)', textDecoration: 'none', lineHeight: 1.95, display: 'block' };
  const head = { fontSize: 11, fontWeight: 800, letterSpacing: '0.1em', textTransform: 'uppercase', color: 'rgba(255,255,255,0.45)', marginBottom: 8 };
  const tel = `tel:${phoneNumber.replace(/[^0-9]/g, '')}`;
  return (
    <footer style={{ background: LV.navyDeep, padding: '34px 20px 96px' }}>
      <div style={{ maxWidth: 820, margin: '0 auto' }}>
        <a href="https://www.lemonsquad.com" aria-label="Lemon Squad home">
          <img src={window.LS_LOGO_WHITE} alt="Lemon Squad" style={{ height: 26, marginBottom: 20, display: 'block' }} />
        </a>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '22px 16px' }}>
          <div>
            <div style={head}>Inspections</div>
            <a href="https://www.lemonsquad.com/live" style={link}>Live Video Inspection</a>
            <a href="https://www.lemonsquad.com/services" style={link}>Used Car Inspection</a>
            <a href="https://www.lemonsquad.com/services" style={link}>Classic &amp; Collector</a>
            <a href="https://www.lemonsquad.com/services" style={link}>Motorcycle &amp; RV</a>
          </div>
          <div>
            <div style={head}>Company</div>
            <a href="https://www.lemonsquad.com/about-us" style={link}>About Us</a>
            <a href="https://www.lemonsquad.com/how-it-works" style={link}>How It Works</a>
            <a href="https://www.lemonsquad.com/reviews" style={link}>Reviews</a>
            <a href="https://www.lemonsquad.com/sample-report" style={link}>Sample Report</a>
          </div>
        </div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px 22px', alignItems: 'center', marginTop: 22, paddingTop: 18, borderTop: '1px solid rgba(255,255,255,0.1)' }}>
          <a href="https://www.lemonsquad.com/contact-us" style={{ ...link, lineHeight: 1.4 }}>Contact</a>
          <a href="https://www.lemonsquad.com/faq" style={{ ...link, lineHeight: 1.4 }}>FAQ</a>
          <a href="https://www.lemonsquad.com/login" style={{ ...link, lineHeight: 1.4 }}>Account Login</a>
          <a href={tel} style={{ ...link, lineHeight: 1.4, fontWeight: 700, color: '#fff' }}>{phoneNumber}</a>
        </div>
        <div style={{ marginTop: 18, fontSize: 11.5, color: 'rgba(255,255,255,0.4)', lineHeight: 1.7 }}>
          © {new Date().getFullYear()} Lemon Squad · America’s largest &amp; most trusted vehicle inspection company.<br />
          <a href="https://www.lemonsquad.com/privacy-policy" style={{ color: 'rgba(255,255,255,0.6)', textDecoration: 'none' }}>Privacy Policy</a> · <a href="https://www.lemonsquad.com/terms" style={{ color: 'rgba(255,255,255,0.6)', textDecoration: 'none' }}>Terms</a>
        </div>
        <div style={{ marginTop: 12, fontSize: 10, color: 'rgba(255,255,255,0.3)', fontFamily: 'ui-monospace, monospace' }}>
          Demo prototype — imagery, testimonials &amp; figures are placeholders to swap with real assets.
        </div>
      </div>
    </footer>);

}

// ===== TWO-LINE CTA BUTTON (label + subhead inside the button) =====
function CtaButton({ label, sub, onClick, track, anchor, bg = LV.red, color = '#fff', radius = 14, fontSize = 16.5, style }) {
  return (
    <button data-track={track} data-comment-anchor={anchor} onClick={onClick} style={{
      width: '100%', border: 'none', cursor: 'pointer', fontFamily: FONT,
      padding: '12px 18px', borderRadius: radius, background: bg, color,
      display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 3,
      boxShadow: '0 14px 30px -12px rgba(230,59,46,0.5)', ...style
    }}>
      <span style={{ display: 'flex', alignItems: 'center', gap: 9, fontWeight: 800, fontSize, whiteSpace: 'nowrap' }}>{label} <Icon d={ICON.arrow} size={18} color={color} /></span>
      {sub !== null && <span style={{ fontSize: 11.5, fontWeight: 600, opacity: 0.9, whiteSpace: 'nowrap' }}>{sub || COPY.ctaSub}</span>}
    </button>);

}

// ===== FLOATING STICKY CTA (centered pill, not full-width; mobile + desktop) =====
function FloatingCTA({ onClick, track, label = 'Get an expert ready', sub, bg = LV.red, color = '#fff' }) {
  const [shown, setShown] = useState(false);
  useEffect(() => {
    const onScroll = () => setShown(window.scrollY > 380);
    onScroll();
    window.addEventListener('scroll', onScroll, { passive: true });
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <div style={{
      position: 'fixed', left: 0, right: 0, bottom: 0, zIndex: 50, pointerEvents: 'none',
      padding: '40px 16px calc(14px + env(safe-area-inset-bottom))',
      display: 'flex', justifyContent: 'center',
      background: 'linear-gradient(to top, rgba(15,18,22,0.10), transparent)',
      opacity: shown ? 1 : 0, transform: shown ? 'none' : 'translateY(22px)',
      transition: 'opacity .3s ease, transform .3s ease'
    }}>
      <button data-track={track} onClick={onClick} style={{
        pointerEvents: shown ? 'auto' : 'none', width: '100%', maxWidth: 440, border: 'none', cursor: 'pointer', fontFamily: FONT,
        padding: '12px 22px', borderRadius: 16, background: bg, color,
        display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 2,
        boxShadow: '0 14px 34px -8px rgba(230,59,46,0.6), 0 6px 16px rgba(15,18,22,0.18)'
      }}>
        <span style={{ display: 'flex', alignItems: 'center', gap: 9, fontWeight: 800, fontSize: 16, whiteSpace: 'nowrap' }}>{label} <Icon d={ICON.arrow} size={18} color={color} /></span>
        <span style={{ fontSize: 11, fontWeight: 600, opacity: 0.92, whiteSpace: 'nowrap' }}>{sub || COPY.ctaSub}</span>
      </button>
    </div>);

}

// ===== TOAST (for booking confirmation handoffs) =====
function useToast() {
  const [msg, setMsg] = useState(null);
  const show = (m) => {setMsg(m);setTimeout(() => setMsg(null), 2600);};
  const node = msg ?
  <div style={{ position: 'fixed', bottom: 88, left: '50%', transform: 'translateX(-50%)', zIndex: 80,
    background: LV.ink, color: '#fff', padding: '12px 18px', borderRadius: 12, fontSize: 13.5, fontWeight: 600,
    boxShadow: '0 12px 30px rgba(0,0,0,0.3)', maxWidth: 340, textAlign: 'center', animation: 'lvFade .3s ease' }}>{msg}</div> :
  null;
  return { show, node };
}

// ===== UNIFIED LEAD FORM (every CTA opens this) =====
// Small form: name, email, mobile + SMS & email opt-in. Themeable per variant.
function openLead(detail) {window.dispatchEvent(new CustomEvent('lv-open-lead', { detail: detail || {} }));}

function ConsentLink({ href, children }) {
  return <a href={href} target="_blank" rel="noopener noreferrer" onClick={(e) => e.stopPropagation()} style={{ color: LV.ink, textDecoration: 'underline', whiteSpace: 'nowrap' }}>{children}</a>;
}

// Collapsible consent text: shows a short lead-in with a "Read more" toggle so the full
// legal disclosure (with links) fits without crowding the form. The toggle and links
// stopPropagation so they don't flip the checkbox.
function ConsentText({ short, children }) {
  const [open, setOpen] = useState(false);
  return (
    <span style={{ fontSize: 12, color: LV.g600, lineHeight: 1.45 }}>
      {open ? children : short}{' '}
      <button type="button" aria-label={open ? 'Show less' : 'Read more'} onClick={(e) => { e.stopPropagation(); setOpen(!open); }} style={{
        background: 'none', border: 'none', padding: 0, marginLeft: 6, color: LV.ink, fontWeight: 800,
        fontSize: 15, lineHeight: 1, cursor: 'pointer', fontFamily: FONT, whiteSpace: 'nowrap', verticalAlign: 'baseline'
      }}>{open ? '−' : '+'}</button>
    </span>);
}

function LeadCheck({ on, onToggle, label, accent }) {
  return (
    <div role="checkbox" aria-checked={on} tabIndex={0} onClick={onToggle}
      onKeyDown={(e) => { if (e.key === ' ' || e.key === 'Enter') { e.preventDefault(); onToggle(); } }}
      style={{ display: 'flex', alignItems: 'flex-start', gap: 10, width: '100%', cursor: 'pointer', fontFamily: FONT }}>
      <span style={{
        marginTop: 1, width: 22, height: 22, borderRadius: 6, flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
        background: on ? accent : 'transparent', border: '2px solid ' + (on ? accent : LV.g300), transition: 'all .15s'
      }}>{on && <Icon d={ICON.check} size={13} color="#fff" sw={3} />}</span>
      <span style={{ flex: 1, fontSize: 12, color: LV.g600, lineHeight: 1.4 }}>{label}</span>
    </div>);

}

function LeadSheet({ theme = {} }) {
  const t = {
    accent: LV.red, onAccent: '#fff', panelBg: '#fff', ink: LV.ink, sub: LV.g500,
    fieldBorder: LV.g200, radius: 20, headFont: FONT, eyebrow: 'Get ready',
    ...theme
  };
  const [open, setOpen] = useState(false);
  const [done, setDone] = useState(false);
  const [f, setF] = useState({ name: '', email: '', phone: '', sms: false, mail: true });
  useEffect(() => {
    const h = () => {setDone(false);setOpen(true);};
    window.addEventListener('lv-open-lead', h);
    return () => window.removeEventListener('lv-open-lead', h);
  }, []);
  if (!open) return null;
  const field = {
    width: '100%', padding: '13px 14px', borderRadius: 12, border: '1.5px solid ' + t.fieldBorder,
    fontSize: 16, fontFamily: FONT, color: t.ink, outline: 'none', background: '#fff'
  };
  return (
    <div onClick={() => setOpen(false)} style={{
      position: 'fixed', inset: 0, zIndex: 90, background: 'rgba(15,20,30,0.55)', backdropFilter: 'blur(4px)',
      display: 'flex', alignItems: 'flex-end', justifyContent: 'center', animation: 'lvFade .2s ease'
    }}>
      <div onClick={(e) => e.stopPropagation()} data-track="lead-sheet" style={{
        width: '100%', maxWidth: 460, background: t.panelBg, borderTopLeftRadius: 26, borderTopRightRadius: 26,
        padding: '10px 22px calc(26px + env(safe-area-inset-bottom))', boxShadow: '0 -10px 40px rgba(0,0,0,0.3)',
        maxHeight: '92vh', overflowY: 'auto', animation: 'lvSheet .28s cubic-bezier(.2,.8,.2,1)'
      }}>
        <div style={{ width: 40, height: 4, borderRadius: 99, background: LV.g300, margin: '0 auto 16px' }} />
        {done ?
        <div style={{ textAlign: 'center', padding: '14px 6px 8px' }}>
            <div style={{ width: 60, height: 60, borderRadius: '50%', background: LV.greenBg, display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 16px' }}>
              <Icon d={ICON.check} size={30} color={LV.green} sw={2.5} />
            </div>
            <div style={{ fontFamily: t.headFont, fontSize: 22, fontWeight: 800, color: t.ink, marginBottom: 8 }}>Your link is on the way</div>
            <div style={{ fontSize: 14.5, lineHeight: 1.55, color: t.sub, marginBottom: 20, maxWidth: 360, marginInline: 'auto' }}>
              We’ll send your Live Inspection link to {f.phone || 'your phone'}{f.mail && f.email ? ' and ' + f.email : ''}. Tap it when you’re at the car — today or later this week. <strong style={{ color: t.ink }}>You’re only charged after your session happens.</strong>
            </div>
            <button onClick={() => setOpen(false)} style={{ border: 'none', background: t.accent, color: t.onAccent, fontFamily: FONT, fontWeight: 800, fontSize: 15, padding: '14px 26px', borderRadius: 12, cursor: 'pointer' }}>Done</button>
          </div> :

        <React.Fragment>
            <div style={{ fontSize: 12, fontWeight: 800, letterSpacing: '0.1em', textTransform: 'uppercase', color: t.accent, marginBottom: 6 }}>{t.eyebrow}</div>
            <div style={{ fontFamily: t.headFont, fontSize: 23, fontWeight: 800, color: t.ink, letterSpacing: '-0.01em', lineHeight: 1.15, marginBottom: 6 }}>Get your inspection link</div>
            <div style={{ fontSize: 13.5, lineHeight: 1.5, color: t.sub, marginBottom: 18 }}>Get your link now and use it whenever you’re at the car. No payment until your session actually happens.</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 11 }}>
              <input data-track="lead-name" value={f.name} onChange={(e) => setF({ ...f, name: e.target.value })} placeholder="First name" style={field} />
              <input data-track="lead-email" value={f.email} onChange={(e) => setF({ ...f, email: e.target.value })} placeholder="Email" inputMode="email" style={field} />
              <input data-track="lead-phone" value={f.phone} onChange={(e) => setF({ ...f, phone: e.target.value })} placeholder="Mobile number" inputMode="tel" style={field} />
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 9, margin: '15px 0 18px' }}>
              <LeadCheck on={f.mail} onToggle={() => setF({ ...f, mail: !f.mail })} accent={t.accent} label={
                <ConsentText short="I agree to receive promotional and informational emails from Lemon Squad and our partners…">
                  I agree to receive promotional and informational emails from Lemon Squad and our partners regarding my inspection, promotions, and related services. You may unsubscribe at any time. <ConsentLink href="https://lemonsquad.com/privacy">Privacy Policy</ConsentLink>
                </ConsentText>
              } />
              <LeadCheck on={f.sms} onToggle={() => setF({ ...f, sms: !f.sms })} accent={t.accent} label={
                <ConsentText short="I agree to receive phone calls and recurring automated SMS/text messages from Lemon Squad and our partners at the phone number provided…">
                  I agree to receive phone calls and recurring automated SMS/text messages from Lemon Squad and our partners at the phone number provided, including promotional and informational messages related to my inspection and related services. Message frequency varies. Message and data rates may apply. Reply STOP to opt out of text messages at any time. Consent is not a condition of purchase. <ConsentLink href="https://lemonsquad.com/terms">Terms</ConsentLink> <ConsentLink href="https://lemonsquad.com/privacy">Privacy Policy</ConsentLink>
                </ConsentText>
              } />
            </div>
            <button data-track="lead-submit" onClick={() => setDone(true)} style={{
            width: '100%', border: 'none', cursor: 'pointer', fontFamily: FONT, fontWeight: 800, fontSize: 16.5,
            padding: '16px', borderRadius: 13, background: t.accent, color: t.onAccent,
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 9
          }}>Get an expert ready <Icon d={ICON.arrow} size={18} color={t.onAccent} /></button>
            <div style={{ display: 'flex', justifyContent: 'center', marginTop: 13 }}>
              <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, padding: '7px 14px', borderRadius: 999, background: LV.greenBg, border: '1px solid ' + LV.g200 }}>
                <Icon d={ICON.shieldCheck} size={15} color={LV.green} />
                <span style={{ fontSize: 12.5, fontWeight: 800, color: LV.ink, whiteSpace: 'nowrap' }}>{COPY.guaranteeHead}</span>
              </div>
            </div>
            <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 7, fontSize: 12.5, color: t.sub, marginTop: 10 }}>
              <Icon d={ICON.shieldCheck} size={14} color={LV.green} /> <strong style={{ color: t.ink }}>$59.99</strong> · only charged after your session
            </div>
          </React.Fragment>
        }
      </div>
    </div>);

}

// ===== ILLUSTRATED LIVE WALKTHROUGH (made-up car + inspector + cycling focus & quotes) =====
const WALK = [
{ label: 'Full walkaround', pl: '50%', pt: '54%', q: "Let’s start with a slow walkaround — pan down the side for me." },
{ label: 'Hood & engine', pl: '72%', pt: '40%', q: "Pop the hood. Belts and fluid lines look clean — that’s a good sign." },
{ label: 'Front tire', pl: '70%', pt: '72%', q: "Show me the front tire… tread’s getting a little low on this edge." },
{ label: 'Doors & panel gaps', pl: '45%', pt: '44%', q: "Even gaps along the doors — no sign of accident repair here." },
{ label: 'Lights & rear', pl: '22%', pt: '50%', q: "Tap the brakes for me — just confirming all the lights work." }];


function CarArt() {
  // a simple, friendly side-profile car (made-up "image" of the car under inspection)
  return (
    <svg viewBox="0 0 320 190" width="100%" height="100%" preserveAspectRatio="xMidYMid slice" style={{ display: 'block' }}>
      <defs>
        <linearGradient id="lvSky" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0" stopColor="#2E3C52" /><stop offset="1" stopColor="#1B2433" />
        </linearGradient>
        <linearGradient id="lvBody" x1="0" y1="0" x2="0" y2="1">
          <stop offset="0" stopColor="#F2F5F9" /><stop offset="1" stopColor="#C9D4E0" />
        </linearGradient>
      </defs>
      <rect width="320" height="190" fill="url(#lvSky)" />
      <ellipse cx="160" cy="150" rx="135" ry="16" fill="rgba(0,0,0,0.28)" />
      {/* greenhouse / cabin */}
      <path d="M104 96 L132 64 Q136 60 144 60 L206 60 Q214 60 220 67 L242 96 Z" fill="url(#lvBody)" />
      <path d="M118 92 L138 70 Q140 68 145 68 L173 68 L173 92 Z" fill="#2A3850" opacity="0.92" />
      <path d="M181 92 L181 68 L203 68 Q208 68 211 72 L227 92 Z" fill="#2A3850" opacity="0.92" />
      {/* body */}
      <path d="M44 96 L276 96 Q292 96 292 112 L292 132 Q292 140 282 140 L38 140 Q28 140 28 130 L28 112 Q28 100 44 96 Z" fill="url(#lvBody)" />
      {/* accent stripe */}
      <rect x="30" y="120" width="262" height="5" rx="2.5" fill="#E63B2E" opacity="0.85" />
      {/* door line + handle */}
      <path d="M160 100 L160 134" stroke="#A9B6C6" strokeWidth="2" />
      <rect x="138" y="110" width="16" height="4" rx="2" fill="#8B9AAC" />
      {/* headlight */}
      <rect x="278" y="106" width="12" height="9" rx="3" fill="#F5A623" />
      {/* wheels */}
      <g>
        <circle cx="92" cy="140" r="30" fill="#1A2230" /><circle cx="92" cy="140" r="29" fill="none" stroke="#33425A" strokeWidth="2" />
        <circle cx="92" cy="140" r="13" fill="#C9D4E0" /><circle cx="92" cy="140" r="5" fill="#7C8AA0" />
        <circle cx="230" cy="140" r="30" fill="#1A2230" /><circle cx="230" cy="140" r="29" fill="none" stroke="#33425A" strokeWidth="2" />
        <circle cx="230" cy="140" r="13" fill="#C9D4E0" /><circle cx="230" cy="140" r="5" fill="#7C8AA0" />
      </g>
    </svg>);

}

function InspectorAvatarArt({ size = 84 }) {
  // a simple, friendly "person on a video tile" — made-up inspector
  return (
    <svg viewBox="0 0 100 130" width={size} height={size * 1.3} style={{ display: 'block' }}>
      <defs><linearGradient id="lvInsBg" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stopColor="#3A4A63" /><stop offset="1" stopColor="#222E40" /></linearGradient></defs>
      <rect width="100" height="130" fill="url(#lvInsBg)" />
      <circle cx="50" cy="48" r="22" fill="#E9C9A8" />
      <path d="M30 44 Q30 24 50 24 Q70 24 70 44 L70 38 Q60 32 50 32 Q40 32 30 38 Z" fill="#3A2E26" />
      <path d="M16 130 Q16 92 50 92 Q84 92 84 130 Z" fill="#2C6E5B" />
      <path d="M40 92 L50 108 L60 92 Z" fill="#F2F5F9" />
      <rect x="47" y="92" width="6" height="20" fill="#1f8f63" />
    </svg>);

}

function CarSceneMock({ accent = LV.red, rounded = 24, inspector = 'Marcus T.', aspect = '3 / 4' }) {
  const [i, setI] = useState(0);
  const [secs, setSecs] = useState(252);
  useEffect(() => {
    const a = setInterval(() => setI((c) => (c + 1) % WALK.length), 3200);
    const b = setInterval(() => setSecs((s) => s + 1), 1000);
    return () => {clearInterval(a);clearInterval(b);};
  }, []);
  const mm = String(Math.floor(secs / 60)).padStart(2, '0');
  const ss = String(secs % 60).padStart(2, '0');
  const w = WALK[i];
  return (
    <div data-track="hero-visual" aria-label="Live walkthrough demo" style={{
      position: 'relative', width: '100%', aspectRatio: aspect, borderRadius: rounded, overflow: 'hidden',
      boxShadow: '0 24px 60px -24px rgba(15,23,35,0.55)', border: '1px solid rgba(255,255,255,0.08)', background: '#1B2433'
    }}>
      <div style={{ position: 'absolute', inset: 0 }}><CarArt /></div>
      {/* moving inspection highlight */}
      <div style={{
        position: 'absolute', width: 64, height: 64, marginLeft: -32, marginTop: -32, left: w.pl, top: w.pt,
        borderRadius: '50%', border: '3px solid ' + accent, boxShadow: '0 0 0 4px rgba(230,59,46,0.18), 0 0 22px rgba(230,59,46,0.5)',
        transition: 'left .6s cubic-bezier(.4,0,.2,1), top .6s cubic-bezier(.4,0,.2,1)'
      }}>
        <span style={{ position: 'absolute', inset: -3, borderRadius: '50%', border: '2px solid ' + accent, opacity: 0.5, animation: 'lvPulse 1.6s infinite' }} />
      </div>
      {/* part label chip following highlight */}
      <div style={{
        position: 'absolute', left: w.pl, top: w.pt, transform: 'translate(-50%, 30px)',
        transition: 'left .6s cubic-bezier(.4,0,.2,1), top .6s cubic-bezier(.4,0,.2,1)',
        background: accent, color: '#fff', fontSize: 10.5, fontWeight: 800, padding: '4px 9px', borderRadius: 999, whiteSpace: 'nowrap'
      }}>{w.label}</div>
      {/* top status */}
      <div style={{ position: 'absolute', top: 0, left: 0, right: 0, padding: '12px 13px', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 7, padding: '5px 10px', borderRadius: 999, background: 'rgba(230,59,46,0.95)' }}>
          <span style={{ width: 7, height: 7, borderRadius: '50%', background: '#fff', animation: 'lvPulse 1.4s infinite' }} />
          <span style={{ color: '#fff', fontWeight: 800, fontSize: 11, letterSpacing: '0.06em' }}>LIVE</span>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 6, color: '#fff', fontSize: 12, fontWeight: 600, fontVariantNumeric: 'tabular-nums', background: 'rgba(0,0,0,0.35)', padding: '4px 9px', borderRadius: 999 }}>
          <Icon d={ICON.clock} size={12} color="#fff" /> {mm}:{ss}
        </div>
      </div>
      {/* inspector PiP (made-up person) */}
      <div style={{ position: 'absolute', top: 50, right: 13, width: 78, borderRadius: 12, overflow: 'hidden', border: '2px solid rgba(255,255,255,0.85)', boxShadow: '0 6px 18px rgba(0,0,0,0.35)' }}>
        <div style={{ position: 'relative' }}>
          <InspectorAvatarArt size={78} />
          <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, padding: '12px 4px 4px', background: 'linear-gradient(180deg,transparent,rgba(0,0,0,0.75))', color: '#fff', fontSize: 9, fontWeight: 700, textAlign: 'center' }}>{inspector}</div>
        </div>
      </div>
      {/* caption (inspector speaking) */}
      <div style={{ position: 'absolute', left: 13, right: 13, bottom: 66 }}>
        <div style={{ display: 'inline-flex', alignItems: 'center', gap: 6, marginBottom: 7, padding: '4px 9px', borderRadius: 999, background: 'rgba(15,23,35,0.62)', backdropFilter: 'blur(4px)' }}>
          <Icon d={ICON.shieldCheck} size={12} color={LV.yellow} />
          <span style={{ color: '#fff', fontSize: 10.5, fontWeight: 700 }}>{inspector} · Certified Inspector</span>
        </div>
        <div key={i} style={{
          background: 'rgba(15,23,35,0.8)', backdropFilter: 'blur(6px)', color: '#fff', padding: '11px 13px',
          borderRadius: 13, fontSize: 13.5, lineHeight: 1.42, fontWeight: 500, animation: 'lvFade 0.5s ease', border: '1px solid rgba(255,255,255,0.08)'
        }}>“{w.q}”</div>
      </div>
      {/* call controls */}
      <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, padding: '14px 13px 16px', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 16, background: 'linear-gradient(0deg,rgba(10,15,22,0.78),transparent)' }}>
        <div style={{ width: 36, height: 36, borderRadius: '50%', background: 'rgba(255,255,255,0.16)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon d={ICON.mic} size={15} color="#fff" /></div>
        <div style={{ width: 46, height: 46, borderRadius: '50%', background: accent, display: 'flex', alignItems: 'center', justifyContent: 'center', boxShadow: '0 6px 16px rgba(230,59,46,0.5)' }}><Icon d={ICON.video} size={19} color="#fff" /></div>
        <div style={{ width: 36, height: 36, borderRadius: '50%', background: 'rgba(255,255,255,0.16)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon d={ICON.refresh} size={15} color="#fff" /></div>
      </div>
    </div>);

}

// ===== CANONICAL COPY (shared across A/B/C so all three say the same thing) =====
const COPY = {
  heroLead: "See what’s wrong, negotiate a better price, and ",
  heroAccent: "buy with confidence.",
  heroSub: "A certified inspector joins you on live video while you’re at the car — a quick, expert once-over that shows you exactly what matters, in plain language.",
  subhead: "A certified inspector joins you on live video and checks a used car with you — pointing out what an untrained eye would miss, so you buy with confidence.",
  bullets: [
  ["A certified inspection specialist", " — not a general mechanic — right there with you at the car."],
  ["No app needed.", " Just tap the link we send — it opens right in your phone’s browser."],
  ["Get your link now,", " then use it when you’re standing at the car."]],

  steps: [
  ["Book in 2 minutes", "Reserve online now. Use it now, or save the link for when you go see the car."],
  ["Connect on video — no app", "Tap one link in your phone’s browser. A certified inspector joins you live."],
  ["Walk the car together", "Up to 20 minutes. They guide every check and flag what an untrained eye misses."]],

  valueHead: "Quickly spot the details that save you money",
  valueLead: "In a few minutes, a certified inspector helps you see exactly what to check — and what’s wrong.",
  valueBody: " Use it to negotiate a better price — or walk away with confidence. At $59.99, this service really pays for itself.",
  guaranteeHead: "100% satisfaction guarantee",
  guaranteeBody: "Not happy with your session? Get your money back — and you’re only charged after your session happens.",
  guaranteeShort: "Backed by our 100% satisfaction guarantee.",
  ctaSub: "Use it at the car · pay only after your session"
};

// ===== GUARANTEE ROW (themeable; appears on all three) =====
function GuaranteeRow({ theme = {}, style }) {
  const t = { bg: LV.greenBg, ring: '#fff', sealBg: LV.redBg, sealIcon: LV.red, ink: LV.ink, sub: LV.g600, border: LV.g200, ...theme };
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 14, padding: '15px 16px', background: t.bg, borderRadius: 16, border: '1px solid ' + t.border, ...style }}>
      <div style={{ width: 50, height: 50, borderRadius: '50%', flexShrink: 0, background: t.sealBg, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Icon d={ICON.shieldCheck} size={25} color={t.sealIcon} />
      </div>
      <div>
        <div style={{ fontWeight: 800, fontSize: 14.5, color: t.ink }}>{COPY.guaranteeHead}</div>
        <div style={{ fontSize: 12.5, color: t.sub, lineHeight: 1.45, marginTop: 2 }}>{COPY.guaranteeBody}</div>
      </div>
    </div>);

}

// ===== AI ASSISTANT (themeable; scripted Q&A → booking handoff; used on all three) =====
const ASSIST_QA = [
{ chip: 'What is this?', a: "Live Video Inspection is a video call with a certified inspection specialist. While you’re at the car, you point your phone’s camera at it and they guide you through every check in real time — pointing out anything an untrained eye would miss. Up to 20 minutes, $59.99." },
{ chip: 'How does it work?', a: "Three steps: 1) Reserve online. 2) When you’re at the car, tap the link we send — no app, it opens in your browser. 3) A certified inspector joins you on video and walks the car with you. Get your link now and use it whenever you go see it." },
{ chip: 'When am I charged?', a: "Only when the session actually happens. If the seller flakes or you cancel, you’re not billed — and rescheduling is free. It’s $59.99, backed by our 100% satisfaction guarantee." }];

const ASSIST_FALLBACK = "Great question. The short version: a certified inspector joins you on a live video call to check the car with you — no app, $59.99, and you’re only charged after it happens. Want me to set you up?";

const ASSIST_THEME = {
  accent: LV.red, panelBg: LV.g100, headerBg: '#fff',
  botBg: '#fff', botText: LV.g700, botBorder: LV.g200,
  ink: LV.ink, sub: LV.g500, border: LV.g200, online: LV.green,
  chipBg: LV.redBg, chipBorder: LV.redBorder, chipText: LV.redDark,
  fieldBg: '#fff', fieldText: LV.ink
};

// Turn bare URLs in the assistant's text into clickable links (the model replies in
// plain text, so without this a "lemonsquad.com/exotic" link wouldn't be tappable).
function lvLinkify(text) {
  const s = String(text == null ? '' : text);
  return s.split(/(https?:\/\/[^\s]+)/g).map((p, i) => {
    if (!/^https?:\/\//.test(p)) return p;
    const href = p.replace(/[).,!?:;]+$/, ''); // don't let trailing punctuation into the URL
    return <a key={i} href={href} target="_blank" rel="noopener noreferrer" style={{ color: 'inherit', fontWeight: 700, textDecoration: 'underline' }}>{p}</a>;
  });
}

// Stable, module-level message bubble. Defining this INSIDE LiveAssistant made it a
// new component type on every render, so each keystroke / streamed token remounted the
// whole list and replayed the fade-in animation (the "flashing"). Hoisting it fixes that.
function AssistantBubble({ from, t, children }) {
  const me = from === 'me';
  return (
    <div style={{ display: 'flex', justifyContent: me ? 'flex-end' : 'flex-start', gap: 8, animation: 'lvFade .3s ease' }}>
      {!me && <div style={{ width: 28, height: 28, borderRadius: '50%', background: t.accent, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0, alignSelf: 'flex-end' }}><Icon d={ICON.shieldCheck} size={15} color="#fff" /></div>}
      <div style={{ maxWidth: '80%', padding: '10px 13px', borderRadius: 15, borderBottomRightRadius: me ? 4 : 15, borderBottomLeftRadius: me ? 15 : 4, background: me ? t.accent : t.botBg, color: me ? '#fff' : t.botText, fontSize: 13.5, lineHeight: 1.5, fontWeight: me ? 600 : 400, border: me ? 'none' : '1px solid ' + t.botBorder }}>{me ? children : lvLinkify(children)}</div>
    </div>);
}

function LiveAssistant({ theme = {}, track = 'assistant', variant = '' }) {
  const t = { ...ASSIST_THEME, ...theme };
  const pfx = variant ? `var${variant}-` : '';
  const [msgs, setMsgs] = useState([{ from: 'bot', text: "Hi! Ask me anything about Live Video Inspection." }]);
  const [typing, setTyping] = useState(false);
  const [showBook, setShowBook] = useState(false);
  const [asked, setAsked] = useState([]);
  const [input, setInput] = useState('');
  const endRef = useRef(null);
  useEffect(() => {if (endRef.current) endRef.current.scrollTop = endRef.current.scrollHeight;}, [msgs, typing]);

  const busyRef = useRef(false);

  // AI endpoint config is injected by ls-ai.js (window.LS_AI_*). The anon key is
  // public-by-design; the Gemini key stays server-side in the `ai` edge function.
  const AI_ENDPOINT = (typeof window !== 'undefined' && window.LS_AI_ENDPOINT) || '';
  const AI_KEY = (typeof window !== 'undefined' && window.LS_AI_KEY) || '';

  // Stream the assistant reply from the gateway, appending tokens live.
  const streamReply = async (history) => {
    busyRef.current = true;
    setTyping(true);
    if (!AI_ENDPOINT) { // not wired (e.g. offline bundle) — graceful canned reply
      setTimeout(() => {
        setTyping(false); setShowBook(true); busyRef.current = false;
        setMsgs((m) => [...m, { from: 'bot', text: ASSIST_FALLBACK }]);
      }, 600);
      return;
    }
    try {
      const res = await fetch(AI_ENDPOINT, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Authorization: 'Bearer ' + AI_KEY, apikey: AI_KEY },
        body: JSON.stringify({ task: 'live-assistant', input: { messages: history } }),
      });
      if (!res.ok || !res.body) throw new Error('bad response');
      const reader = res.body.getReader();
      const dec = new TextDecoder();
      let acc = '', started = false;
      for (;;) {
        const { done, value } = await reader.read();
        if (done) break;
        const chunk = dec.decode(value, { stream: true });
        if (!chunk) continue;
        acc += chunk;
        if (!started) { started = true; setTyping(false); setMsgs((m) => [...m, { from: 'bot', text: acc }]); }
        else setMsgs((m) => { const c = m.slice(); c[c.length - 1] = { from: 'bot', text: acc }; return c; });
      }
      if (!started) setMsgs((m) => [...m, { from: 'bot', text: ASSIST_FALLBACK }]);
    } catch (e) {
      setMsgs((m) => [...m, { from: 'bot', text: ASSIST_FALLBACK }]);
    } finally {
      setTyping(false); setShowBook(true); busyRef.current = false;
    }
  };

  // Send a question: record it, build the chat history, and stream a reply.
  const ask = (q) => {
    const text = (q || '').trim();
    if (!text || busyRef.current) return;
    lvTrack('assistant_message', { variant: variant, q: text.slice(0, 120) });
    const history = msgs
      .filter((x, i) => !(i === 0 && x.from === 'bot')) // drop the opening greeting
      .map((x) => ({ role: x.from === 'me' ? 'user' : 'assistant', content: x.text }))
      .concat([{ role: 'user', content: text }]);
    setMsgs((m) => [...m, { from: 'me', text: text }]);
    streamReply(history);
  };
  const tapChip = (item) => { setAsked((a) => [...a, item.chip]); ask(item.chip); };
  const send = () => { if (!input.trim()) return; const v = input.trim(); setInput(''); ask(v); };
  const remaining = ASSIST_QA.filter((x) => !asked.includes(x.chip));

  // (message bubble hoisted to module-level AssistantBubble — see above)

  return (
    <div data-track={`${pfx}assistant`} style={{ background: t.panelBg, borderRadius: 20, overflow: 'hidden', border: '1px solid ' + t.border, boxShadow: '0 14px 40px -24px rgba(20,30,45,0.3)' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '13px 15px', background: t.headerBg, borderBottom: '1px solid ' + t.border }}>
        <div style={{ position: 'relative', width: 36, height: 36, borderRadius: '50%', background: t.accent, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
          <Icon d={ICON.spark} size={18} color="#fff" fill="#fff" sw={0} />
          <span style={{ position: 'absolute', bottom: -1, right: -1, width: 11, height: 11, borderRadius: '50%', background: t.online, border: '2px solid ' + t.headerBg }} />
        </div>
        <div style={{ flex: 1 }}>
          <div style={{ fontWeight: 800, fontSize: 14.5, color: t.ink }}>Ask an expert</div>
          <div style={{ fontSize: 11.5, color: t.online, fontWeight: 600 }}>● Online · replies instantly</div>
        </div>
      </div>
      <div ref={endRef} style={{ padding: 15, display: 'flex', flexDirection: 'column', gap: 10, maxHeight: 340, overflowY: 'auto' }}>
        {msgs.map((m, i) => <AssistantBubble key={i} from={m.from === 'me' ? 'me' : 'bot'} t={t}>{m.text}</AssistantBubble>)}
        {typing &&
        <div style={{ display: 'flex', gap: 8 }}>
            <div style={{ width: 28, height: 28, borderRadius: '50%', background: t.accent, display: 'flex', alignItems: 'center', justifyContent: 'center', alignSelf: 'flex-end' }}><Icon d={ICON.shieldCheck} size={15} color="#fff" /></div>
            <div style={{ padding: '13px 15px', borderRadius: 15, borderBottomLeftRadius: 4, background: t.botBg, border: '1px solid ' + t.botBorder, display: 'flex', gap: 4 }}>
              {[0, 1, 2].map((i) => <span key={i} style={{ width: 6, height: 6, borderRadius: '50%', background: LV.g400, animation: `lvPulse 1s ${i * 0.18}s infinite` }} />)}
            </div>
          </div>
        }
        {showBook &&
        <div style={{ animation: 'lvFade .3s ease', marginTop: 2 }}>
            <button data-track={`${pfx}assistant-book`} onClick={() => openLead({ v: variant })} style={{ width: '100%', border: 'none', cursor: 'pointer', fontFamily: FONT, fontWeight: 800, fontSize: 15, padding: '13px', borderRadius: 12, background: t.accent, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8 }}>Book my session — $59.99 <Icon d={ICON.arrow} size={16} color="#fff" /></button>
            <div style={{ textAlign: 'center', fontSize: 11, color: t.sub, marginTop: 6 }}>Only charged after it happens · 100% satisfaction guarantee</div>
          </div>
        }
      </div>
      <div style={{ padding: '0 13px 13px' }}>
        {remaining.length > 0 &&
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 7, marginBottom: 10 }}>
            {remaining.map((item) =>
          <button key={item.chip} data-track={`${pfx}assistant-chip`} onClick={() => tapChip(item)} style={{ border: '1px solid ' + t.chipBorder, cursor: 'pointer', fontFamily: FONT, fontWeight: 700, fontSize: 12.5, padding: '8px 12px', borderRadius: 999, background: t.chipBg, color: t.chipText }}>{item.chip}</button>
          )}
          </div>
        }
        <div style={{ display: 'flex', gap: 8, alignItems: 'center', background: t.fieldBg, borderRadius: 13, border: '1px solid ' + t.border, padding: 6 }}>
          <input data-track={`${pfx}assistant-input`} value={input} onChange={(e) => setInput(e.target.value)} onKeyDown={(e) => e.key === 'Enter' && send()} placeholder="Type your question…" style={{ flex: 1, border: 'none', outline: 'none', fontSize: 14, padding: '6px 8px', background: 'transparent', color: t.fieldText, fontFamily: FONT }} />
          <button data-track={`${pfx}assistant-send`} onClick={send} style={{ width: 36, height: 36, borderRadius: 10, flexShrink: 0, background: t.accent, border: 'none', cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center' }}><Icon d={ICON.send} size={16} color="#fff" /></button>
        </div>
      </div>
    </div>);

}

Object.assign(window, {
  LV, FONT, MAXW, phoneNumber, Icon, ICON, Stars, Avatar, PhotoSlot,
  LiveHeader, PriceLine, TrustPill, VideoCallMock, ExplainerVideo, YT_ID, StickyCTA, HowItWorks,
  TrustStats, TESTIMONIALS, TestimonialCard, Testimonials, FAQ_ITEMS, FAQ,
  Section, Eyebrow, H2, Benefit, LiveFooter, useToast,
  openLead, LeadSheet, CarSceneMock, CarArt, InspectorAvatarArt,
  COPY, GuaranteeRow, LiveAssistant, ASSIST_QA, CtaButton, useIsWide, MAXW_D, FloatingCTA
});