// results.jsx — split list+map results view
const Results = ({ filters, onBack, onClaim }) => {
  const [hovered, setHovered] = React.useState(null);
  const [query, setQuery] = React.useState(filters?.query || '');
  const [activeSpec, setActiveSpec] = React.useState(filters?.spec || '');
  const [activeInsurance, setActiveInsurance] = React.useState(filters?.insurance || '');
  const [activeFeature, setActiveFeature] = React.useState('');
  const [radius, setRadius] = React.useState(25);
  const [sort, setSort] = React.useState('relevance');
  const [view, setView] = React.useState('split'); // split | list | map (mobile-ish toggle)
  const [favVer, setFavVer] = React.useState(0); // bump to re-render after toggling a heart
  const handleToggleFav = (id) => { if (typeof toggleFavorite === 'function') { toggleFavorite(id); setFavVer(v=>v+1); } };

  // Log a 'view' card event the first time each card scrolls into the viewport.
  const obsRef = React.useRef(null);
  React.useEffect(() => {
    if (typeof IntersectionObserver === 'undefined' || typeof logCardEvent !== 'function') return;
    obsRef.current = new IntersectionObserver((entries) => {
      entries.forEach(e => {
        if (e.isIntersecting) {
          const pid = e.target.getAttribute('data-pid');
          if (pid) logCardEvent(pid, 'view');
          obsRef.current.unobserve(e.target);
        }
      });
    }, { threshold: 0.35 });
    return () => obsRef.current?.disconnect();
  }, []);
  const registerCard = React.useCallback((el) => { if (el && obsRef.current) obsRef.current.observe(el); }, []);
  const logClick = (id, target) => { if (typeof logCardEvent === 'function') logCardEvent(id, 'click', target); };

  const list = React.useMemo(()=>{
    const source = typeof getMergedProviders === 'function' ? getMergedProviders() : PROVIDERS;
    let l = source.slice();
    const q = query.trim().toLowerCase();
    if (q) {
      l = l.filter(p => {
        const hay = [p.name, p.business, p.photoLabel, p.city, p.state, p.specialty]
          .filter(Boolean).join(' ').toLowerCase();
        return hay.includes(q);
      });
    }
    if (activeSpec) {
      l = l.filter(p =>
        p.specKey === activeSpec ||
        (Array.isArray(p.specKeys) && p.specKeys.includes(activeSpec))
      );
    }
    if (activeInsurance) {
      l = l.filter(p => Array.isArray(p.insurances) && p.insurances.includes(activeInsurance));
    }
    if (activeFeature) {
      l = l.filter(p => Array.isArray(p.tags) && p.tags.includes(activeFeature));
    }
    return l;
  },[query, activeSpec, activeInsurance, activeFeature]);

  return (
    <div className="results-wrap" style={view==='list'?{gridTemplateColumns:'1fr'}:view==='map'?{gridTemplateColumns:'1fr'}:undefined}>
      {/* LIST PANEL */}
      {view!=='map' && (
        <div className="results-list">
          <div className="results-toolbar">
            <div>
              <h3>TMJD specialists</h3>
              <span className="count">{list.length} of {(typeof getMergedProviders==='function'?getMergedProviders():PROVIDERS).length} · sorted by {sort}</span>
            </div>
            <div style={{display:'flex',gap:8,alignItems:'center'}}>
              <button className="btn" onClick={onBack}>← Home</button>
              <select className="btn" value={sort} onChange={e=>setSort(e.target.value)} style={{appearance:'none',paddingRight:24}}>
                <option value="relevance">Relevance</option>
                <option value="distance">Distance</option>
                <option value="rating">Rating</option>
                <option value="reviews">Most reviewed</option>
              </select>
            </div>
          </div>

          {/* free-text search by provider / business name */}
          <div style={{position:'relative', margin:'4px 0 12px'}}>
            <span style={{position:'absolute', left:14, top:'50%', transform:'translateY(-50%)', color:'var(--muted)', pointerEvents:'none'}}>
              <Icon name="search" size={15}/>
            </span>
            <input
              type="search"
              value={query}
              onChange={e=>setQuery(e.target.value)}
              placeholder="Search by provider or clinic name, city, specialty…"
              aria-label="Search providers"
              style={{
                width:'100%', padding:'12px 38px 12px 40px',
                borderRadius:999, border:'1px solid var(--line)', background:'var(--paper)',
                font:'inherit', fontSize:15, color:'var(--ink)', outline:'none',
              }}
            />
            {query && (
              <button
                type="button"
                onClick={()=>setQuery('')}
                aria-label="Clear search"
                style={{position:'absolute', right:12, top:'50%', transform:'translateY(-50%)', color:'var(--muted)', background:'none', border:0, fontSize:18, cursor:'pointer', lineHeight:1}}
              >×</button>
            )}
          </div>

          {/* specialty filter dropdown (modeled on the insurance dropdown) */}
          <div className="insurance-filter-row">
            <label htmlFor="results-specialty">Specialty:</label>
            <select
              id="results-specialty"
              className="insurance-filter-select"
              value={activeSpec}
              onChange={e => setActiveSpec(e.target.value)}
            >
              <option value="">All specialties</option>
              {SPECIALTIES.map(s => (
                <option key={s.key} value={s.key}>{s.label} ({s.count})</option>
              ))}
            </select>
            {activeSpec && (
              <button
                type="button"
                className="insurance-filter-clear"
                onClick={() => setActiveSpec('')}
                aria-label="Clear specialty filter"
              >Clear</button>
            )}
          </div>

          {/* insurance filter row */}
          <div className="insurance-filter-row">
            <label htmlFor="results-insurance">Insurance:</label>
            <select
              id="results-insurance"
              className="insurance-filter-select"
              value={activeInsurance}
              onChange={e => setActiveInsurance(e.target.value)}
            >
              <option value="">All insurances</option>
              {(typeof INSURANCE_OPTIONS !== 'undefined' ? INSURANCE_OPTIONS : []).map(name => (
                <option key={name} value={name}>{name}</option>
              ))}
            </select>
            {activeInsurance && (
              <button
                type="button"
                className="insurance-filter-clear"
                onClick={() => setActiveInsurance('')}
                aria-label="Clear insurance filter"
              >Clear</button>
            )}
          </div>

          {/* feature filter dropdown */}
          <div className="insurance-filter-row" style={{borderBottom:0,marginBottom:6}}>
            <label htmlFor="results-feature">Feature:</label>
            <select
              id="results-feature"
              className="insurance-filter-select"
              value={activeFeature}
              onChange={e => setActiveFeature(e.target.value)}
            >
              <option value="">Any feature</option>
              {['Accepting patients','Telehealth','Cash-pay','Botox','Manual therapy','Splints','Same-week'].map(f => (
                <option key={f} value={f}>{f}</option>
              ))}
            </select>
            {activeFeature && (
              <button
                type="button"
                className="insurance-filter-clear"
                onClick={() => setActiveFeature('')}
                aria-label="Clear feature filter"
              >Clear</button>
            )}
          </div>

          {list.map(p=>{
            const isPremium = p.status === 'premium' || !!p.premium;
            const isClaimed = isPremium || p.status === 'claimed' || p.claimed;
            const businessName = p.business || p.photoLabel;
            const favored = typeof isFavorite === 'function' ? isFavorite(p.id) : false;
            return (
              <article
                key={p.id}
                ref={registerCard}
                data-pid={p.id}
                className={`pcard ${isPremium ? 'pcard-premium' : ''}`}
                onMouseEnter={()=>setHovered(p.id)}
                onMouseLeave={()=>setHovered(null)}
                style={{position:'relative'}}
              >
                <button
                  type="button"
                  className="pcard-fav"
                  aria-label={favored ? 'Remove from favorites' : 'Add to favorites'}
                  aria-pressed={favored}
                  title={favored ? 'Remove from favorites' : 'Add to favorites'}
                  onClick={(e)=>{ e.stopPropagation(); handleToggleFav(p.id); }}
                  style={{
                    position:'absolute', top:8, left:8, zIndex:2,
                    width:28, height:28, padding:0, border:'none', cursor:'pointer',
                    display:'flex', alignItems:'center', justifyContent:'center',
                    borderRadius:'50%', background:'rgba(255,255,255,.92)',
                    boxShadow:'0 1px 3px rgba(0,0,0,.18)',
                    color: favored ? '#e25555' : 'var(--muted)',
                  }}
                >
                  <Icon name={favored ? 'heart-fill' : 'heart'} size={14}/>
                </button>
                <Placeholder label={p.photoLabel} image={p.photo} className="pcard-photo" style={{borderRadius:12}}/>
                <div className="pcard-mid">
                  <div className="pcard-head">
                    <div>
                      <h4>
                        {p.name}
                        {isPremium && <span className="premium-badge" title="Premium provider">★ Premium</span>}
                      </h4>
                      <div className="credentials">
                        {isClaimed ? p.credentials : businessName}
                      </div>
                    </div>
                  </div>
                  {isClaimed ? (
                    <>
                      <p className="pcard-bio">{p.bio}</p>
                      <div className="pcard-tags">
                        <span className="pill" style={{background:'var(--ink)',color:'var(--paper)',borderColor:'var(--ink)'}}>{p.specialty}</span>
                        {p.peerSavedCount > 0 && (
                          <span className="pill" style={{background:'var(--accent)',borderColor:'var(--accent)',color:'var(--ink)'}} title="Saved by other TMJD providers as a referral partner">
                            ◇ Saved by {p.peerSavedCount} provider{p.peerSavedCount===1?'':'s'}
                          </span>
                        )}
                        {p.favoriteCount > 0 && (
                          <span className="pill" style={{background:'transparent',borderColor:'#e25555',color:'#c23b3b'}} title="Patients who hearted this listing">
                            ♥ {p.favoriteCount}
                          </span>
                        )}
                        {(p.tags || []).map(t=><span key={t} className="pill">{t}</span>)}
                      </div>
                      <div className="pcard-loc">
                        <Icon name="pin" size={14}/>
                        <span>
                          {p.addr ? <>{p.addr} · </> : null}
                          <span className="city">{p.city}{p.state?`, ${p.state}`:''}</span>
                          {p.zip?` ${p.zip}`:''}
                          {p.country?`, ${p.country}`:''}
                        </span>
                      </div>
                      {p.web && (
                        <div className="pcard-loc">
                          <Icon name="globe" size={14}/>
                          <a
                            href={p.web.startsWith('http') ? p.web : `https://${p.web}`}
                            target="_blank"
                            rel="noreferrer"
                            className="pcard-link"
                          >{p.web}</a>
                        </div>
                      )}
                    </>
                  ) : (
                    <>
                      <p className="pcard-bio" style={{opacity:.75}}>
                        <strong>Claim it free</strong> to add your address, phone, website, socials, photo and more.
                      </p>
                      <div className="pcard-tags">
                        <span className="pill" style={{background:'var(--ink)',color:'var(--paper)',borderColor:'var(--ink)'}}>{p.specialty}</span>
                        {p.peerSavedCount > 0 && (
                          <span className="pill" style={{background:'var(--accent)',borderColor:'var(--accent)',color:'var(--ink)'}} title="Saved by other TMJD providers as a referral partner">
                            ◇ Saved by {p.peerSavedCount} provider{p.peerSavedCount===1?'':'s'}
                          </span>
                        )}
                        {p.favoriteCount > 0 && (
                          <span className="pill" style={{background:'transparent',borderColor:'#e25555',color:'#c23b3b'}} title="Patients who hearted this listing">
                            ♥ {p.favoriteCount}
                          </span>
                        )}
                      </div>
                      <div className="pcard-loc">
                        <Icon name="pin" size={14}/>
                        <span>
                          {businessName}
                          {(p.city || p.state) ? (
                            <> · <span className="city">{p.city}{p.state?`, ${p.state}`:''}</span></>
                          ) : null}
                        </span>
                      </div>
                    </>
                  )}
                </div>
                <div className="pcard-right">
                  {isClaimed ? (
                    <>
                      {p.rating ? (
                        <div className="pcard-rating">
                          <div className="big">{Number(p.rating).toFixed(1)}</div>
                          <Stars rating={Number(p.rating)}/>
                          {p.reviews ? <span className="src">{p.reviews} on {p.source || 'Google'}</span> : null}
                        </div>
                      ) : null}
                      <div className="pcard-icons">
                        {p.phone && (
                          <a className="icon-btn" title={`Call ${p.phone}`} href={`tel:${p.phone.replace(/[^\d+]/g,'')}`} onClick={()=>logClick(p.id,'phone')}><Icon name="phone" size={14}/></a>
                        )}
                        {p.email && (
                          <a className="icon-btn" title={`Email ${p.email}`} href={`mailto:${p.email}`} onClick={()=>logClick(p.id,'email')}><Icon name="mail" size={14}/></a>
                        )}
                        {p.web && (
                          <a className="icon-btn" title={p.web} href={p.web.startsWith('http')?p.web:`https://${p.web}`} target="_blank" rel="noreferrer" onClick={()=>logClick(p.id,'web')}><Icon name="globe" size={14}/></a>
                        )}
                        {(p.instagram || p.facebook || p.x || p.linkedin) && (
                          <a className="icon-btn" title="Social"
                             href={(()=>{ const s=p.instagram||p.facebook||p.x||p.linkedin; if(!s) return '#'; if(s.startsWith('http')) return s; if(p.instagram===s) return `https://instagram.com/${s.replace(/^@/,'')}`; return s; })()}
                             target="_blank" rel="noreferrer" onClick={()=>logClick(p.id,'social')}><Icon name="ig" size={14}/></a>
                        )}
                      </div>
                      {p.scheduleUrl ? (
                        <a
                          className="pcard-cta"
                          href={p.scheduleUrl.startsWith('http') ? p.scheduleUrl : `https://${p.scheduleUrl}`}
                          target="_blank"
                          rel="noreferrer"
                          onClick={()=>logClick(p.id,'schedule')}
                        >
                          <Icon name="cal" size={13}/> Schedule
                        </a>
                      ) : null}
                    </>
                  ) : (
                    <button className="pcard-cta pcard-cta-secondary" type="button" onClick={()=>onClaim?.(p.id)}>
                      Claim free
                    </button>
                  )}
                  {isClaimed && (
                    <span
                      className="pcard-cta pcard-cta-secondary"
                      aria-disabled="true"
                      style={{opacity:.55, cursor:'default', display:'inline-flex', alignItems:'center', justifyContent:'center', gap:6, marginTop:8}}
                    >
                      Claimed ✓
                    </span>
                  )}
                </div>
              </article>
            );
          })}

          <button className="btn" style={{margin:'10px auto 0', display:'flex'}}>Load more practitioners <Icon name="arrow" size={13}/></button>

          <div className="add-listing-cta">
            <div>
              <h4>Don't see yourself listed?</h4>
              <p>List your TMJD practice today — free to claim, takes about 2 minutes.</p>
            </div>
            <button className="btn btn-dark" type="button" onClick={()=>onClaim?.('')}>
              Add your listing <Icon name="arrow" size={13}/>
            </button>
          </div>
        </div>
      )}

      {/* MAP PANEL */}
      {view!=='list' && (
        <div className="results-map">
          <div className="map-vis-full"/>
          <div className="map-grid" style={{position:'absolute',inset:0,backgroundImage:'linear-gradient(var(--line-soft) 1px, transparent 1px), linear-gradient(90deg, var(--line-soft) 1px, transparent 1px)', backgroundSize:'64px 64px'}}/>

          {/* user location */}
          <div className="pulse" style={{top:'48%', left:'48%'}}/>
          <div style={{position:'absolute', top:'48%', left:'48%', transform:'translate(-50%,-50%)', width:14, height:14, borderRadius:'50%', background:'var(--ink)', border:'3px solid var(--paper)', boxShadow:'0 4px 10px rgba(0,0,0,.3)'}}/>

          {list.map(p=>(
            <button
              key={p.id}
              onMouseEnter={()=>setHovered(p.id)}
              onMouseLeave={()=>setHovered(null)}
              style={{position:'absolute', left:`${p.pin.x}%`, top:`${p.pin.y}%`, padding:0, transform:'translate(-50%,-100%)'}}
              aria-label={p.name}
            >
              <span className={`pin ${p.pin.color}`} style={{display:'block'}}/>
            </button>
          ))}

          {hovered && (() => {
            const p = list.find(x=>x.id===hovered);
            if (!p) return null;
            return (
              <div className="map-tooltip" style={{ left:`${p.pin.x}%`, top:`${p.pin.y}%` }}>
                <h5 className="nm">{p.name}</h5>
                <div className="sp">{p.specialty}</div>
                <div className="rt">
                  {p.rating ? <><Stars rating={p.rating}/> {p.rating.toFixed(1)} · </> : null}
                  {p.distance}
                </div>
              </div>
            );
          })()}

          <div className="map-controls">
            <button className="map-ctl" title="Zoom in"><Icon name="plus" size={14}/></button>
            <button className="map-ctl" title="Zoom out"><Icon name="minus" size={14}/></button>
            <button className="map-ctl" title="Recenter"><Icon name="crosshair" size={14}/></button>
          </div>

          <div className="map-radius">
            <label><span>Search radius</span><span>{radius} mi</span></label>
            <input type="range" min="2" max="100" value={radius} onChange={e=>setRadius(+e.target.value)}/>
            <div style={{display:'flex',justifyContent:'space-between',fontSize:11,color:'var(--muted)',fontFamily:'var(--mono)'}}>
              <span>2</span><span>25</span><span>50</span><span>100 mi</span>
            </div>
          </div>
        </div>
      )}

      {/* mobile-style view tabs */}
      <div className="view-tabs">
        <button className={view==='list'?'active':''} onClick={()=>setView('list')}><Icon name="list" size={12}/> List</button>
        <button className={view==='split'?'active':''} onClick={()=>setView('split')}>Split</button>
        <button className={view==='map'?'active':''} onClick={()=>setView('map')}><Icon name="map" size={12}/> Map</button>
      </div>
    </div>
  );
};

if (typeof window !== 'undefined') Object.assign(window, { Results });
