// DirectoryView.jsx - sortable filterable card grid
const { useState: useStateD, useMemo: useMemoD } = React;

const TYPE_TINT = {
  'MDB/ IFI / DFI': 'var(--ocean-blue)',
  'Bilateral development agency': 'var(--earth-clay)',
  'Intergovernmental organization (IGO)': 'var(--faded-dewberry)',
  'Coalition or multi-stakeholder platform': 'var(--verdant-green)',
  'NGO': 'var(--solar-yellow)',
  'Philanthropic foundation': '#e07b4a',
  'Private company (IPP)': '#2a7a5a',
  'Private investor': '#7a5da8',
  'Commercial system actor': '#b05c7a',
  'Research & Academic institution': 'var(--sky-blue)',
};

function DirectoryView({ orgs, allOrgs, onPickOrg, filters, setFilters }) {
  const { facets } = window.INITIATIVES_DATA;
  const [sort, setSort] = useStateD('name');
  const searchActive = !!(filters && filters.search);

  const sorted = useMemoD(() => {
    const arr = [...orgs];
    // When searching, app.jsx has already ordered by relevance - keep that
    if (searchActive) return arr;
    if (sort === 'name') arr.sort((a, b) => a.name.localeCompare(b.name));
    else if (sort === 'reach') arr.sort((a, b) => b.regions.length - a.regions.length);
    return arr;
  }, [orgs, sort, searchActive]);

  const toggleFilter = (key, val) => {
    const cur = filters[key] || [];
    const next = cur.includes(val) ? cur.filter(x => x !== val) : [...cur, val];
    setFilters({ ...filters, [key]: next });
  };
  const clearFilter = (key) => setFilters({ ...filters, [key]: [] });

  const activeTypes  = filters.types  || [];
  const activePillar = filters.pillar || [];
  const activeRegions = filters.regions || [];

  const presentTypes = useMemoD(() => {
    const s = new Set((allOrgs || orgs).map(o => o.type).filter(Boolean));
    return Object.keys(TYPE_TINT).filter(t => s.has(t));
  }, [allOrgs, orgs]);

  return (
    <div>
      {/* Filter strip */}
      <div className="dir-filters">
        <div className="mx-legend">
          <span className="mx-legend-label">Type</span>
          {presentTypes.map(t => {
            const active = activeTypes.includes(t);
            const faded  = activeTypes.length > 0 && !active;
            return (
              <button
                key={t}
                type="button"
                className={'mx-legend-item is-clickable' + (active ? ' is-on' : '') + (faded ? ' is-faded' : '')}
                title={active ? `Remove: ${t}` : `Filter to: ${t}`}
                onClick={() => toggleFilter('types', t)}
              >
                <span className="mx-legend-dot" style={{ background: TYPE_TINT[t] }}></span>
                {facets.types.labels[t] || t}
              </button>
            );
          })}
          {activeTypes.length > 0 && (
            <button type="button" className="mx-legend-clear" onClick={() => clearFilter('types')}>Clear</button>
          )}
        </div>

        <div className="mx-legend">
          <span className="mx-legend-label">Pillar</span>
          {[['grids','Grids of the Future','var(--c-mint)'],['powering','Powering Opportunity','var(--c-yellow)'],['both','Both','var(--text-mid)']].map(([id, label, color]) => {
            const active = activePillar.includes(id);
            const faded  = activePillar.length > 0 && !active;
            return (
              <button
                key={id}
                type="button"
                className={'mx-legend-item is-clickable' + (active ? ' is-on' : '') + (faded ? ' is-faded' : '')}
                onClick={() => toggleFilter('pillar', id)}
              >
                <span className="mx-legend-dot" style={{ background: color }}></span>
                {label}
              </button>
            );
          })}
          {activePillar.length > 0 && (
            <button type="button" className="mx-legend-clear" onClick={() => clearFilter('pillar')}>Clear</button>
          )}
        </div>

        <div className="mx-legend">
          <span className="mx-legend-label">Region</span>
          {facets.regions.order.map(r => {
            const active = activeRegions.includes(r);
            const faded  = activeRegions.length > 0 && !active;
            return (
              <button
                key={r}
                type="button"
                className={'mx-legend-item is-clickable' + (active ? ' is-on' : '') + (faded ? ' is-faded' : '')}
                onClick={() => toggleFilter('regions', r)}
              >
                {facets.regions.labels[r] || r}
              </button>
            );
          })}
          {activeRegions.length > 0 && (
            <button type="button" className="mx-legend-clear" onClick={() => clearFilter('regions')}>Clear</button>
          )}
        </div>
      </div>

      <div className="dir-controls">
        <span style={{ fontFamily: 'var(--font-mono)', fontSize: 11, color: 'var(--text-mid)', letterSpacing: '0.1em', textTransform: 'uppercase' }}>
          {orgs.length} initiative{orgs.length === 1 ? '' : 's'}
        </span>
        <div className="seg" style={{ marginLeft: 'auto' }}>
          {[
            ['name', 'A → Z'],
            ['reach', 'Reach'],
          ].map(([k, l]) => (
            <button key={k} className={sort === k ? 'is-on' : ''} onClick={() => setSort(k)}>{l}</button>
          ))}
        </div>
      </div>

      <div className="dir-grid">
        {sorted.map((o) => {
          const color = TYPE_TINT[o.type];
          return (
            <div key={o.id} className="dir-card" onClick={() => onPickOrg(o)}>
              <div className="accent" style={{ background: color }} />
              <div className="head">
                <div className="name">{o.name}</div>
                <span className="type-tag" style={{ background: color, color: 'var(--ink-900)' }}>
                  {facets.types.short[o.type]}
                </span>
              </div>
              <div className="meta">
                <span><b>{o.regions.length}</b> region{o.regions.length === 1 ? '' : 's'}</span>
              </div>
              <div className="desc">{o.description}</div>
              <div className="tags">
                {o.regions.slice(0, 3).map((r) => (
                  <span key={r} className="tag region">{facets.regions.labels[r] || r}</span>
                ))}
                {o.regions.length > 3 && <span className="tag region">+{o.regions.length - 3}</span>}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}
window.DirectoryView = DirectoryView;
