// HomePro For Owners — B2B scroll-driven landing, themed by the operator's chosen trade.
// User picks a service from 170+ on first load; every scene, copy, and form reshapes around it.

function ForOwners() {
  const [service, setService] = React.useState(() => {
    try { return localStorage.getItem('hp-owner-service') || null; } catch { return null; }
  });
  const [pickerOpen, setPickerOpen] = React.useState(() => {
    // Open the picker on first load if no service is stored
    try { return !localStorage.getItem('hp-owner-service'); } catch { return true; }
  });

  const config = service ? getServiceConfig(service) : null;

  const handlePick = (name) => {
    setService(name);
    try { localStorage.setItem('hp-owner-service', name); } catch {}
    setPickerOpen(false);
    setTimeout(() => window.scrollTo({ top: 0, behavior: 'smooth' }), 100);
  };

  // URL param auto-pick: /for-owners.html?s=Roofing skips the picker
  React.useEffect(() => {
    const param = new URLSearchParams(location.search).get('s');
    if (param) {
      const match = SERVICE_LIST.find(([name]) =>
        name.toLowerCase() === param.toLowerCase() ||
        name.toLowerCase().replace(/\s+/g, '-') === param.toLowerCase().replace(/\s+/g, '-')
      );
      if (match) handlePick(match[0]);
    }
  }, []);

  return (
    <div className="fo-root" style={{ background:'#fff', fontFamily:'var(--font-body)', color:'var(--ink)' }}>
      <ServicePicker open={pickerOpen} onPick={handlePick} onClose={service ? () => setPickerOpen(false) : null} current={service}/>
      {/* Show landing chrome behind the picker so the page feels alive */}
      <NavOwners service={service} onSwitch={() => setPickerOpen(true)}/>
      <div data-grain="1"><HeroOwners config={config} onSwitch={() => setPickerOpen(true)}/></div>
      <div data-reveal="1"><LogoStrip current={service}/></div>
      <div data-reveal="1"><FilmStripOwners config={config} onSwitch={() => setPickerOpen(true)}/></div>
      <div data-grain="1"><PriceIntelligence config={config}/></div>
      <div data-reveal="1"><BuiltForOwners config={config}/></div>
      <div data-grain="1"><CTAOwners config={config}/></div>
      <FooterOwners/>
    </div>
  );
}

/* ============== NAV ============== */
function NavOwners({ service, onSwitch }) {
  return (
    <nav className="fo-nav" style={{ position:'sticky', top:0, zIndex:60, display:'flex', alignItems:'center', justifyContent:'space-between', padding:'14px 56px', background:'rgba(255,255,255,0.85)', backdropFilter:'blur(20px) saturate(180%)', borderBottom:'1px solid var(--line-2)' }}>
      <div style={{ display:'flex', alignItems:'center', gap:32 }}>
        <a href="../index.html" style={{ display:'flex', alignItems:'center', gap:10, textDecoration:'none', color:'var(--ink)' }}>
          <Logo size={34}/>
          <Wordmark size={19}/>
          <span style={{ fontFamily:'var(--font-display)', fontWeight:600, fontSize:12, letterSpacing:'0.08em', textTransform:'uppercase', padding:'3px 8px', borderRadius:99, background:'var(--lilac-100)', color:'var(--lilac-800)', marginLeft:6 }}>For Owners</span>
        </a>
        {service && (
          <button onClick={onSwitch} style={{
            display:'flex', alignItems:'center', gap:7,
            background:'var(--ink)', color:'#fff', border:0,
            padding:'7px 6px 7px 14px', borderRadius:99, cursor:'pointer',
            fontFamily:'var(--font-body)', fontSize:12.5, fontWeight:600,
          }}>
            <span style={{ width:5, height:5, borderRadius:99, background:'var(--chart-300)' }} className="pulse-soft"/>
            <span style={{ opacity:.6, fontWeight:500 }}>Trade ·</span>
            <span>{service}</span>
            <span style={{ background:'rgba(255,255,255,0.12)', color:'#fff', padding:'3px 8px', borderRadius:99, fontSize:11, marginLeft:4 }}>switch</span>
          </button>
        )}
        <div className="fo-nav-links" style={{ display:'flex', gap:24, fontSize:14 }}>
          <a href="#" style={{ color:'var(--ink)', textDecoration:'none', fontWeight:500 }}>Estimate engine</a>
        </div>
      </div>
      <div className="fo-nav-right" style={{ display:'flex', gap:10, alignItems:'center' }}>
        <a href="#" className="fo-nav-signin" style={{ fontSize:13, fontWeight:500, color:'var(--ink)', textDecoration:'none' }}>Sign in</a>
        <a href="/onboarding" style={{ background:'var(--ink)', color:'var(--chart-300)', border:0, padding:'9px 18px', borderRadius:99, fontWeight:600, fontSize:13, cursor:'pointer', fontFamily:'var(--font-body)', textDecoration:'none', display:'inline-flex', alignItems:'center' }}>Start onboarding →</a>
      </div>
    </nav>
  );
}

/* ============== HERO ============== */
function HeroOwners({ config, onSwitch }) {
  const trade = config ? config.name : null;

  return (
    <section style={{ position:'relative', overflow:'hidden', background:'var(--ink)', color:'#fff' }}>
      {/* MESH GRADIENT BACKDROP */}
      <HeroGradient/>
      <div className="bg-grid" style={{ position:'absolute', inset:0, opacity:0.18, mixBlendMode:'screen' }}/>

      {/* TOP BAR */}
      <div className="fo-hero-topbar" style={{ position:'relative', padding:'40px 56px 0', display:'flex', justifyContent:'space-between', alignItems:'flex-start' }}>
        <div onClick={config ? onSwitch : undefined} style={{ display:'inline-flex', alignItems:'center', gap:9, padding:'7px 14px', background:'rgba(255,255,255,0.08)', border:'1px solid rgba(255,255,255,0.14)', borderRadius:99, backdropFilter:'blur(20px)', fontSize:12.5, fontWeight:500, color:'rgba(255,255,255,0.85)', cursor: config ? 'pointer' : 'default' }}>
          <span style={{ width:7, height:7, borderRadius:99, background:'var(--chart-300)' }} className="pulse-soft"/>
          {config ? <>Configured for <strong style={{ color:'#fff', fontWeight:700 }}>{trade}</strong> · {config.catLabel} · switch ↗</>
                  : <>For home service operators</>}
        </div>
      </div>

      {/* MASSIVE EDITORIAL HEADLINE */}
      <div className="fo-hero-head-wrap" style={{ position:'relative', padding:'80px 56px 30px', maxWidth:1280 }}>
        <h1 className="display fo-hero-h1" style={{ fontSize:184, fontWeight:500, margin:0, letterSpacing:'-0.06em', lineHeight:0.86, color:'#fff' }}>
          {trade ? (
            <span style={{ display:'block', fontSize:62, fontWeight:400, letterSpacing:'-0.04em', lineHeight:1, color:'rgba(255,255,255,0.5)', marginBottom:14 }}>
              <span className="serif-it" style={{ color:'var(--lilac-300)' }}>{trade}</span> operators —
            </span>
          ) : null}
          Estimates<br/>
          that <span className="serif-it" style={{ color:'var(--chart-300)', textShadow:'0 0 80px rgba(196,240,0,0.5)' }}>close</span><br/>
          themselves.
        </h1>
      </div>

      {/* SUPPORTING COPY */}
      <div className="fo-hero-sub-wrap" style={{ position:'relative', padding:'10px 56px 50px' }}>
        <p className="fo-hero-sub" style={{ fontSize:22, color:'rgba(255,255,255,0.7)', lineHeight:1.45, maxWidth:760, margin:0 }}>
          {trade
            ? <>The AI estimate engine that measures the property, qualifies the lead, builds the quote, and chases the signature — without an estimator. Built for {trade.toLowerCase()} operators who'd rather run a business than babysit a CRM.</>
            : <>The AI estimate engine that measures the property, qualifies the lead, builds the quote, and chases the signature — without an estimator. Built for operators who'd rather run a business than babysit a CRM.</>}
        </p>
      </div>

      {/* CTA ROW */}
      <div className="fo-hero-cta" style={{ position:'relative', padding:'10px 56px 80px', display:'flex', alignItems:'center', gap:14 }}>
        <a href="/onboarding" style={{ background:'var(--chart-300)', color:'var(--ink)', border:0, padding:'18px 28px', borderRadius:99, fontWeight:700, fontSize:15, cursor:'pointer', fontFamily:'var(--font-body)', display:'inline-flex', alignItems:'center', gap:10, boxShadow:'0 18px 48px rgba(196,240,0,0.4)', textDecoration:'none' }}>
          Start onboarding <IconArrow size={16}/>
        </a>
        <button
          onClick={() => window.scrollBy({ top: window.innerHeight * 1.1, behavior: 'smooth' })}
          style={{ background:'transparent', color:'#fff', border:'1px solid rgba(255,255,255,0.2)', padding:'17px 24px', borderRadius:99, fontWeight:600, fontSize:14, cursor:'pointer', fontFamily:'var(--font-body)' }}
        >
          Watch the demo ↓
        </button>
      </div>
    </section>
  );
}

/* Animated mesh-gradient backdrop — multiple drifting radial blooms */
function HeroGradient() {
  return (
    <>
      <style>{`
        @keyframes hero-drift-1 { 0% { transform: translate(0,0) scale(1); } 50% { transform: translate(60px,-40px) scale(1.08); } 100% { transform: translate(0,0) scale(1); } }
        @keyframes hero-drift-2 { 0% { transform: translate(0,0) scale(1); } 50% { transform: translate(-50px,40px) scale(0.95); } 100% { transform: translate(0,0) scale(1); } }
        @keyframes hero-drift-3 { 0% { transform: translate(0,0) scale(1); } 50% { transform: translate(40px,30px) scale(1.05); } 100% { transform: translate(0,0) scale(1); } }
      `}</style>
      <div style={{ position:'absolute', inset:0, pointerEvents:'none' }}>
        <div style={{ position:'absolute', top:'-15%', left:'-10%', width:'70%', height:'90%', background:'radial-gradient(circle, var(--chart-700) 0%, transparent 60%)', opacity:0.7, filter:'blur(60px)', animation:'hero-drift-1 18s ease-in-out infinite' }}/>
        <div style={{ position:'absolute', bottom:'-30%', right:'-15%', width:'80%', height:'100%', background:'radial-gradient(circle, var(--lilac-700) 0%, transparent 60%)', opacity:0.85, filter:'blur(70px)', animation:'hero-drift-2 22s ease-in-out infinite' }}/>
        <div style={{ position:'absolute', top:'35%', right:'10%', width:'45%', height:'55%', background:'radial-gradient(circle, var(--lilac-500) 0%, transparent 60%)', opacity:0.35, filter:'blur(80px)', animation:'hero-drift-3 26s ease-in-out infinite' }}/>
        <div style={{ position:'absolute', top:'55%', left:'8%', width:'40%', height:'55%', background:'radial-gradient(circle, var(--chart-500) 0%, transparent 60%)', opacity:0.25, filter:'blur(80px)', animation:'hero-drift-1 30s ease-in-out infinite' }}/>
      </div>
    </>
  );
}

/* ============== LOGO STRIP ============== */
function LogoStrip({ current }) {
  const trades = ['Roofing','HVAC','Solar','Plumbing','Electrical','Pool','Tree','Painting','Fence','Concrete','Pest','Landscape','Garage','Window','Siding','Cleaning','Restoration','Remodel','Commercial','Emergency'];
  return (
    <section style={{ padding:'30px 0 50px', background:'#fff', borderTop:'1px solid var(--line-2)', borderBottom:'1px solid var(--line-2)' }}>
      <div style={{ maxWidth:1180, margin:'0 auto', textAlign:'center' }}>
        <div className="eyebrow" style={{ color:'var(--mute-1)' }}>One engine · {SERVICE_LIST.length}+ trades · yours configured</div>
      </div>
      <div style={{ marginTop:18, overflow:'hidden', position:'relative' }}>
        <div className="marquee" style={{ width:'200%' }}>
          {[...trades, ...trades].map((t, i) => {
            const matches = current && (current.toLowerCase().includes(t.toLowerCase()) || t.toLowerCase().includes(current.split(' ')[0].toLowerCase()));
            return (
              <div key={i} style={{ display:'flex', alignItems:'center', gap:36, padding:'0 18px', fontFamily:'var(--font-display)', fontSize:22, fontWeight:600, letterSpacing:'-0.02em', whiteSpace:'nowrap',
                color: matches ? 'var(--lilac-700)' : 'var(--ink)',
                opacity: matches ? 1 : (i % 3 === 0 ? 0.85 : 0.32),
                textDecoration: matches ? 'underline' : 'none',
                textUnderlineOffset: 6,
                textDecorationColor: 'var(--chart-300)',
                textDecorationThickness: 3,
              }}>
                {t}
                <span style={{ color:'var(--lilac-400)' }}>·</span>
              </div>
            );
          })}
        </div>
      </div>
    </section>
  );
}

/* ============== FILMSTRIP ============== */
function FilmStripOwners({ config, onSwitch }) {
  const steps = React.useMemo(() => config ? buildOwnerSteps(config) : buildOwnerSteps({
    name:'your trade', atlas:{ label:'property', value:'—' }, fields:[], arTags:[], qualifyChecks:[]
  }), [config && config.name]);

  const [step, setStep] = React.useState(0);
  const [progress, setProgress] = React.useState(0);
  const sectionRefs = React.useRef([]);

  // Drag/drop state for the fields scene
  const [placedFields, setPlacedFields] = React.useState(null);
  React.useEffect(() => { setPlacedFields(null); }, [config && config.name]);

  React.useEffect(() => {
    const onScroll = () => {
      const vCenter = window.scrollY + window.innerHeight / 2;
      let active = 0, prog = 0;
      sectionRefs.current.forEach((el, i) => {
        if (!el) return;
        const rect = el.getBoundingClientRect();
        const top = rect.top + window.scrollY;
        const bot = top + rect.height;
        if (vCenter >= top && vCenter < bot) {
          active = i;
          prog = (vCenter - top) / rect.height;
        }
      });
      setStep(active);
      setProgress(prog);
    };
    onScroll();
    window.addEventListener('scroll', onScroll, { passive:true });
    window.addEventListener('resize', onScroll);
    return () => {
      window.removeEventListener('scroll', onScroll);
      window.removeEventListener('resize', onScroll);
    };
  }, []);

  const renderScene = () => {
    const id = steps[step].id;
    if (id === 'configured') return <SceneConfigured progress={progress} config={config} onSwitch={onSwitch}/>;
    if (id === 'satellite')  return <SceneSatellite  progress={progress} config={config}/>;
    if (id === 'ar')         return <SceneAR         progress={progress} config={config}/>;
    if (id === 'fields')     return <SceneFields     progress={progress} config={config}
        placedIds={placedFields}
        onDrop={(fid) => setPlacedFields(prev => {
          const catalog = (config && config.fields) || [];
          const base = prev ?? catalog.slice(0, Math.floor(progress * catalog.length * 1.4)).map(f => f.id);
          if (base.includes(fid)) return base;
          return [...base, fid];
        })}
        onRemove={(fid) => setPlacedFields(prev => {
          const catalog = (config && config.fields) || [];
          const base = prev ?? catalog.slice(0, Math.floor(progress * catalog.length * 1.4)).map(f => f.id);
          return base.filter(x => x !== fid);
        })}
      />;
    if (id === 'qualify')    return <SceneQualify  progress={progress} config={config}/>;
    if (id === 'estimate')   return <SceneEstimate progress={progress} config={config}/>;
    if (id === 'stack')      return <SceneStack    progress={progress} config={config}/>;
    return null;
  };

  const glowColor = ['configured','satellite','estimate'].includes(steps[step].id)
    ? 'var(--chart-200)' : 'var(--lilac-200)';

  return (
    <section style={{ position:'relative', background:'#fff' }}>
      <div style={{ position:'sticky', top:60, zIndex:30, background:'rgba(255,255,255,0.85)', backdropFilter:'blur(20px)', borderBottom:'1px solid var(--line-2)' }}>
        <div style={{ maxWidth:1180, margin:'0 auto', display:'flex', alignItems:'center', gap:12, padding:'10px 56px' }}>
          <div style={{ fontSize:10, fontWeight:700, letterSpacing:'0.14em', color:'var(--mute-1)' }}>SCROLL TOUR</div>
          {config && (
            <div style={{ fontSize:10, fontWeight:700, letterSpacing:'0.06em', color:'var(--lilac-700)', padding:'3px 8px', borderRadius:99, background:'var(--lilac-100)' }}>{config.name.toUpperCase()}</div>
          )}
          <div style={{ flex:1, display:'flex', gap:3 }}>
            {steps.map((s, i) => (
              <div key={s.id} style={{ flex:1, height:4, borderRadius:99, background: i<=step ? 'var(--ink)' : 'var(--paper-3)', transition:'background 0.3s' }}/>
            ))}
          </div>
          <div style={{ fontSize:10, fontFamily:'var(--font-mono)', color:'var(--mute-1)' }}>{String(step+1).padStart(2,'0')}/{String(steps.length).padStart(2,'0')}</div>
        </div>
      </div>

      <div className="fo-filmstrip-grid" style={{ display:'grid', gridTemplateColumns:'1fr 1fr', alignItems:'flex-start', maxWidth:1180, margin:'0 auto', position:'relative' }}>
        <div>
          {steps.map((s, i) => (
            <div key={s.id} ref={el => sectionRefs.current[i] = el} style={{ minHeight: '48vh', display:'flex', alignItems:'center', padding:'24px 60px 24px 56px' }}>
              <OwnerScrollPanel s={s} idx={i} active={i === step} config={config}/>
            </div>
          ))}
        </div>
        <div className="fo-filmstrip-phone" style={{ position:'sticky', top:120, height:'calc(100vh - 140px)', display:'flex', alignItems:'center', justifyContent:'center' }}>
          <div style={{ position:'absolute', inset:'-40px', background:`radial-gradient(circle at center, ${glowColor} 0%, transparent 65%)`, filter:'blur(50px)', transition:'background 0.6s' }}/>
          <Phone width={340} height={700} style={{ position:'relative' }}>
            <OwnerLivePhone step={step} steps={steps} sceneEl={renderScene()} config={config}/>
          </Phone>
          <div style={{ position:'absolute', right:18, top:'50%', transform:'translateY(-50%)', display:'flex', flexDirection:'column', gap:5 }}>
            {steps.map((_, i) => (
              <div key={i} style={{ width:3, height: i===step ? 22 : 10, borderRadius:99, background: i<=step ? 'var(--ink)' : 'rgba(12,14,16,0.12)', transition:'all 0.3s' }}/>
            ))}
          </div>
        </div>
      </div>
    </section>
  );
}

function OwnerScrollPanel({ s, idx, active, config }) {
  return (
    <div style={{ maxWidth:460, opacity: active ? 1 : 0.32, transform: active ? 'translateY(0)' : 'translateY(20px)', transition:'all 0.5s ease' }}>
      <div style={{ display:'flex', alignItems:'center', gap:10 }}>
        <div className="eyebrow" style={{ color:'var(--lilac-700)' }}>{s.eyebrow}</div>
        <div style={{ flex:1, height:1, background:'var(--line)' }}/>
      </div>
      <h2 className="display" style={{ fontSize:64, fontWeight:500, margin:'18px 0 0', letterSpacing:'-0.045em', lineHeight:0.98 }}>{s.title}</h2>
      <p style={{ fontSize:17, color:'var(--mute-1)', lineHeight:1.55, marginTop:24 }}>{s.body}</p>
      {active && idx === 3 && (
        <div style={{ marginTop:22, padding:'10px 14px', background:'var(--lilac-100)', color:'var(--lilac-800)', borderRadius:12, fontSize:12.5, display:'flex', alignItems:'center', gap:8 }}>
          <span style={{ fontSize:14 }}>👆</span>
          <span>Drag the lilac chips into the form on the phone.</span>
        </div>
      )}
      {active && idx === 5 && config && (
        <div style={{ marginTop:22, padding:'10px 14px', background:'var(--chart-100)', color:'var(--chart-900)', borderRadius:12, fontSize:12.5, display:'flex', alignItems:'center', gap:8 }}>
          <span style={{ fontSize:14 }}>📈</span>
          <span>This quote priced live with weather, labor &amp; permit data — see the next section.</span>
        </div>
      )}
    </div>
  );
}

function OwnerLivePhone({ step, steps, sceneEl, config }) {
  return (
    <div style={{ position:'absolute', inset:0, paddingTop:54, background:'#fff', display:'flex', flexDirection:'column' }}>
      <div style={{ padding:'6px 18px 10px', display:'flex', alignItems:'center', justifyContent:'space-between' }}>
        <div style={{ display:'flex', alignItems:'center', gap:7 }}>
          <Logo size={26}/>
          <Wordmark size={15}/>
          {config && <span style={{ fontSize:9, fontWeight:700, padding:'2px 6px', borderRadius:5, background:'var(--lilac-100)', color:'var(--lilac-800)', letterSpacing:'0.06em', marginLeft:2, maxWidth:90, overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap' }}>{config.name.toUpperCase()}</span>}
        </div>
        <div style={{ display:'flex', alignItems:'center', gap:5, fontSize:10, color:'var(--mute-1)' }}>
          <IconPin size={11}/> Pine St
        </div>
      </div>
      <div style={{ display:'flex', gap:3, padding:'0 18px 12px' }}>
        {steps.map((_, i) => (
          <div key={i} style={{ flex:1, height:3, borderRadius:99, background: i<=step ? 'var(--ink)' : 'rgba(12,14,16,0.1)', transition:'background 0.3s' }}/>
        ))}
      </div>
      <div style={{ flex:1, padding:'0 18px 18px', overflow:'hidden' }}>
        {sceneEl}
      </div>
    </div>
  );
}

/* ============== PRICE INTELLIGENCE ============== */
const PRICE_SIGNALS = [
  { id:'yourjobs',    label:'Your job history',        sub:'18 mo · 1,420 closed jobs', icon:'▲',  delta:'-2%',  reason:'You win 64% under this price range here' },
  { id:'yourbook',    label:'Your price book',         sub:'Margins + tiers · you set',  icon:'◈',  delta:'+0%',  reason:'Margin floor protected · 32%' },
  { id:'weather',     label:'Weather APIs',            sub:'NWS · forecast · risk',     icon:'☁︎',  delta:'+4%',  reason:'Rain risk Tue–Thu' },
  { id:'labor',       label:'Local labor shortages',   sub:'BLS · prevailing wage',     icon:'◔',   delta:'+6%',  reason:'Tight crew supply' },
  { id:'storm',       label:'Storm activity',          sub:'NOAA · hail · wind events', icon:'◇',   delta:'+11%', reason:'Hail event 8 days ago' },
  { id:'material',    label:'Material pricing',        sub:'Live distributor feeds',    icon:'❖',  delta:'+2%',  reason:'Asphalt up 2.1% this wk' },
  { id:'seasonality', label:'Seasonality',             sub:'7-yr trade signal',         icon:'❍',  delta:'+3%',  reason:'Pre-summer demand curve' },
  { id:'urgency',     label:'Urgency',                 sub:'Lead-stated timeline',      icon:'!',   delta:'+5%',  reason:'Same-week install' },
  { id:'affluence',   label:'Neighborhood affluence',  sub:'Census · AVM blend',         icon:'★',  delta:'+8%',  reason:'Top-quartile zip' },
  { id:'crew',        label:'Crew availability',       sub:'Your live dispatch board',  icon:'◐',  delta:'+0%',  reason:'Capacity normal' },
  { id:'close',       label:'Historical close rates',  sub:'Your 18-mo win/loss',       icon:'◗',  delta:'-3%',  reason:'You win more under-bid here' },
  { id:'insurance',   label:'Insurance payout data',   sub:'Xactimate ranges',          icon:'§',   delta:'+12%', reason:'Carrier paid 1.12× last 90d' },
  { id:'value',       label:'Property value',          sub:'AVM · sale comps',          icon:'◊',  delta:'+4%',  reason:'$680k AVM · move-up market' },
  { id:'satellite',   label:'Satellite imagery',       sub:'Freshness 6 days',          icon:'◉',  delta:'+0%',  reason:'Roof condition score: 38/100' },
  { id:'permit',      label:'Permit databases',        sub:'AHJ · prior work',          icon:'◫',  delta:'+2%',  reason:'Permit avg + 5 days local' },
];

function PriceIntelligence({ config }) {
  const [active, setActive] = React.useState('yourjobs');
  const sel = PRICE_SIGNALS.find(s => s.id === active);
  const base = (config && config.total) || 16395;
  // multiplier — just for display drama
  const mults = { yourjobs: 0.98, yourbook: 1.00, storm: 1.11, insurance: 1.12, affluence: 1.08, close: 0.97, weather: 1.04, labor: 1.06, material: 1.02, seasonality: 1.03, urgency: 1.05, crew: 1.00, value: 1.04, satellite: 1.00, permit: 1.02 };
  const mult = mults[active] || 1.04;
  const adjusted = Math.round(base * mult);
  return (
    <section style={{ padding:'130px 56px', background:'var(--ink)', color:'#fff', position:'relative', overflow:'hidden' }}>
      <div style={{ position:'absolute', top:-200, left:-150, width:500, height:500, borderRadius:'50%', background:'radial-gradient(circle, var(--lilac-700) 0%, transparent 60%)', opacity:.4, filter:'blur(60px)' }}/>
      <div style={{ position:'absolute', bottom:-200, right:-150, width:500, height:500, borderRadius:'50%', background:'radial-gradient(circle, var(--chart-700) 0%, transparent 60%)', opacity:.3, filter:'blur(60px)' }}/>
      <div style={{ maxWidth:1180, margin:'0 auto', position:'relative' }}>
        <div className="fo-pi-grid" style={{ display:'grid', gridTemplateColumns:'1.1fr 1fr', gap:60, alignItems:'flex-start' }}>
          <div>
            <div className="eyebrow" style={{ color:'var(--chart-300)' }}>Price intelligence</div>
            <h2 className="display" style={{ fontSize:84, fontWeight:500, letterSpacing:'-0.05em', lineHeight:0.92, margin:'18px 0 0' }}>
              Priced against your <span className="serif-it" style={{ color:'var(--chart-300)' }}>jobs</span>,<br/>your <span className="serif-it" style={{ color:'var(--lilac-300)' }}>book</span>, and the world.
            </h2>
            <p style={{ fontSize:17, color:'rgba(255,255,255,0.7)', marginTop:26, maxWidth:480, lineHeight:1.55 }}>
              The engine doesn't pick a number from a spreadsheet. It starts from <strong style={{ color:'#fff' }}>your 18 months of closed jobs</strong> and <strong style={{ color:'#fff' }}>your price book</strong>, then blends in weather, labor, storms, insurance payouts, and a dozen other live signals — to price each {config ? config.name.toLowerCase() : 'job'} for max win-rate at your margin floor.
            </p>
            <div style={{ marginTop:30, padding:'20px 22px', background:'rgba(255,255,255,0.04)', border:'1px solid rgba(255,255,255,0.1)', borderRadius:18, backdropFilter:'blur(20px)' }}>
              <div style={{ fontSize:11, color:'rgba(255,255,255,0.5)', fontWeight:600, letterSpacing:'0.12em', textTransform:'uppercase' }}>This quote · live</div>
              <div style={{ display:'flex', alignItems:'baseline', gap:12, marginTop:8 }}>
                <span className="display" style={{ fontSize:56, fontWeight:600, letterSpacing:'-0.04em', color:'var(--chart-300)', lineHeight:1 }}>${adjusted.toLocaleString()}</span>
                <span style={{ fontSize:14, color:'rgba(255,255,255,0.55)' }}>was ${base.toLocaleString()}</span>
              </div>
              <div style={{ marginTop:14, fontSize:13, color:'rgba(255,255,255,0.85)', display:'flex', alignItems:'center', gap:10, padding:'10px 14px', background:'rgba(196,240,0,0.08)', borderRadius:10, border:'1px solid rgba(196,240,0,0.18)' }}>
                <span style={{ color:'var(--chart-300)', fontWeight:700, fontFamily:'var(--font-mono)', fontSize:13 }}>{sel.delta}</span>
                <span>·</span>
                <span style={{ fontWeight:600 }}>{sel.label}</span>
                <span style={{ color:'rgba(255,255,255,0.55)' }}>— {sel.reason}</span>
              </div>
              <div style={{ marginTop:10, fontSize:10.5, color:'rgba(255,255,255,0.4)', fontFamily:'var(--font-mono)' }}>
                Click any signal → see how it moved the price.
              </div>
            </div>
          </div>
          {/* Right: signal grid */}
          <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:8 }}>
            {PRICE_SIGNALS.map(s => {
              const isActive = s.id === active;
              const positive = s.delta.startsWith('+') && s.delta !== '+0%';
              return (
                <div key={s.id} onClick={() => setActive(s.id)} style={{
                  background: isActive ? 'var(--chart-300)' : 'rgba(255,255,255,0.04)',
                  color: isActive ? 'var(--ink)' : '#fff',
                  border: '1px solid ' + (isActive ? 'transparent' : 'rgba(255,255,255,0.10)'),
                  borderRadius:14, padding:'14px 14px', cursor:'pointer', transition:'all 0.2s',
                  boxShadow: isActive ? '0 12px 40px rgba(196,240,0,0.25)' : 'none',
                }}>
                  <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center' }}>
                    <span style={{ fontSize:18, fontFamily:'var(--font-display)', fontWeight:700 }}>{s.icon}</span>
                    <span style={{ fontFamily:'var(--font-mono)', fontSize:11, fontWeight:700, color: isActive ? 'var(--ink)' : (positive ? 'var(--chart-300)' : '#ff8a65') }}>{s.delta}</span>
                  </div>
                  <div style={{ fontSize:12.5, fontWeight:600, marginTop:10, lineHeight:1.2 }}>{s.label}</div>
                  <div style={{ fontSize:10, color: isActive ? 'rgba(12,14,16,0.55)' : 'rgba(255,255,255,0.45)', marginTop:3, fontFamily:'var(--font-mono)' }}>{s.sub}</div>
                </div>
              );
            })}
          </div>
        </div>
      </div>
    </section>
  );
}

/* ============== BUILT FOR ============== */
function BuiltForOwners({ config }) {
  const trade = config ? config.name.toLowerCase() : 'trade';
  const cards = [
    {
      tag:'For the owner',
      title:<>You stay the <span className="serif-it" style={{color:'var(--lilac-600)'}}>owner.</span></>,
      body:`No more sitting in the truck pricing change orders at 9pm. The system writes the ${trade} quote, your name is on the line, your margins stay yours.`,
      icon:<IconShield size={20}/>,
    },
    {
      tag:'For the office',
      title:<>One <span className="serif-it" style={{color:'var(--lilac-600)'}}>fewer</span> dispatcher.</>,
      body:`The system handles intake, measures from satellite, tags from AR, and prices live. CSR work that used to take three people now takes one — focused on the warm ones.`,
      icon:<IconUser size={20}/>,
    },
    {
      tag:'For the crew',
      title:<>They show up to <span className="serif-it" style={{color:'var(--lilac-600)'}}>signed</span> work.</>,
      body:`Crew gets a job packet with photos, measurements, materials list, gate code. No surprises on the property, no callbacks to the office.`,
      icon:<IconHome size={20}/>,
    },
  ];
  return (
    <section style={{ padding:'140px 56px', background:'#fff' }}>
      <div style={{ maxWidth:1180, margin:'0 auto' }}>
        <div style={{ textAlign:'center', marginBottom:60 }}>
          <div className="eyebrow" style={{ color:'var(--lilac-700)' }}>Built for the whole org</div>
          <h2 className="display" style={{ fontSize:76, fontWeight:500, letterSpacing:'-0.045em', lineHeight:0.96, margin:'14px 0 0' }}>
            One install.<br/>Every <span className="serif-it" style={{ color:'var(--lilac-700)' }}>seat</span> better.
          </h2>
        </div>
        <div className="fo-cards-grid" style={{ display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap:18 }}>
          {cards.map((c,i)=>(
            <div key={i} style={{ background: i===1 ? 'var(--lilac-50)' : 'var(--paper-2)', borderRadius:28, padding:'34px 30px', border:'1px solid var(--line-2)' }}>
              <div style={{ width:46, height:46, borderRadius:13, background: i===1? 'var(--lilac-200)':'#fff', display:'flex', alignItems:'center', justifyContent:'center', color: i===1? 'var(--lilac-800)':'var(--ink)' }}>
                {c.icon}
              </div>
              <div className="eyebrow" style={{ color:'var(--mute-1)', marginTop:24 }}>{c.tag}</div>
              <h3 className="display" style={{ fontSize:30, fontWeight:600, letterSpacing:'-0.035em', lineHeight:1.05, marginTop:8 }}>{c.title}</h3>
              <p style={{ fontSize:14.5, color:'var(--mute-1)', lineHeight:1.55, marginTop:14 }}>{c.body}</p>
            </div>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ============== CTA ============== */
function CTAOwners({ config }) {
  const trade = config ? config.name : 'home services';
  return (
    <section style={{ padding:'60px 0 0', background:'var(--ink)', color:'#fff', position:'relative', overflow:'hidden' }}>
      {/* Same animated mesh bg as the top hero */}
      <HeroGradient/>
      <div className="bg-grid" style={{ position:'absolute', inset:0, opacity:0.16, mixBlendMode:'screen' }}/>

      {/* TOP LIVE BAR */}
      <div style={{ position:'relative', padding:'24px 56px 0', display:'flex', justifyContent:'space-between', alignItems:'flex-start' }}>
        <a href="/onboarding" style={{ display:'inline-flex', alignItems:'center', gap:9, padding:'7px 14px', background:'rgba(255,255,255,0.08)', border:'1px solid rgba(255,255,255,0.14)', borderRadius:99, backdropFilter:'blur(20px)', fontSize:12.5, fontWeight:500, color:'rgba(255,255,255,0.85)', textDecoration:'none' }}>
          <span style={{ width:7, height:7, borderRadius:99, background:'var(--chart-300)' }} className="pulse-soft"/>
          {config ? <>Start onboarding · <strong style={{ color:'#fff', fontWeight:700 }}>{trade}</strong></> : <>Start onboarding</>}
        </a>
      </div>

      {/* MEGA HEADLINE */}
      <div className="fo-cta-head-wrap" style={{ position:'relative', padding:'80px 56px 24px' }}>
        <h2 className="display fo-cta-h2" style={{ fontSize:188, fontWeight:500, margin:0, letterSpacing:'-0.065em', lineHeight:0.86, color:'#fff' }}>
          Stop <span className="serif-it" style={{ color:'var(--chart-300)', textShadow:'0 0 80px rgba(196,240,0,0.5)' }}>sending</span>.<br/>
          Start <span className="serif-it" style={{ color:'var(--lilac-300)', textShadow:'0 0 80px rgba(169,138,255,0.5)' }}>closing</span>.
        </h2>
      </div>

      <div className="fo-cta-grid" style={{ position:'relative', padding:'30px 56px 100px', display:'grid', gridTemplateColumns:'1.05fr 1fr', gap:80, alignItems:'flex-start' }}>
        <div>
          <p style={{ fontSize:21, color:'rgba(255,255,255,0.7)', lineHeight:1.5, maxWidth:540, margin:0 }}>
            One 20-minute call. We measure your last {trade.toLowerCase()} job from satellite while we talk. You walk out with three quotes priced live against your zip — no slide deck, no upsell.
          </p>

          <div style={{ marginTop:46, display:'grid', gridTemplateColumns:'1fr 1fr', gap:20, maxWidth:540 }}>
            {[
              { k:'20-minute call',   v:'We price a real job together' },
              { k:'2-week install',   v:'From call to signed jobs' },
              { k:'No SDRs',         v:'Founder picks up the phone' },
              { k:'We use it too',   v:'Built on our own operations' },
            ].map((it, i) => (
              <div key={i} style={{ paddingTop:18, borderTop:'1px solid rgba(255,255,255,0.15)' }}>
                <div style={{ fontSize:11, fontWeight:700, letterSpacing:'0.14em', color:'var(--chart-300)', textTransform:'uppercase' }}>{it.k}</div>
                <div style={{ fontSize:17, fontWeight:600, color:'#fff', marginTop:5, fontFamily:'var(--font-display)', letterSpacing:'-0.02em' }}>{it.v}</div>
              </div>
            ))}
          </div>

          <div style={{ marginTop:40, padding:'18px 22px', background:'rgba(255,255,255,0.04)', border:'1px solid rgba(255,255,255,0.1)', borderRadius:16 }}>
            <div className="eyebrow" style={{ color:'var(--chart-300)' }}>How it works</div>
            <div style={{ marginTop:10, fontSize:14, color:'rgba(255,255,255,0.8)', lineHeight:1.5 }}>
              You apply. We talk for 20 minutes. If you're a fit, we install the system on your operation in two weeks. Real humans, real install — not a self-serve signup.
            </div>
          </div>
        </div>

        {/* Application form (glass) */}
        <div style={{ background:'rgba(255,255,255,0.06)', border:'1px solid rgba(255,255,255,0.14)', borderRadius:28, padding:34, backdropFilter:'blur(28px) saturate(160%)', boxShadow:'0 40px 100px rgba(0,0,0,0.5), inset 0 1px 0 rgba(255,255,255,0.12)' }}>
          <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between' }}>
            <div className="eyebrow" style={{ color:'var(--chart-300)' }}>Apply for install</div>
            <span style={{ fontSize:10, fontFamily:'var(--font-mono)', color:'rgba(255,255,255,0.45)' }}>Step 1 of 1</span>
          </div>
          <h3 className="display" style={{ fontSize:34, fontWeight:600, letterSpacing:'-0.035em', lineHeight:1.05, marginTop:10, color:'#fff' }}>
            Start <span className="serif-it" style={{ color:'var(--chart-300)' }}>onboarding.</span>
          </h3>
          <CTAForm config={config} trade={trade}/>
          <div style={{ marginTop:12, fontSize:11.5, color:'rgba(255,255,255,0.5)', textAlign:'center', display:'flex', alignItems:'center', justifyContent:'center', gap:8 }}>
            <span style={{ width:5, height:5, borderRadius:99, background:'var(--chart-300)' }} className="pulse-soft"/>
            You'll hear back within 24 hours. Real human.
          </div>
        </div>
      </div>
    </section>
  );
}

function CTAForm({ config, trade }) {
  const [sending, setSending] = React.useState(false);
  const handleSubmit = async (e) => {
    e.preventDefault();
    setSending(true);
    const fd = new FormData(e.currentTarget);
    try {
      await fetch('/api/send-onboarding', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          type: 'apply',
          company: fd.get('company'),
          trade: fd.get('trade') || trade,
          crew: fd.get('crew'),
          email: fd.get('email'),
        }),
      });
    } catch {}
    const tradeVal = fd.get('trade') || trade;
    window.location.href = '/onboarding' + (tradeVal ? '?s=' + encodeURIComponent(tradeVal) : '');
  };
  return (
    <form onSubmit={handleSubmit} style={{ marginTop:24, display:'flex', flexDirection:'column', gap:11 }}>
      <FormField name="company" label="Company" placeholder="Cardinal Roofing"/>
      <FormField name="trade" label="Trade" placeholder={trade} preset={config ? config.name : ''}/>
      <FormField name="crew" label="Crew size" select options={['1–3 techs','4–8 techs','9–15 techs','16+ techs']}/>
      <FormField name="email" label="Work email" placeholder="you@cardinalroof.com"/>
      <button type="submit" disabled={sending} style={{ marginTop:11, width:'100%', background:'var(--chart-300)', color:'var(--ink)', border:0, padding:'16px', borderRadius:14, fontFamily:'var(--font-display)', fontWeight:700, fontSize:16, cursor: sending ? 'default' : 'pointer', opacity: sending ? 0.75 : 1, letterSpacing:'-0.01em', display:'flex', alignItems:'center', justifyContent:'center', gap:8, boxShadow:'0 18px 40px rgba(196,240,0,0.35)' }}>
        {sending ? 'Sending…' : <> Start onboarding <IconArrow size={15}/></>}
      </button>
    </form>
  );
}

function FormField({ name, label, placeholder, select, options, preset }) {
  return (
    <label style={{ display:'flex', flexDirection:'column', gap:5 }}>
      <span style={{ fontSize:11, fontWeight:600, color:'rgba(255,255,255,0.7)', letterSpacing:'0.06em', textTransform:'uppercase' }}>{label}</span>
      {select ? (
        <select name={name} style={{ background:'rgba(255,255,255,0.06)', border:'1px solid rgba(255,255,255,0.14)', color:'#fff', padding:'11px 14px', borderRadius:12, fontFamily:'var(--font-body)', fontSize:14, outline:0 }}>
          {options.map(o => <option key={o} value={o} style={{ color:'#000' }}>{o}</option>)}
        </select>
      ) : (
        <input name={name} defaultValue={preset || ''} placeholder={placeholder} style={{ background:'rgba(255,255,255,0.06)', border:'1px solid rgba(255,255,255,0.14)', color:'#fff', padding:'11px 14px', borderRadius:12, fontFamily:'var(--font-body)', fontSize:14, outline:0 }}/>
      )}
    </label>
  );
}

/* ============== FOOTER ============== */
function FooterOwners() {
  return (
    <footer style={{ background:'var(--ink)', color:'#fff', padding:'40px 56px 36px', borderTop:'1px solid rgba(255,255,255,0.1)' }}>
      <div style={{ maxWidth:1180, margin:'0 auto', display:'flex', justifyContent:'space-between', alignItems:'center', flexWrap:'wrap', gap:24 }}>
        <div style={{ display:'flex', alignItems:'center', gap:10 }}>
          <Logo size={32}/>
          <Wordmark size={18} color="#fff"/>
          <span style={{ fontSize:11, color:'rgba(255,255,255,0.5)', marginLeft:6 }}>thehomeproai.com</span>
        </div>
        <div style={{ display:'flex', gap:24, fontSize:13, color:'rgba(255,255,255,0.7)' }}>
          {['Estimate engine','Industries','Apply','Terms'].map(l=><a key={l} href="#" style={{ color:'inherit', textDecoration:'none' }}>{l}</a>)}
        </div>
        <div style={{ fontSize:12, color:'rgba(255,255,255,0.5)' }}>© 2026 HomePro · For operators</div>
      </div>
    </footer>
  );
}

Object.assign(window, { ForOwners });
