// Find a dentist — dental care search

function findRouteParams(route) {
  const q = (route || window.location.hash.replace(/^#/, '') || '').split('?')[1] || '';
  return new URLSearchParams(q);
}

function FindADoctor({ tone = 'warm', route = '' }) {
  const [selected, setSelected] = React.useState(1);
  const [filterSpec, setFilterSpec] = React.useState('all');
  const [onlineOnly, setOnlineOnly] = React.useState(() => findRouteParams(route).get('online') === '1');
  const { user, signedIn } = useAuth();
  useDoctorReviews();
  const presence = usePresence();

  React.useEffect(() => {
    setOnlineOnly(findRouteParams(route).get('online') === '1');
  }, [route]);

  const list = DOCTORS.map(d => ({ ...d, online: presence.has(d.id) }))
    .filter(d => doctorMatchesSpec(d, filterSpec) && (!onlineOnly || d.online));
  const sel = list.find(p => p.id === selected) || list[0] || DOCTORS[0];

  return (
    <div className="ml-root" style={{ height: '100%', overflowY: 'auto', background: 'var(--paper-2)' }}>
      {/* Slim nav */}
      {!signedIn && <nav style={{ display: 'flex', alignItems: 'center', padding: '16px 40px', borderBottom: '1px solid var(--line)', background: '#fff' }}>
        <div onClick={() => window.navigate && window.navigate('/')} style={{ display: 'flex', alignItems: 'center', gap: 10, cursor: 'pointer' }}>
          <div style={{ width: 24, height: 24, borderRadius: 7, background: 'var(--blue)', display: 'grid', placeItems: 'center', color: '#fff' }}>
            <I.pulse size={14}/>
          </div>
          <div style={{ fontFamily: 'var(--display)', fontSize: 18, letterSpacing: '-0.02em' }}>molara</div>
        </div>
        <div style={{ display: 'flex', gap: 24, marginLeft: 48, fontSize: 14, color: 'var(--ink-2)' }}>
          <a style={{ color: 'var(--ink)', fontWeight: 500, cursor: 'pointer' }}>Find a dentist</a>
          <a onClick={() => window.startEmergencyConsult ? window.startEmergencyConsult(null) : window.requireAuth('/pay?emergency=1')} style={{ cursor: 'pointer' }}>Emergency consult</a>
          <a onClick={() => window.navigate && window.navigate('/')} style={{ cursor: 'pointer' }}>How it works</a>
        </div>
        <div style={{ marginLeft: 'auto', display: 'flex', gap: 10, alignItems: 'center' }}>
          {signedIn ? (
            <>
              <I.bell size={18} style={{ color: 'var(--ink-3)' }}/>
              <div className="ml-avatar" title={user?.name} style={{ width: 32, height: 32, borderRadius: 999, fontSize: 12 }}>{user?.initials || 'PT'}</div>
            </>
          ) : (
            <>
              <button onClick={() => window.openGate ? window.openGate('/', 'signin') : window.navigate('/signin')} className="ml-btn ml-btn--ghost" style={{ padding: '8px 14px', fontSize: 13 }}>Sign in</button>
            </>
          )}
        </div>
      </nav>}

      {/* Dental care chip strip */}
      <div style={{ padding: '18px 40px', display: 'flex', gap: 8, overflow: 'auto', background: '#fff', borderBottom: '1px solid var(--line)' }}>
        <button onClick={() => setFilterSpec('all')}
          className={filterSpec === 'all' ? 'ml-pill' : 'ml-pill ml-pill--ghost'}
          style={{ cursor: 'pointer', border: 'none', fontSize: 13, padding: '8px 12px' }}>All dental care</button>
        {SPECIALTIES.map(s => (
          <button key={s.k} onClick={() => setFilterSpec(s.k)}
            className={filterSpec === s.k ? 'ml-pill' : 'ml-pill ml-pill--ghost'}
            style={{ cursor: 'pointer', border: 'none', fontSize: 13, padding: '8px 12px' }}>{s.n}</button>
        ))}
      </div>

      {/* Results header */}
      <div style={{ padding: '20px 40px', display: 'flex', alignItems: 'center', gap: 12 }}>
        <div style={{ fontSize: 15, color: 'var(--ink-3)' }}>
          <b style={{ color: 'var(--ink)', fontFamily: 'var(--display)', fontSize: 22, marginRight: 7 }}>{list.length}</b> dentists available
        </div>
        <button onClick={() => setOnlineOnly(!onlineOnly)}
          className={onlineOnly ? 'ml-pill' : 'ml-pill ml-pill--ghost'}
          style={{ cursor: 'pointer', border: 'none', fontSize: 13, marginLeft: 16, padding: '8px 12px' }}>
          <span className="ml-live"/> Online now only
        </button>
        <div style={{ marginLeft: 'auto', display: 'flex', gap: 16, alignItems: 'center', fontSize: 14, color: 'var(--ink-3)' }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 7 }}><I.filter size={14}/> More filters</span>
          <span>Sort: <b style={{ color: 'var(--ink)' }}>Soonest available</b></span>
        </div>
      </div>

      {/* 2-col layout */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 20, padding: '0 40px 40px' }}>
        {/* Provider list */}
        <div style={{ display: 'grid', gap: 14 }}>
          {list.map((p) => {
            const on = sel && sel.id === p.id;
            const stats = doctorStats(p);
            return (
              <div key={p.id} onClick={() => setSelected(p.id)}
                className="ml-card"
                style={{ padding: 20, display: 'grid', gridTemplateColumns: '68px 1fr auto', gap: 18, cursor: 'pointer',
                  borderColor: on ? 'var(--blue)' : 'var(--line)',
                  boxShadow: on ? '0 0 0 3px oklch(92% 0.05 240)' : 'none' }}>
                <div className="ml-avatar" style={{ width: 68, height: 68, borderRadius: 12, fontSize: 20,
                  background: TONE_BG[p.tone], color: TONE_FG[p.tone] }}>{p.avatar}</div>
                <div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4, flexWrap: 'wrap' }}>
                    <span style={{ fontFamily: 'var(--display)', fontSize: 20, fontWeight: 500 }}>{p.n}</span>
                    <span className="ml-pill ml-pill--ghost" style={{ fontFamily: 'var(--mono)', fontSize: 11 }}>{p.creds}</span>
                    {p.online && <span className="ml-pill ml-pill--mint"><span className="ml-live"/> Online</span>}
                  </div>
                  <div style={{ fontSize: 14, color: 'var(--ink-3)', marginBottom: 10 }}>
                    {p.spec} · {p.y} yrs · {p.loc}
                  </div>
                  <div style={{ display: 'flex', gap: 16, fontSize: 13, color: 'var(--ink-2)', flexWrap: 'wrap' }}>
                    <span style={searchInline}><I.star size={13}/> <b>{stats.rating}</b> <span className="ml-quiet">({stats.reviews.toLocaleString()})</span></span>
                    <span style={searchInline}>{p.langs.join(' · ')}</span>
                  </div>
                </div>
                <div style={{ textAlign: 'right' }}>
                  <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>From</div>
                  <div style={{ fontFamily: 'var(--display)', fontSize: 22 }}>₹{p.fee}</div>
                  <button onClick={(e) => { e.stopPropagation(); window.requireAuth(`/book?doctor=${p.id}`); }} className="ml-btn ml-btn--dark" style={{ marginTop: 10, padding: '8px 13px', fontSize: 13 }}>
                    Consult now <I.arrowR size={13}/>
                  </button>
                </div>
              </div>
            );
          })}
          {list.length === 0 && (
            <div className="ml-card" style={{ padding: 48, textAlign: 'center', color: 'var(--ink-3)' }}>
              No dentists match these filters.
            </div>
          )}
        </div>

        {/* Profile preview panel */}
        <aside style={{ position: 'sticky', top: 20, height: 'fit-content' }}>
          <div className="ml-card" style={{ padding: 0, overflow: 'hidden' }}>
            <div style={{
              height: 140,
              background: `linear-gradient(135deg, ${TONE_BG[sel.tone]}, var(--paper-2))`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>
              <div className="ml-avatar" style={{ width: 96, height: 96, borderRadius: '50%', fontSize: 30,
                background: TONE_BG[sel.tone], color: TONE_FG[sel.tone],
                border: '4px solid #fff' }}>{sel.avatar}</div>
            </div>
            <div style={{ padding: 22 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <h3 style={{ fontSize: 26 }}>{sel.n}</h3>
                {sel.online && <span className="ml-pill ml-pill--mint" style={{ marginLeft: 'auto' }}><span className="ml-live"/> Online now</span>}
              </div>
              <div style={{ color: 'var(--ink-3)', fontSize: 14, marginTop: 5 }}>{sel.creds} · {sel.spec} · {sel.y} yrs · {sel.loc}</div>

              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 8, marginTop: 18, textAlign: 'center' }}>
                {[[doctorStats(sel).rating, `${doctorStats(sel).reviews} reviews`], [sel.wait || '5 min', 'Avg wait'], [`${sel.y} yrs`, 'Experience']].map(([a, b]) => (
                  <div key={b} style={{ padding: 12, background: 'var(--paper-2)', borderRadius: 8 }}>
                    <div style={{ fontFamily: 'var(--display)', fontSize: 20, fontWeight: 500 }}>{a}</div>
                    <div style={{ fontSize: 12, color: 'var(--ink-3)' }}>{b}</div>
                  </div>
                ))}
              </div>

              <div style={{ marginTop: 18 }}>
                <div className="ml-label" style={{ marginBottom: 8 }}>About</div>
                <p style={{ fontSize: 14, color: 'var(--ink-2)', margin: 0, lineHeight: 1.55 }}>{sel.bio}</p>
              </div>

              <div style={{ marginTop: 18 }}>
                <div className="ml-label" style={{ marginBottom: 8 }}>Languages</div>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                  {sel.langs.map(t => <span key={t} className="ml-pill ml-pill--ghost">{t}</span>)}
                </div>
              </div>

              <div style={{ marginTop: 18 }}>
                <div className="ml-label" style={{ marginBottom: 8 }}>Consult modes</div>
                <div style={{ display: 'flex', gap: 6 }}>
                  <span className="ml-pill ml-pill--ghost" style={{ fontSize: 13 }}><I.video size={12}/> Video</span>
                  <span className="ml-pill ml-pill--ghost" style={{ fontSize: 13 }}><I.mic size={12}/> Audio</span>
                  <span className="ml-pill ml-pill--ghost" style={{ fontSize: 13 }}><I.chat size={12}/> Chat</span>
                </div>
              </div>

              <button onClick={() => window.requireAuth(`/book?doctor=${sel.id}`)} className="ml-btn ml-btn--primary" style={{ width: '100%', justifyContent: 'center', marginTop: 20, padding: '13px', fontSize: 14 }}>
                Consult now <I.arrowR size={14}/>
              </button>
              <div style={{ textAlign: 'center', fontSize: 12, color: 'var(--ink-3)', marginTop: 10 }}>
                Pay after consult · refund if cancelled
              </div>
            </div>
          </div>
        </aside>
      </div>
    </div>
  );
}

const searchInline = { display: 'inline-flex', alignItems: 'center', gap: 6 };

Object.assign(window, { FindADoctor, FindADentist: FindADoctor });
