// FilterBar.jsx - view-aware filter rail
// Each view defines its own spec'd filter set per the GEA visual specs:
//   Value Chain Map: pillar, barrier, region
//   Collaboration Network: pillar, org type
//   Directory: all filters

const TYPE_KEY = {
  'MDB/ IFI / DFI': 'mdb',
  'Bilateral development agency': 'bil',
  'Intergovernmental organization (IGO)': 'igo',
  'Coalition or multi-stakeholder platform': 'coa',
  'NGO': 'ngo',
  'Research & Academic institution': 'res',
};
window.TYPE_KEY = TYPE_KEY;

// Per-view filter visibility - controls which filter sections render
const VIEW_FILTERS = {
  valuechain: ['pillar', 'barriers', 'regions'],
  matrix:     ['pillar', 'types', 'regions'],
  network:    ['pillar', 'types'],
  directory:  ['pillar', 'regions', 'barriers', 'types'],
};
window.VIEW_FILTERS = VIEW_FILTERS;

function FilterChip({ label, count, active, onClick, sublabel, swatch }) {
  return (
    <button className={'chip' + (active ? ' is-on' : '')} onClick={onClick}>
      <span style={{ display: 'flex', alignItems: 'center', gap: 8, minWidth: 0 }}>
        {swatch && <span style={{ width: 8, height: 8, borderRadius: 2, background: swatch, flexShrink: 0 }}></span>}
        <span style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>
          {label}
          {sublabel && <span style={{ color: 'var(--text-mid)', marginLeft: 6, fontSize: 11 }}>{sublabel}</span>}
        </span>
      </span>
      <span className="count">{count}</span>
    </button>
  );
}

function FilterSection({ title, children, onClear, showClear }) {
  return (
    <div className="rail-section">
      <h4>
        {title}
        {showClear && <span className="clear" onClick={onClear}>clear</span>}
      </h4>
      {children}
    </div>
  );
}

const PILLAR_COLORS = {
  grids: 'var(--c-mint)',
  powering: 'var(--c-yellow)',
  both: 'var(--c-leaf)',
};

function FilterBar({ filters, setFilters, allOrgs, filteredOrgs, facets, activeView }) {
  const { regions, barriers, types, pillar } = facets;
  const visible = VIEW_FILTERS[activeView] || VIEW_FILTERS.directory;
  const showSearch = activeView === 'directory';

  const countOf = (key, val) => filteredOrgs.filter((o) => {
    const v = o[key];
    return Array.isArray(v) ? v.includes(val) : v === val;
  }).length;

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

  const clear = (key) => setFilters({ ...filters, [key]: [] });
  const resetAll = () => setFilters({ search: '', regions: [], barriers: [], types: [], pillar: [] });

  const activeCount = ['regions','barriers','types','pillar']
    .reduce((n,k) => n + (filters[k]?.length || 0), 0) + (filters.search ? 1 : 0);

  return (
    <aside className="rail">
      {showSearch && (
        <>
          <input
            type="text"
            className="search"
            placeholder="Search organizations..."
            value={filters.search}
            onChange={(e) => setFilters({ ...filters, search: e.target.value })}
          />
          <div style={{ height: 14 }} />
        </>
      )}

      <div className="rail-summary">
        <b>{filteredOrgs.length}</b> of {allOrgs.length} initiatives
        {activeCount > 0 && (
          <a className="reset" onClick={resetAll}>Reset all filters →</a>
        )}
      </div>

      {visible.includes('pillar') && (
        <FilterSection title="Pillar" onClear={() => clear('pillar')} showClear={filters.pillar?.length > 0}>
          {pillar.order.map((p) => (
            <FilterChip
              key={p}
              label={pillar.labels[p]}
              count={filteredOrgs.filter(o => o.pillar === p || (p !== 'both' && o.pillar === 'both')).length}
              active={(filters.pillar || []).includes(p)}
              onClick={() => toggle('pillar', p)}
              swatch={PILLAR_COLORS[p]}
            />
          ))}
        </FilterSection>
      )}

      {visible.includes('barriers') && (
        <FilterSection title="Barrier addressed" onClear={() => clear('barriers')} showClear={filters.barriers.length > 0}>
          {barriers.order.map((b) => (
            <FilterChip
              key={b}
              label={b}
              count={countOf('barriers', b)}
              active={filters.barriers.includes(b)}
              onClick={() => toggle('barriers', b)}
            />
          ))}
        </FilterSection>
      )}

      {visible.includes('regions') && (
        <FilterSection title="Region active" onClear={() => clear('regions')} showClear={filters.regions.length > 0}>
          {regions.order.map((r) => (
            <FilterChip
              key={r}
              label={regions.labels[r]}
              count={countOf('regions', r)}
              active={filters.regions.includes(r)}
              onClick={() => toggle('regions', r)}
            />
          ))}
        </FilterSection>
      )}

      {visible.includes('types') && (
        <FilterSection title="Organization type" onClear={() => clear('types')} showClear={filters.types.length > 0}>
          {types.order.map((t) => (
            <FilterChip
              key={t}
              label={types.labels[t]}
              count={countOf('type', t)}
              active={filters.types.includes(t)}
              onClick={() => toggle('types', t)}
            />
          ))}
        </FilterSection>
      )}

    </aside>
  );
}

window.FilterBar = FilterBar;
