// screens-directory.jsx — Directory list + PsyCard

function DirectoryScreen({ filters, setFilters, setRoute, saved, toggleSave }) {
  const { t, tU, lang } = useLang();
  const [search, setSearch] = useState('');
  const [sort, setSort] = useState('relevance');
  const [allPsys, setAllPsys] = useState([]);
  const [loadingPsys, setLoadingPsys] = useState(true);

  // Load psychologists from API
  useEffect(() => {
    API.getPsychologists()
      .then(data => { setAllPsys(Array.isArray(data) ? data : []); setLoadingPsys(false); })
      .catch(() => { setAllPsys([]); setLoadingPsys(false); });
  }, []);

  function toggleArr(key, v) {
    const cur = new Set(filters[key] || []);
    if (cur.has(v)) cur.delete(v); else cur.add(v);
    setFilters({ ...filters, [key]: Array.from(cur) });
  }
  function setVal(key, v) { setFilters({ ...filters, [key]: v }); }

  const filtered = useMemo(() => {
    let xs = allPsys.slice();
    if (search.trim()) {
      const q = search.trim().toLowerCase();
      xs = xs.filter(p =>
        p.name.toLowerCase().includes(q) ||
        p.bio.toLowerCase().includes(q) ||
        p.specializations.some(s => SPECIALIZATIONS.find(x => x.id === s)?.name.toLowerCase().includes(q)));
    }
    if (filters.approaches?.length) {
      xs = xs.filter(p => p.approaches.some(a => filters.approaches.includes(a)));
    }
    if (filters.specializations?.length) {
      xs = xs.filter(p => p.specializations.some(s => filters.specializations.includes(s)));
    }
    if (filters.districts?.length) {
      xs = xs.filter(p => filters.districts.includes(p.district) || filters.modes?.includes('online') && p.modes.includes('online'));
    }
    if (filters.modes?.length) {
      xs = xs.filter(p => p.modes.some(m => filters.modes.includes(m)));
    }
    if (filters.languages?.length) {
      xs = xs.filter(p => p.languages.some(l => filters.languages.includes(l)));
    }
    if (filters.gesy === true) {
      xs = xs.filter(p => p.gesy === true);
    }

    if (sort === 'rating') xs = xs.sort((a, b) => b.rating - a.rating);
    if (sort === 'experience') xs = xs.sort((a, b) => b.yearsExperience - a.yearsExperience);
    if (sort === 'soonest') xs = xs.sort((a, b) => a.responseHours - b.responseHours);
    return xs;
  }, [filters, search, sort, allPsys]);

  const activeFilters = (filters.approaches?.length || 0) +
    (filters.specializations?.length || 0) +
    (filters.districts?.length || 0) +
    (filters.modes?.length || 0) +
    (filters.languages?.length || 0) +
    (filters.gesy === true ? 1 : 0);

  return (
    <div className="page wide">
      <div style={{ display: 'flex', alignItems: 'end', justifyContent: 'space-between', marginBottom: 16, gap: 16 }}>
        <div>
          <span className="eyebrow muted">{tU('dir_eyebrow')}</span>
          <h1 className="display" style={{ fontSize: 40, marginTop: 8 }}>{t('dir_h1')}</h1>
        </div>
        <div style={{ flex: 1, maxWidth: 460 }}>
          <div className="search">
            <Icon name="search" />
            <input
              placeholder={t('dir_search')}
              value={search}
              onChange={e => setSearch(e.target.value)} />
          </div>
        </div>
      </div>

      {/* Issue-first quick chips */}
      <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap', marginBottom: 20 }}>
        <span style={{ fontSize: 12, color: 'var(--fg3)', alignSelf: 'center', marginRight: 4 }}>
          {lang === 'el' ? 'Γρήγορη επιλογή:' : 'Quick filter:'}
        </span>
        {[
          { id: 'anxiety',    label: lang === 'el' ? 'Άγχος' : 'Anxiety' },
          { id: 'depression', label: lang === 'el' ? 'Κατάθλιψη' : 'Depression' },
          { id: 'trauma',     label: lang === 'el' ? 'Τραύμα' : 'Trauma' },
          { id: 'couples',    label: lang === 'el' ? 'Ζευγάρια' : 'Couples' },
          { id: 'work',       label: lang === 'el' ? 'Εξάντληση' : 'Burnout' },
          { id: 'grief',      label: lang === 'el' ? 'Πένθος' : 'Grief' },
          { id: 'child',      label: lang === 'el' ? 'Παιδιά' : 'Children' },
        ].map(function(chip) {
          const active = (filters.specializations || []).includes(chip.id);
          return (
            <button key={chip.id}
              onClick={function() { toggleArr('specializations', chip.id); }}
              style={{
                appearance: 'none', border: '1.5px solid',
                borderColor: active ? 'var(--psy-accent)' : 'var(--psy-rule)',
                background: active ? 'var(--psy-accent-soft)' : 'white',
                color: active ? 'var(--psy-accent)' : 'var(--fg2)',
                borderRadius: 999, padding: '5px 14px', fontSize: 13,
                fontWeight: active ? 600 : 400, cursor: 'pointer',
                transition: 'all 0.15s',
              }}>
              {chip.label}
            </button>
          );
        })}
        {(filters.specializations || []).length > 0 && (
          <button onClick={function() { setFilters({ ...filters, specializations: [] }); }}
            style={{ appearance: 'none', border: 0, background: 'none', color: 'var(--fg3)',
              fontSize: 12, cursor: 'pointer', padding: '5px 8px' }}>
            {lang === 'el' ? '× καθαρισμός' : '× clear'}
          </button>
        )}
      </div>

      <div className="directory">
        {/* Filters */}
        <aside className="filter-card">
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 8 }}>
            <strong style={{ fontSize: 14 }}>{t('dir_filter')}</strong>
            {activeFilters > 0 && (
              <button className="btn link" style={{ fontSize: 12 }} onClick={() => setFilters({})}>{t('dir_clear')}</button>
            )}
          </div>

          <h4>{tU('filter_approach')}</h4>
          <div className="checks">
            {APPROACHES.map(a => (
              <label key={a.id} className="check" title={a.short}>
                <input type="checkbox"
                  checked={(filters.approaches || []).includes(a.id)}
                  onChange={() => toggleArr('approaches', a.id)} />
                {lang === 'el' && a.name_el ? a.name_el : a.name}
                <span className="count">{allPsys.filter(p => (p.approaches || []).includes(a.id)).length}</span>
              </label>
            ))}
          </div>

          <h4>{tU('filter_spec')}</h4>
          <div className="checks">
            {SPECIALIZATIONS.slice(0, 8).map(s => (
              <label key={s.id} className="check">
                <input type="checkbox"
                  checked={(filters.specializations || []).includes(s.id)}
                  onChange={() => toggleArr('specializations', s.id)} />
                {lang === 'el' && s.name_el ? s.name_el : s.name}
                <span className="count">{allPsys.filter(p => (p.specializations || []).includes(s.id)).length}</span>
              </label>
            ))}
          </div>

          <h4>{tU('filter_district')}</h4>
          <div className="checks">
            {DISTRICTS.map(d => (
              <label key={d} className="check">
                <input type="checkbox"
                  checked={(filters.districts || []).includes(d)}
                  onChange={() => toggleArr('districts', d)} />
                {lang === 'el' && DISTRICT_EL[d] ? DISTRICT_EL[d] : d}
              </label>
            ))}
          </div>

          <h4>{tU('filter_format')}</h4>
          <div className="checks">
            <label className="check">
              <input type="checkbox" checked={(filters.modes || []).includes('in-person')} onChange={() => toggleArr('modes', 'in-person')} />
              {t('filter_inperson')}
            </label>
            <label className="check">
              <input type="checkbox" checked={(filters.modes || []).includes('online')} onChange={() => toggleArr('modes', 'online')} />
              {t('filter_online')}
            </label>
          </div>

          <h4>{tU('filter_language')}</h4>
          <div className="checks">
            {LANGUAGES.map(l => (
              <label key={l} className="check">
                <input type="checkbox"
                  checked={(filters.languages || []).includes(l)}
                  onChange={() => toggleArr('languages', l)} />
                {lang === 'el' && LANGUAGE_EL[l] ? LANGUAGE_EL[l] : l}
              </label>
            ))}
          </div>

          <h4>{tU('filter_insurance')}</h4>
          <label className="check">
            <input type="checkbox"
              checked={filters.gesy === true}
              onChange={() => setVal('gesy', filters.gesy === true ? null : true)} />
            {t('filter_gesy')}
          </label>
        </aside>

        {/* Results */}
        <main>
          <div className="results-toolbar">
            <div className="count">
              <strong>{filtered.length}</strong> {filtered.length === 1 ? t('dir_psychologists') : t('dir_psychologists_pl')}
              {activeFilters > 0 ? ` · ${activeFilters} ${activeFilters === 1 ? t('dir_filters_applied') : t('dir_filters_applied_pl')}` : ''}
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 13 }}>
              <span style={{ color: 'var(--fg2)' }}>{t('dir_sort')}</span>
              <select className="select" style={{ width: 'auto', padding: '8px 12px', fontSize: 13 }}
                value={sort} onChange={e => setSort(e.target.value)}>
                <option value="relevance">{t('dir_sort_best')}</option>
                <option value="rating">{t('dir_sort_rating')}</option>
                <option value="experience">{t('dir_sort_exp')}</option>
                <option value="soonest">{t('dir_sort_fast')}</option>
              </select>
            </div>
          </div>

          {loadingPsys ? (
            <div className="card" style={{ padding: 48, textAlign: 'center' }}>
              <Icon name="sync" style={{ fontSize: 36, color: 'var(--fg3)' }} />
              <p style={{ color: 'var(--fg2)', marginTop: 12 }}>Loading psychologists…</p>
            </div>
          ) : allPsys.length === 0 ? (
            <div className="card" style={{ padding: 56, textAlign: 'center' }}>
              <Icon name="group_off" style={{ fontSize: 40, color: 'var(--fg3)' }} />
              <h3 className="display" style={{ fontSize: 22, marginTop: 14, fontWeight: 600 }}>No psychologists yet</h3>
              <p style={{ color: 'var(--fg2)', marginTop: 8, maxWidth: 420, marginInline: 'auto', lineHeight: 1.6 }}>
                The directory is currently empty. Are you a licensed psychologist?{' '}
                <a href="#" onClick={e => { e.preventDefault(); window.dispatchEvent(new CustomEvent('openProSignup')); }}
                   style={{ color: 'var(--psy-accent)', fontWeight: 600 }}>
                  Register your practice
                </a>
              </p>
            </div>
          ) : filtered.length === 0 ? (
            <div className="card" style={{ padding: 48, textAlign: 'center' }}>
              <Icon name="search_off" style={{ fontSize: 36, color: 'var(--fg3)' }} />
              <h3 style={{ fontFamily: 'var(--font-display)', fontSize: 22, marginTop: 12, fontWeight: 600 }}>No matching results</h3>
              <p style={{ color: 'var(--fg2)', marginTop: 8 }}>Try removing a filter, or open the directory without any filters applied.</p>
              <button className="btn ghost" style={{ marginTop: 16 }} onClick={() => setFilters({})}>Clear all filters</button>
            </div>
          ) : (
            <div className="psy-list">
              {filtered.map(p => (
                <PsyCard key={p.id}
                  psy={p}
                  saved={saved.has(p.id)}
                  onToggleSave={() => toggleSave(p.id)}
                  onOpen={() => setRoute('detail', p.id)} />
              ))}
            </div>
          )}
        </main>
      </div>
    </div>
  );
}

function PsyCard({ psy, onOpen, saved, onToggleSave }) {
  const { t, lang } = useLang();
  const approach = APPROACHES.find(a => a.id === psy.primaryApproach);
  return (
    <div className="psy-card" onClick={onOpen}>
      <Avatar psy={psy} />
      <div className="info">
        <div className="name-row">
          <span className="name">{psy.name}</span>
          {psy.verified && <span className="verified"><Icon name="verified" /> {t('card_verified')}</span>}
        </div>
        <div className="creds">{psy.credentials}</div>
        <div className="tags">
          <span className="tag accent">{approach ? (lang === 'el' && approach.name_el ? approach.name_el : approach.name) : ''}</span>
          <TagList ids={psy.specializations} source={SPECIALIZATIONS} max={3} />
        </div>
        <p className="blurb">{psy.bio}</p>
        <div className="meta">
          <span><Stars value={psy.rating} /> <strong style={{ color: 'var(--psy-ink)' }}>{psy.rating}</strong> <span style={{ color: 'var(--fg3)' }}>({psy.reviewCount})</span></span>
          <span><Icon name="place" /> {psy.district}</span>
          <span><Icon name="schedule" /> {psy.nextAvailable}</span>
          {psy.gesy && <span style={{ color: 'var(--psy-leaf)' }}><Icon name="health_and_safety" /> GeSY</span>}
          {psy.introCall && <span><Icon name="phone_in_talk" /> Free intro call</span>}
        </div>
      </div>
      <div className="side">
        <button className={`save ${saved ? 'saved' : ''}`}
          onClick={(e) => { e.stopPropagation(); onToggleSave(); }}
          title={saved ? 'Remove from shortlist' : 'Save to shortlist'}>
          <Icon name="bookmark" style={{ fontVariationSettings: saved ? "'FILL' 1" : "'FILL' 0" }} />
        </button>
        <div style={{ textAlign: 'right' }}>
          <div style={{ fontSize: 11, color: 'var(--fg3)', textTransform: 'uppercase', letterSpacing: '0.08em', fontWeight: 600 }}>From</div>
          <div style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 22 }}>
            €{psy.pricePerSession}<small style={{ fontSize: 12, color: 'var(--fg2)', fontWeight: 500 }}>/session</small>
          </div>
        </div>
        <button className="btn primary sm">{t('card_view')}</button>
      </div>
    </div>
  );
}

Object.assign(window, { DirectoryScreen, PsyCard });
