// Directory & Profile screens
const R = window.RECOGNITION;

// "All" + the nine recognition axes, sourced from the shared model.
const AXIS_FILTERS = [{ slug: 'all', name: 'All' }].concat(
  R.AXES.map(a => ({ slug: a.slug, name: a.short }))
);

// Tier → pill tone for subspecialty grade chips.
const TIER_TONE = { distinguished: 'gold', excellence: 'silver', recognized: 'bronze', listed: 'neutral' };

function DirSkeleton() {
  return (
    <div className="dir-grid" style={{ paddingBottom: 'var(--s-12)' }}>
      {[0, 1, 2].map(i => (
        <div className="card dir-card skeleton-card" key={i} aria-hidden="true">
          <div className="dir-card-top">
            <div style={{ flex: 1 }}>
              <div className="skel skel-line" style={{ width: '52%', height: 18 }} />
              <div className="skel skel-line" style={{ width: '78%', height: 12, marginTop: 8 }} />
            </div>
            <div style={{ display: 'flex', gap: 6 }}>
              <div className="skel skel-circle" /><div className="skel skel-circle" />
            </div>
          </div>
          <div className="skel skel-line" style={{ width: '100%', height: 38, marginTop: 12, borderRadius: 8 }} />
          <div className="skel skel-line" style={{ width: '60%', height: 12, marginTop: 12 }} />
        </div>
      ))}
    </div>
  );
}

function SubspecialtyChips({ specialties, max = 3 }) {
  if (!specialties || !specialties.length) return null;
  const top = specialties
    .slice()
    .sort((a, b) => (R.TIER_RANK[b.tier] || 0) - (R.TIER_RANK[a.tier] || 0) || b.vps - a.vps)
    .slice(0, max);
  return (
    <div className="subspec-chips">
      {top.map(s => (
        <span key={s.subspecialty} className={`subspec-chip subspec-${TIER_TONE[s.tier] || 'neutral'}`}
          title={`${R.tierLabel(s.tier)} · VPS ${s.vps} · informs ${s.axes.map(R.axisShort).join(', ')}`}>
          {s.label}
          <span className="subspec-tier">{R.tierLabel(s.tier)}</span>
        </span>
      ))}
    </div>
  );
}

function Directory({ go, lang, setLang, state, set }) {
  const saved = (state && state._dir) || {};
  const [filt, setFilt] = useState(saved.filt || ['all']);
  const [q, setQ] = useState(saved.q || '');
  const [qInput, setQInput] = useState(saved.q || '');
  const [results, setResults] = useState([]);
  const [loading, setLoading] = useState(true);
  const [err, setErr] = useState(null);

  const toggle = (slug) => {
    if (slug === 'all') { setFilt(['all']); return; }
    setFilt(prev => {
      const next = prev.filter(x => x !== 'all');
      const r = next.includes(slug) ? next.filter(x => x !== slug) : [...next, slug];
      return r.length ? r : ['all'];
    });
  };

  // Persist filter state so "Back to results" restores it.
  React.useEffect(() => {
    if (set) set(s => ({ ...s, _dir: { filt, q } }));
  }, [filt.join(','), q]);

  const [note, setNote] = useState(null);
  React.useEffect(() => {
    const axes = filt.filter(f => f !== 'all').join(',');
    const params = new URLSearchParams({
      zip: (state && state.zip) || '',
      insurance: (state && state.insurance) || '',
      language: (state && state.language) || '',
      ...(axes ? { axes } : {}),
      ...(q ? { q } : {}),
      limit: '10',
    });
    setLoading(true);
    fetch(`/api/directory?${params}`)
      .then(r => r.json().then(d => ({ status: r.status, d })).catch(() => ({ status: r.status, d: null })))
      .then(({ status, d }) => {
        if (!d) { setErr(`Directory request failed (${status})`); setResults([]); setNote(null); return; }
        if (d.ok === false) { setErr(d.error || `Directory error (${status})`); setResults([]); setNote(null); return; }
        setResults(d.results || []);
        setNote(d.note || null);
        setErr(null);
      })
      .catch(e => { setErr(`Couldn't load directory (${e?.message || e})`); setResults([]); setNote(null); })
      .finally(() => setLoading(false));
  }, [filt.join(','), q, state && state.zip, state && state.insurance, state && state.language]);

  const zip = (state && state.zip) || '94102';
  const openProfile = (d) => { if (set) set(s => ({ ...s, _selectedDentist: d })); go('profile'); };
  const clearAll = () => { setFilt(['all']); setQ(''); setQInput(''); };

  return (
    <div className="app">
      <Masthead lang={lang} setLang={setLang} go={go}/>
      <main>
        <div className="container">
          <Breadcrumbs crumbs={[{label:'Home',screen:'landing'},{label:'Find a dentist'}]} go={go}/>
          <div style={{padding:'var(--s-2) 0 var(--s-4)'}}>
            <div className="t-eyebrow" style={{marginBottom:6}}>Directory</div>
            <h1 className="section-h" style={{margin:0}}>Recognized dentists near {zip}</h1>
            <p style={{margin:'var(--s-2) 0 0',color:'var(--ink-2)'}}>
              {loading ? 'Searching…' : `${results.length} ${results.length === 1 ? 'dentist' : 'dentists'} · sorted by Verified Performance Score`}
              {err && <span style={{color:'var(--alert)'}}> · {err}</span>}
            </p>
            {!loading && note && (
              <p style={{margin:'var(--s-2) 0 0',color:'var(--ink-3)',fontSize:13}}>{note}</p>
            )}
          </div>

          <form className="dir-search" onSubmit={(e)=>{e.preventDefault();setQ(qInput.trim());}}>
            <Icon d={ICONS.search} size={16}/>
            <input
              type="search"
              value={qInput}
              onChange={(e)=>setQInput(e.target.value)}
              placeholder="Search by name, practice, specialty — e.g. veneers, implants, Invisalign…"
              aria-label="Search dentists and specialties"
            />
            <Button variant="primary" size="sm" type="submit">Search</Button>
          </form>

          <div className="dir-toolbar">
            <div className="dir-filters">
              {AXIS_FILTERS.map(f => (
                <span key={f.slug}
                  className={`pill ${filt.includes(f.slug)?'pill-active':''}`}
                  onClick={()=>toggle(f.slug)}
                  role="button" tabIndex={0}
                  onKeyDown={(e)=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();toggle(f.slug);}}}
                  style={{cursor:'pointer'}}>{f.name}</span>
              ))}
            </div>
            <Button variant="tertiary" size="sm"><Icon d={ICONS.filter} size={14}/> Sort: Best fit</Button>
          </div>

          {loading && <DirSkeleton/>}

          {!loading && results.length === 0 && (
            <div className="dir-empty">
              <Icon d={ICONS.search} size={32} stroke={1.2}/>
              <h3>No dentists match these filters yet</h3>
              <p>We're seeded with a San Francisco set today and the NPPES ingest is expanding nationally. Try fewer filters or a broader search term.</p>
              <Button variant="secondary" size="md" onClick={clearAll}>Clear all filters</Button>
            </div>
          )}

          {!loading && results.length > 0 && (
            <div className="dir-grid" style={{paddingBottom:'var(--s-12)'}}>
              {results.map(r => (
                <div className="card dir-card" key={r.npi}>
                  <div className="dir-card-top">
                    <div>
                      <h3>{r.name}</h3>
                      <div className="practice">{r.practice} · {r.distance_mi} mi · {r.address}</div>
                    </div>
                    <div className="badges">
                      {r.badges.map(([a,t])=> <Badge key={a} axis={a} tier={t} size={52}/>)}
                    </div>
                  </div>
                  <div className="why">
                    <strong>Why we're showing this:</strong> {r.why}
                  </div>
                  <SubspecialtyChips specialties={r.specialties}/>
                  <div className="meta-row">
                    <span style={{fontFamily:'var(--font-display)',fontSize:17,fontWeight:500,color:'var(--ink-1)',fontFeatureSettings:'"tnum"'}}>{r.cost_band}</span>
                    <span>·</span>
                    <span>{r.insurance.slice(0,2).join(' · ')}</span>
                    <span>·</span>
                    <span>{r.languages.join(' · ')}</span>
                    <span>·</span>
                    <Pill tone={r.accepting?'ok':'neutral'}>{r.accepting?'Accepting':'Waitlist'}</Pill>
                  </div>
                  <div className="actions">
                    <Button variant="tertiary" size="sm" onClick={()=>openProfile(r)}>View profile</Button>
                    <Button variant="primary" size="sm">Book {r.next_avail}</Button>
                  </div>
                </div>
              ))}
            </div>
          )}
        </div>
      </main>
      <Footer go={go}/>
    </div>
  );
}

// Fallback dentist when Profile is reached without a selection (deep link / refresh).
const FALLBACK_DENTIST = {
  npi: '1234567893',
  name: 'Dr. Sarah Chen, DDS',
  practice: 'Bay Dental Care',
  address: '1402 Mission St, San Francisco',
  initials: 'SC',
  accepting: true,
  insurance: ['Delta PPO','MetLife','Cigna'],
  languages: ['English','中文'],
  next_avail: 'Tue 2:00 PM',
  phone: '(415) 555-0142',
  hours: 'Mon–Fri 8a–6p · Sat 9a–2p',
  badges: [['anxious-friendly','distinguished'],['multilingual','excellence'],['patient-favorite','recognized']],
  specialties: [
    { subspecialty:'root-canal', label:'Root canal therapy', specialty_label:'Endodontics', axes:['anxious-friendly'], vps:90, tier:'distinguished' },
    { subspecialty:'fillings', label:'Fillings & cavity care', specialty_label:'General & Preventive', axes:['continuity-champion','budget-conscious','family-friendly'], vps:86, tier:'excellence' },
    { subspecialty:'cleanings-exams', label:'Cleanings & exams', specialty_label:'General & Preventive', axes:['continuity-champion','budget-conscious','family-friendly'], vps:81, tier:'excellence' },
    { subspecialty:'nitrous-oral-sedation', label:'Nitrous oxide / oral sedation', specialty_label:'Sedation & Comfort', axes:['anxious-friendly','caregiver-friendly'], vps:88, tier:'distinguished' },
  ],
  about: 'Bay Dental Care has served the Mission District since 2014. The practice emphasizes calm, paced visits and bilingual care. Dr. Chen completed her DDS at UCSF and is a member of the American Dental Association.',
};

function initialsOf(name) {
  return (name || '').replace(/^Dr\.?\s*/, '').split(/\s+/).slice(0, 2).map(w => w[0]).join('').toUpperCase();
}

function Profile({ go, lang, setLang, state, set }) {
  const d = (state && state._selectedDentist) || FALLBACK_DENTIST;
  const initials = d.initials || initialsOf(d.name);

  React.useEffect(() => { window.Enc?.viewedDentist(d); }, [d && d.npi]);

  const TABS = [
    ['recognition','Recognition'],
    ['clinical','Clinical performance'],
    ['highlights','Patient highlights'],
    ['costs','Costs'],
    ['about','About'],
  ];
  const [tab, setTab] = useState('recognition');

  // Group graded subspecialties by their parent specialty for the clinical tab.
  const groups = {};
  (d.specialties || []).forEach(s => {
    const k = s.specialty_label || 'Other';
    (groups[k] = groups[k] || []).push(s);
  });
  const backToResults = () => go('directory');

  return (
    <div className="app">
      <Masthead lang={lang} setLang={setLang} go={go}/>
      <main>
        <div className="container">
          <Breadcrumbs crumbs={[{label:'Home',screen:'landing'},{label:'Find a dentist',screen:'directory'},{label:d.name}]} go={go}/>
          <div className="profile-grid">
            <div>
              <div className="profile-hero">
                <div className="profile-photo">{initials}</div>
                <div>
                  <h1 className="profile-name">{d.name}</h1>
                  <div className="profile-practice">{d.practice} · {d.address}</div>
                  <div style={{display:'flex',gap:6,marginTop:8,flexWrap:'wrap'}}>
                    <Pill tone={d.accepting?'ok':'neutral'}>{d.accepting?'Accepting new patients':'Waitlist'}</Pill>
                    <Pill>{(d.insurance||[]).slice(0,3).join(' · ')}</Pill>
                    <Pill>{(d.languages||[]).join(' · ')}</Pill>
                  </div>
                </div>
              </div>

              <div className="profile-tabs" role="tablist" aria-label="Profile sections">
                {TABS.map(([id,label])=>(
                  <button key={id} role="tab" aria-selected={tab===id} className={`profile-tab ${tab===id?'on':''}`} onClick={()=>setTab(id)}>{label}</button>
                ))}
              </div>

              {tab==='recognition' && <section className="profile-section">
                <div className="t-eyebrow" style={{marginBottom:6}}>Recognition · 2026</div>
                <h2>Recognized in {(d.badges||[]).length} {(d.badges||[]).length === 1 ? 'area' : 'areas'}</h2>
                <div className="profile-axes" style={{marginTop:'var(--s-4)'}}>
                  {(d.badges||[]).map(([a,t])=>(
                    <div className="profile-axis" key={a}>
                      <Badge axis={a} tier={t} size={84}/>
                      <div style={{fontSize:13,fontWeight:600,marginTop:6}}>{R.axisShort(a)}</div>
                      <div className="t-tier">{R.tierLabel(t)}</div>
                    </div>
                  ))}
                </div>
                <p className="t-fine" style={{marginTop:'var(--s-4)'}}>Recognition is earned algorithmically across nine positive-only axes from verified surveys, practice-published data, and structured outcome signals. <a href="/methodology/" style={{color:'var(--ink-2)'}}>See methodology</a>.</p>
              </section>}

              {tab==='clinical' && <section className="profile-section">
                <div className="t-eyebrow" style={{marginBottom:6}}>Clinical performance · graded per subspecialty</div>
                <h2>What this practice is graded on</h2>
                <p style={{margin:'0 0 var(--s-4)',color:'var(--ink-2)',fontSize:14,lineHeight:1.6}}>
                  Each subspecialty carries a Verified Performance Score and tier, computed from outcome data and Council case review — and reported in the context of the recognition axes it informs.
                </p>
                {Object.keys(groups).length === 0 && (
                  <p className="t-meta">No subspecialty grades published yet for this practice.</p>
                )}
                {Object.entries(groups).map(([specialty, items])=>(
                  <div key={specialty} className="clin-group">
                    <div className="clin-group-h">{specialty}</div>
                    {items.sort((a,b)=>(R.TIER_RANK[b.tier]||0)-(R.TIER_RANK[a.tier]||0)||b.vps-a.vps).map(s=>(
                      <div className="clin-row" key={s.subspecialty}>
                        <div className="clin-row-main">
                          <div className="clin-sub">{s.label}</div>
                          <div className="clin-axes">informs {(s.axes||[]).map(R.axisShort).join(' · ')}</div>
                        </div>
                        <div className={`clin-tier subspec-${TIER_TONE[s.tier]||'neutral'}`}>{R.tierLabel(s.tier)}</div>
                        <div className="clin-vps" title="Verified Performance Score">{s.vps}</div>
                      </div>
                    ))}
                  </div>
                ))}
                <p className="t-fine" style={{marginTop:'var(--s-4)'}}>VPS is a 0–100 composite per subspecialty. Absence of a grade is a neutral signal — not a negative one.</p>
              </section>}

              {tab==='highlights' && <section className="profile-section">
                <h2>Verified patient highlights</h2>
                <div style={{display:'grid',gap:'var(--s-3)'}}>
                  {[
                    ['What patients said most often','"Explained things calmly. Didn\'t rush. Walked me through every step before starting." — recurring across 31 verified surveys'],
                    ['Patient Favorite signal','Earned only from patient-submitted material — reviews, x-rays, and photos — each authenticated by a human-in-the-loop auditor before it counts toward the axis.'],
                    ['Multilingual signal','Mandarin and Cantonese available without translator request. Verified Apr 2026.'],
                  ].map(([t,desc])=>(
                    <div className="card card-paper" key={t}>
                      <div style={{fontWeight:600,fontSize:14,marginBottom:6}}>{t}</div>
                      <div style={{fontSize:14,color:'var(--ink-2)',lineHeight:1.55}}>{desc}</div>
                    </div>
                  ))}
                </div>
              </section>}

              {tab==='costs' && <section className="profile-section">
                <h2>Practice-published cost ranges</h2>
                <p style={{margin:'0 0 var(--s-3)',color:'var(--ink-2)',fontSize:14}}>Cash-pay rates published Apr 2026. Insurance benefit estimates are approximate.</p>
                <table className="profile-cost-table">
                  <tbody>
                    {[
                      ['New patient exam + cleaning','D0150 · D1110','$185'],
                      ['Filling, single surface','D2330','$220 – $310'],
                      ['Crown, porcelain','D2740','$1,180 – $1,520'],
                      ['Root canal, molar','D3330','$1,420 – $1,820'],
                    ].map(([n,c,p])=>(
                      <tr key={c}><td>{n}</td><td style={{color:'var(--ink-3)',fontFamily:'var(--font-mono)',fontSize:12}}>{c}</td><td style={{fontWeight:600}}>{p}</td></tr>
                    ))}
                  </tbody>
                </table>
              </section>}

              {tab==='about' && <section className="profile-section">
                <h2>About this practice</h2>
                <p style={{color:'var(--ink-2)',lineHeight:1.65,fontSize:15}}>{d.about || `${d.practice} is part of TheDentist.ai recognized directory. Recognition and clinical-performance grades are computed from verified data.`}</p>
              </section>}

              <Disclosure/>
            </div>

            <aside className="profile-side">
              <div className="card card-paper">
                <div className="t-eyebrow" style={{marginBottom:6}}>Next available</div>
                <div style={{fontFamily:'var(--font-display)',fontSize:24,fontWeight:500}}>{d.next_avail || 'Call to book'}</div>
                <div style={{color:'var(--ink-2)',fontSize:13,margin:'4px 0 var(--s-4)'}}>{d.distance_mi ? `${d.distance_mi} mi from your search` : 'San Francisco'}</div>
                <Button variant="primary" size="md" style={{width:'100%'}}
                  onClick={()=>{ window.Enc?.bookedAppointment(d); window.open(window.buildTrafftUrl(d),'_blank','noopener'); }}>
                  Book appointment
                </Button>
                <Button variant="secondary" size="sm" style={{width:'100%',marginTop:8}}
                  onClick={()=>{ if(set) set(s=>({...s,_selectedDentist:d})); go('forms'); }}>
                  Get intake forms
                </Button>
                <Button variant="tertiary" size="sm" style={{width:'100%',marginTop:8}} onClick={backToResults}>← Back to results</Button>
                <div style={{marginTop:'var(--s-4)',paddingTop:'var(--s-4)',borderTop:'1px solid var(--ink-5)'}}>
                  <div style={{fontSize:12,color:'var(--ink-3)',marginBottom:6}}>Been a patient here?</div>
                  <Button variant="ghost" size="sm" style={{width:'100%',fontSize:13,color:'var(--seal)',borderColor:'var(--seal)'}}
                    onClick={()=>{ if(set) set(s=>({...s,_selectedDentist:d})); go('survey'); }}>
                    Rate this dentist →
                  </Button>
                </div>
              </div>
              <div className="card card-paper">
                <div className="t-eyebrow" style={{marginBottom:6}}>Practice info</div>
                <div style={{display:'grid',gap:8,fontSize:14}}>
                  <div><strong>Hours</strong><br/><span style={{color:'var(--ink-2)'}}>{d.hours || 'Mon–Fri 8a–6p'}</span></div>
                  <div><strong>Phone</strong><br/><span style={{color:'var(--ink-2)'}}>{d.phone || '(415) 555-0100'}</span></div>
                  <div><strong>Languages</strong><br/><span style={{color:'var(--ink-2)'}}>{(d.languages||['English']).join(' · ')}</span></div>
                </div>
              </div>
            </aside>
          </div>
        </div>
      </main>
      <Footer go={go}/>
    </div>
  );
}

Object.assign(window,{ Directory, Profile });
