// Service picker — full-screen overlay where business owner picks their trade.
// 170+ services across 21 categories, with search, featured trades, and live preview.

function ServicePicker({ open, onPick, onClose, current }) {
  const [query, setQuery] = useState('');
  const [cat, setCat] = useState('all');
  const [hover, setHover] = useState(null);
  const inputRef = useRef(null);

  useEffect(() => {
    if (open && inputRef.current) {
      setTimeout(() => inputRef.current?.focus(), 200);
    }
  }, [open]);

  useEffect(() => {
    if (!open) return;
    const onKey = (e) => {
      if (e.key === 'Escape' && current) onClose && onClose();
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [open, current, onClose]);

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    return SERVICE_LIST.filter(s => {
      if (cat !== 'all' && s.cat !== cat) return false;
      if (!q) return true;
      return s.name.toLowerCase().includes(q);
    });
  }, [query, cat]);

  const grouped = useMemo(() => {
    const g = {};
    filtered.forEach(s => { (g[s.cat] ||= []).push(s); });
    return g;
  }, [filtered]);

  // Featured trades — shown at top when no search/category active
  const FEATURED = ['Roofing','HVAC','Solar Installation','Plumbing','Electrical','Pool Service','Kitchen Remodeling','Painting','Pest Control','Landscaping','Cleaning Services','Tree Service'];

  if (!open) return null;

  const showFeatured = !query && cat === 'all';
  const hoverCfg = hover ? getServiceConfig(hover) : null;

  return (
    <div style={{
      position:'fixed', inset:0, zIndex:200,
      background:'radial-gradient(120% 80% at 50% 0%, rgba(196,240,0,0.18) 0%, transparent 50%), rgba(12,14,16,0.78)',
      backdropFilter:'blur(28px) saturate(140%)',
      display:'flex', alignItems:'flex-start', justifyContent:'center',
      padding:'32px 24px 40px', overflowY:'auto'
    }}>
      <div style={{
        width:'100%', maxWidth:1120, background:'#fff', borderRadius:40,
        boxShadow:'0 60px 140px rgba(12,14,16,0.55), 0 0 0 1px rgba(196,240,0,0.18)',
        overflow:'hidden', position:'relative',
      }}>
        {/* HEADER */}
        <div style={{ position:'relative', padding:'40px 48px 28px',
          background:`
            radial-gradient(500px 300px at 90% -20%, var(--chart-200) 0%, transparent 60%),
            radial-gradient(400px 280px at 10% -10%, var(--lilac-200) 0%, transparent 60%),
            #fff` }}>
          {/* faint dot grid */}
          <div className="bg-grid" style={{ position:'absolute', inset:0, opacity:.15, pointerEvents:'none' }}/>
          <div style={{ position:'relative', display:'flex', justifyContent:'space-between', alignItems:'flex-start', gap:24 }}>
            <div style={{ flex:1 }}>
              <div style={{ display:'flex', alignItems:'center', gap:12, marginBottom:18 }}>
                <Logo size={48}/>
                <div>
                  <Wordmark size={20}/>
                  <div style={{ fontSize:10, fontWeight:700, letterSpacing:'0.16em', color:'var(--mute-1)', marginTop:2, textTransform:'uppercase' }}>Operator install · step 1 of 1</div>
                </div>
              </div>
              <h2 className="display" style={{ fontSize:54, fontWeight:500, margin:0, letterSpacing:'-0.045em', lineHeight:0.96 }}>
                What does your business <span className="serif-it" style={{ color:'var(--lilac-600)' }}>sell?</span>
              </h2>
              <p style={{ fontSize:16, color:'var(--mute-1)', marginTop:12, maxWidth:620, lineHeight:1.5 }}>
                Pick your trade — the estimate engine, AR walkthrough, custom fields, qualifier chat, and price model will reshape around it before you finish reading this sentence.
              </p>
            </div>
            {onClose && current && (
              <button onClick={onClose} style={{ background:'rgba(12,14,16,0.06)', border:0, padding:'9px 16px', borderRadius:99, fontSize:13, fontWeight:600, cursor:'pointer', color:'var(--ink)', fontFamily:'var(--font-body)', display:'flex', alignItems:'center', gap:6 }}>
                Keep {current} <span style={{ color:'var(--mute-2)' }}>×</span>
              </button>
            )}
          </div>
          {/* Search bar */}
          <div style={{ position:'relative', marginTop:28, display:'flex', alignItems:'center', gap:12, background:'#fff', border:'1.5px solid var(--ink)', borderRadius:18, padding:'14px 20px', boxShadow:'0 14px 40px rgba(12,14,16,0.10)' }}>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="var(--ink)" strokeWidth="2" strokeLinecap="round"><circle cx="11" cy="11" r="7"/><path d="m21 21-4-4"/></svg>
            <input
              ref={inputRef}
              value={query}
              onChange={e=>setQuery(e.target.value)}
              placeholder={`Search ${SERVICE_LIST.length}+ trades — try ‘roof’, ‘HVAC’, ‘pool’, ‘emergency’, ‘commercial’…`}
              style={{ flex:1, border:0, outline:0, fontFamily:'var(--font-body)', fontSize:17, color:'var(--ink)' }}
            />
            {query && <button onClick={()=>setQuery('')} style={{ background:'var(--paper-3)', border:0, borderRadius:99, padding:'5px 12px', fontSize:12, cursor:'pointer', color:'var(--mute-1)', fontWeight:600 }}>Clear</button>}
            <kbd style={{ fontFamily:'var(--font-mono)', fontSize:11, color:'var(--mute-2)', background:'var(--paper-3)', padding:'4px 9px', borderRadius:7 }}>⌘K</kbd>
          </div>
        </div>

        {/* BODY */}
        <div style={{ display:'grid', gridTemplateColumns:'220px 1fr 280px', minHeight:560, maxHeight:'calc(100vh - 280px)' }}>
          {/* Categories sidebar */}
          <div style={{ borderRight:'1px solid var(--line-2)', padding:'18px 12px', overflowY:'auto', background:'var(--paper-2)' }}>
            <div className="eyebrow" style={{ color:'var(--mute-1)', padding:'4px 10px 10px' }}>Browse by category</div>
            {SERVICE_CATEGORIES.map(c => {
              const count = c.id === 'all' ? SERVICE_LIST.length : SERVICE_LIST.filter(s => s.cat === c.id).length;
              const active = c.id === cat;
              return (
                <div key={c.id} onClick={()=>setCat(c.id)} style={{
                  padding:'9px 12px', borderRadius:10, cursor:'pointer',
                  display:'flex', alignItems:'center', justifyContent:'space-between',
                  background: active ? 'var(--ink)' : 'transparent',
                  color: active ? 'var(--chart-300)' : 'var(--ink)',
                  fontSize:13, fontWeight: active ? 600 : 500, transition:'all 0.15s',
                  marginBottom:2,
                }}
                onMouseEnter={e => { if(!active) e.currentTarget.style.background = 'var(--paper-3)'; }}
                onMouseLeave={e => { if(!active) e.currentTarget.style.background = 'transparent'; }}
                >
                  <span style={{ display:'flex', alignItems:'center', gap:8 }}>
                    {active && <span style={{ width:5, height:5, borderRadius:99, background:'var(--chart-300)' }} className="pulse-soft"/>}
                    {c.label}
                  </span>
                  <span style={{ fontSize:10, fontFamily:'var(--font-mono)', color: active ? 'rgba(196,240,0,0.7)' : 'var(--mute-2)' }}>{count}</span>
                </div>
              );
            })}
          </div>

          {/* Results */}
          <div style={{ padding:'22px 28px 28px', overflowY:'auto' }}>
            {filtered.length === 0 && (
              <div style={{ padding:'80px 20px', textAlign:'center', color:'var(--mute-1)' }}>
                <div style={{ fontSize:42, marginBottom:8 }}>🔎</div>
                <div style={{ fontSize:17, fontFamily:'var(--font-display)', fontWeight:600, color:'var(--ink)' }}>Nothing matches "{query}"</div>
                <div style={{ marginTop:8, fontSize:13 }}>Try a broader term — or browse a category on the left.</div>
              </div>
            )}

            {showFeatured && (
              <div style={{ marginBottom:24 }}>
                <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:12 }}>
                  <div className="eyebrow" style={{ color:'var(--lilac-700)' }}>Popular trades</div>
                  <span style={{ background:'var(--chart-300)', color:'var(--ink)', padding:'2px 8px', borderRadius:99, fontSize:9, fontWeight:800, letterSpacing:'0.08em' }}>MOST INSTALLED</span>
                  <div style={{ flex:1, height:1, background:'var(--line-2)' }}/>
                </div>
                <div style={{ display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap:8 }}>
                  {FEATURED.map(name => {
                    const s = SERVICE_LIST.find(x => x.name === name);
                    if (!s) return null;
                    return (
                      <FeaturedCard key={s.id} svc={s}
                        isCurrent={current === s.name}
                        onPick={() => onPick(s.name)}
                        onHover={() => setHover(s.name)}
                        onLeave={() => setHover(null)}
                      />
                    );
                  })}
                </div>
              </div>
            )}

            {SERVICE_CATEGORIES.filter(c => c.id !== 'all' && grouped[c.id]).map(c => (
              <div key={c.id} style={{ marginBottom:22 }}>
                <div style={{ display:'flex', alignItems:'center', gap:10, marginBottom:10 }}>
                  <div className="eyebrow" style={{ color:'var(--lilac-700)' }}>{c.label}</div>
                  <div style={{ flex:1, height:1, background:'var(--line-2)' }}/>
                  <div style={{ fontSize:10, fontFamily:'var(--font-mono)', color:'var(--mute-2)' }}>{grouped[c.id].length}</div>
                </div>
                <div style={{ display:'grid', gridTemplateColumns:'repeat(2, 1fr)', gap:5 }}>
                  {grouped[c.id].map(s => {
                    const isCurrent = s.name === current;
                    return (
                      <button key={s.id}
                        onClick={() => onPick(s.name)}
                        onMouseEnter={() => setHover(s.name)}
                        onMouseLeave={() => setHover(null)}
                        style={{
                          textAlign:'left', cursor:'pointer',
                          padding:'10px 14px', borderRadius:10,
                          border: isCurrent ? '1.5px solid var(--ink)' : '1px solid var(--line)',
                          background: isCurrent ? 'var(--chart-100)' : '#fff',
                          fontFamily:'var(--font-body)', fontSize:13, fontWeight:500,
                          color:'var(--ink)', transition:'all 0.15s',
                          display:'flex', alignItems:'center', justifyContent:'space-between', gap:6,
                        }}
                        onMouseOver={e => { if(!isCurrent){ e.currentTarget.style.background = 'var(--paper-3)'; e.currentTarget.style.borderColor = 'var(--ink)'; } }}
                        onMouseOut={e => { if(!isCurrent){ e.currentTarget.style.background = '#fff'; e.currentTarget.style.borderColor = 'var(--line)'; } }}
                      >
                        <span>{s.name}</span>
                        {isCurrent ? <span style={{ fontSize:9, color:'var(--lilac-700)', fontWeight:800, letterSpacing:'0.08em' }}>CURRENT</span>
                                   : <span style={{ fontSize:14, color:'var(--mute-3)' }}>→</span>}
                      </button>
                    );
                  })}
                </div>
              </div>
            ))}
          </div>

          {/* Live preview panel */}
          <PickerPreview cfg={hoverCfg} current={current} onPick={onPick}/>
        </div>

        {/* FOOTER */}
        <div style={{ padding:'16px 48px', background:'var(--paper-2)', borderTop:'1px solid var(--line-2)', display:'flex', justifyContent:'space-between', alignItems:'center' }}>
          <div style={{ fontSize:12, color:'var(--mute-1)' }}>
            <strong style={{ color:'var(--ink)', fontFamily:'var(--font-display)' }}>{filtered.length}</strong> of {SERVICE_LIST.length} trades shown
            {cat !== 'all' && <span> · in <strong style={{ color:'var(--ink)' }}>{SERVICE_CATEGORIES.find(c=>c.id===cat).label}</strong></span>}
          </div>
          <div style={{ fontSize:11, color:'var(--mute-2)', display:'flex', alignItems:'center', gap:14 }}>
            <span style={{ display:'flex', alignItems:'center', gap:5 }}><kbd style={{ fontFamily:'var(--font-mono)', background:'#fff', border:'1px solid var(--line)', padding:'2px 6px', borderRadius:5 }}>↵</kbd> select</span>
            <span style={{ display:'flex', alignItems:'center', gap:5 }}><kbd style={{ fontFamily:'var(--font-mono)', background:'#fff', border:'1px solid var(--line)', padding:'2px 6px', borderRadius:5 }}>esc</kbd> close</span>
            <span style={{ fontFamily:'var(--font-mono)' }}>Don't see yours? Keep typing.</span>
          </div>
        </div>
      </div>
    </div>
  );
}

/* ============== FEATURED TRADE CARD ============== */
function FeaturedCard({ svc, isCurrent, onPick, onHover, onLeave }) {
  const cfg = getServiceConfig(svc.name);
  const ticket = cfg.total > 0 ? `~$${Math.round(cfg.total/100)*100/1000 >= 10 ? Math.round(cfg.total/1000)+'k' : '$'+cfg.total.toLocaleString()}` : '—';
  const niceTicket = cfg.total >= 10000 ? `~$${Math.round(cfg.total/1000)}k` : `~$${cfg.total.toLocaleString()}`;
  return (
    <button
      onClick={onPick}
      onMouseEnter={onHover}
      onMouseLeave={onLeave}
      style={{
        textAlign:'left', cursor:'pointer',
        padding:'14px 14px 12px', borderRadius:14,
        background: isCurrent ? 'var(--ink)' : 'var(--paper-3)',
        color: isCurrent ? '#fff' : 'var(--ink)',
        border: isCurrent ? '1.5px solid var(--ink)' : '1.5px solid transparent',
        fontFamily:'var(--font-body)',
        position:'relative', overflow:'hidden',
        transition:'all 0.2s',
      }}
      onMouseOver={e => { if(!isCurrent){ e.currentTarget.style.background = '#fff'; e.currentTarget.style.borderColor = 'var(--ink)'; e.currentTarget.style.boxShadow = '0 8px 22px rgba(12,14,16,0.10)'; }}}
      onMouseOut={e => { if(!isCurrent){ e.currentTarget.style.background = 'var(--paper-3)'; e.currentTarget.style.borderColor = 'transparent'; e.currentTarget.style.boxShadow = 'none'; }}}
    >
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', gap:8 }}>
        <span className="display" style={{ fontSize:15, fontWeight:600, letterSpacing:'-0.025em', lineHeight:1.1 }}>{svc.name}</span>
        {isCurrent && <span style={{ fontSize:8, fontWeight:800, letterSpacing:'0.08em', background:'var(--chart-300)', color:'var(--ink)', padding:'2px 6px', borderRadius:4 }}>YOURS</span>}
      </div>
      <div style={{ marginTop:10, fontSize:10, color: isCurrent ? 'rgba(255,255,255,0.6)' : 'var(--mute-1)', fontFamily:'var(--font-mono)', display:'flex', gap:10 }}>
        <span>{cfg.fields.length} fields</span>
        <span>·</span>
        <span>{niceTicket} avg</span>
      </div>
    </button>
  );
}

/* ============== PREVIEW PANEL ============== */
function PickerPreview({ cfg, current, onPick }) {
  if (!cfg) {
    return (
      <div style={{ background:'var(--ink)', color:'#fff', padding:'24px 22px', display:'flex', flexDirection:'column', justifyContent:'space-between' }}>
        <div>
          <div className="eyebrow" style={{ color:'var(--chart-300)' }}>Live preview</div>
          <div style={{ marginTop:16, fontSize:15, color:'rgba(255,255,255,0.7)', lineHeight:1.4 }}>
            Hover any trade to see what configures.
          </div>
        </div>
        <div style={{ marginTop:24, padding:'14px 16px', background:'rgba(255,255,255,0.04)', border:'1px dashed rgba(255,255,255,0.18)', borderRadius:12 }}>
          <div style={{ fontSize:10, color:'rgba(255,255,255,0.5)', fontFamily:'var(--font-mono)', letterSpacing:'0.1em', textTransform:'uppercase' }}>What you'll get</div>
          <div style={{ marginTop:10, display:'flex', flexDirection:'column', gap:7, fontSize:12 }}>
            {[
              'Custom estimate fields',
              'AR feature recognition',
              'Atlas satellite measure',
              'Lead qualifier chat',
              'Line-item pricing rules',
              'CRM + calendar sync',
            ].map((l, i) => (
              <div key={i} style={{ display:'flex', alignItems:'center', gap:8, color:'rgba(255,255,255,0.85)' }}>
                <span style={{ width:14, height:14, borderRadius:99, background:'var(--chart-300)', color:'var(--ink)', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0 }}>
                  <IconCheck size={9} stroke="var(--ink)" sw={3}/>
                </span>
                <span>{l}</span>
              </div>
            ))}
          </div>
        </div>
      </div>
    );
  }
  return (
    <div style={{ background:'var(--ink)', color:'#fff', padding:'24px 22px', display:'flex', flexDirection:'column', position:'relative', overflow:'hidden' }}>
      <div style={{ position:'absolute', top:-60, right:-60, width:200, height:200, borderRadius:'50%', background:'var(--lilac-700)', opacity:0.4, filter:'blur(40px)' }}/>
      <div style={{ position:'relative' }}>
        <div className="eyebrow" style={{ color:'var(--chart-300)' }}>Live preview</div>
        <div style={{ marginTop:14 }}>
          <div style={{ fontSize:10, fontWeight:700, letterSpacing:'0.14em', color:'var(--chart-300)' }}>{cfg.catLabel.toUpperCase()}</div>
          <div className="display" style={{ fontSize:24, fontWeight:600, letterSpacing:'-0.03em', lineHeight:1.05, marginTop:2 }}>{cfg.name}</div>
        </div>
        {/* mini stats */}
        <div style={{ marginTop:18, display:'grid', gridTemplateColumns:'1fr 1fr', gap:6 }}>
          {[
            ['Atlas', cfg.atlas.label],
            ['Fields', `${cfg.fields.length}`],
            ['AR tags', `${cfg.arTags.length}`],
            ['Avg quote', cfg.total >= 10000 ? `$${Math.round(cfg.total/1000)}k` : `$${cfg.total.toLocaleString()}`],
          ].map(([l, v], i) => (
            <div key={i} style={{ padding:'8px 10px', background:'rgba(255,255,255,0.06)', borderRadius:9 }}>
              <div style={{ fontSize:9, color:'rgba(255,255,255,0.5)', fontFamily:'var(--font-mono)', letterSpacing:'0.08em', textTransform:'uppercase' }}>{l}</div>
              <div style={{ fontSize:12, fontWeight:600, marginTop:2, color:'#fff', textOverflow:'ellipsis', overflow:'hidden', whiteSpace:'nowrap' }}>{v}</div>
            </div>
          ))}
        </div>
        {/* Field preview */}
        <div style={{ marginTop:14 }}>
          <div style={{ fontSize:9, color:'rgba(255,255,255,0.45)', fontFamily:'var(--font-mono)', letterSpacing:'0.1em', textTransform:'uppercase', marginBottom:6 }}>Custom fields</div>
          <div style={{ display:'flex', flexWrap:'wrap', gap:4 }}>
            {cfg.fields.slice(0, 6).map(f => (
              <span key={f.id} style={{ background:'rgba(196,240,0,0.12)', color:'var(--chart-300)', fontSize:10, padding:'3px 8px', borderRadius:99, fontWeight:600 }}>{f.name}</span>
            ))}
          </div>
        </div>
        {/* Sample line item */}
        <div style={{ marginTop:14, padding:'10px 12px', background:'rgba(255,255,255,0.04)', borderRadius:10 }}>
          <div style={{ fontSize:9, color:'rgba(255,255,255,0.45)', fontFamily:'var(--font-mono)', letterSpacing:'0.1em', textTransform:'uppercase' }}>Top line item</div>
          <div style={{ display:'flex', alignItems:'baseline', justifyContent:'space-between', marginTop:4, fontSize:12 }}>
            <span style={{ color:'rgba(255,255,255,0.85)', overflow:'hidden', textOverflow:'ellipsis', whiteSpace:'nowrap', maxWidth:160 }}>{cfg.lines[0]?.[0] || '—'}</span>
            <span style={{ fontFamily:'var(--font-mono)', color:'var(--chart-300)', fontWeight:700 }}>{cfg.lines[0]?.[1] || '—'}</span>
          </div>
        </div>
      </div>
      <button onClick={() => onPick(cfg.name)} style={{ marginTop:18, background:'var(--chart-300)', color:'var(--ink)', border:0, padding:'12px', borderRadius:12, fontFamily:'var(--font-display)', fontWeight:700, fontSize:13, cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center', gap:6, letterSpacing:'-0.01em' }}>
        Configure for {cfg.name.split(' ')[0]} <IconArrow size={13}/>
      </button>
    </div>
  );
}

Object.assign(window, { ServicePicker });
