/* filter-core.jsx — Filter hub + sub-screens (Select Members → Filters) */
const { useState } = React;

/* Single-select per category. Realistic data. Search only on long lists. */
const FILTER_DATA = {
  type: { key: 'type', name: 'Type', search: false,
    options: ['Company', 'Department', 'State'] },
  aboveUnit: { key: 'aboveUnit', name: 'Above unit', search: true,
    options: ['North Region', 'South Region', 'East Region', 'West Region', 'Central Region', 'Corporate HQ', 'Field Operations', 'Franchise Group', 'Hospitality Division'] },
  unit: { key: 'unit', name: 'Unit', search: true,
    options: ['Operations', 'Front of House', 'Back of House', 'Northgate Store', 'Westfield Store', 'Riverside Store', 'Downtown Store', 'Distribution Center', 'Customer Care'] },
  job: { key: 'job', name: 'Job', search: true,
    options: ['Bartending', 'Catering', 'Chef', 'Cleaning', 'Hosting', 'Housekeeping', 'Roomservice', 'Serving', 'Sitecrew'] }
};
const CATS = [FILTER_DATA.type, FILTER_DATA.aboveUnit, FILTER_DATA.unit, FILTER_DATA.job];
const SUB_HREF = { type: 'filter-type.html', aboveUnit: 'filter-above-unit.html', unit: 'filter-unit.html', job: 'filter-job.html' };
const SELECT_MEMBERS_HREF = 'select-members.html?badge=fellow-helper';

const FKEY = 'sx_filters_v1';
function loadFilters() {try {return JSON.parse(localStorage.getItem(FKEY)) || {};} catch (e) {return {};}}
function saveFilters(f) {try {localStorage.setItem(FKEY, JSON.stringify(f));} catch (e) {}}
function anyActive(f) {return Object.values(f).some(Boolean);}
function hubHref(f) {return anyActive(f) ? 'filters-active.html' : 'filters-empty.html';}

/* =================== HUB =================== */
function FilterHub({ seed }) {
  const [filters, setFilters] = useState(() => {
    if (seed === 'empty') {saveFilters({});return {};}
    let f = loadFilters();
    if (seed === 'active' && !anyActive(f)) {
      f = { type: 'Company', aboveUnit: 'North Region', unit: 'Front of House', job: 'Serving' };
      saveFilters(f);
    }
    return f;
  });

  const active = anyActive(filters);
  const count = Object.values(filters).filter(Boolean).length;
  const update = (f) => {setFilters(f);saveFilters(f);};
  const clearOne = (key) => {const f = { ...filters };delete f[key];update(f);};
  const reset = () => update({});
  const close = () => {window.location.href = SELECT_MEMBERS_HREF;};

  return (
    <IOSDevice width={402} height={874}>
      <div className="app fh">
        <div className="flt-header">
          <button className="flt-nav" onClick={close} aria-label="Close filters"><Ic.Close s={21} c="var(--ink)" /></button>
          <div className="flt-title">Filters</div>
        </div>

        <div className="fh-body">
          <div className="fh-toprow">
            <span className="fh-section-label">Active filters{active ? ` · ${count}` : ''}</span>
            <button className="fh-reset" disabled={!active} onClick={reset}>
              <Ic.Refresh s={15} c={active ? 'var(--purple-strong)' : 'var(--ink-3)'} /> Reset filters
            </button>
          </div>

          <div className="fh-chipzone">
            {active ?
            CATS.filter((c) => filters[c.key]).map((c) =>
            <span key={c.key} className="fh-chip">
                    <span><b>{c.name}:</b> {filters[c.key]}</span>
                    <button className="fh-chip-x" onClick={() => clearOne(c.key)} aria-label={'Clear ' + c.name}><Ic.Close s={11} c="var(--purple-strong)" /></button>
                  </span>
            ) :
            <div className="fh-chip-empty">Filters you apply will appear here</div>}
          </div>

          <div className="fh-rows">
            {CATS.map((c) => {
              const v = filters[c.key];
              return (
                <button key={c.key} className="fh-row" onClick={() => {window.location.href = SUB_HREF[c.key];}}>
                  <span className="fh-row-label">{c.name}</span>
                  <span className={'fh-row-value' + (v ? ' set' : '')}>{v || 'Any'}</span>
                  <span className="fh-row-chev"><Ic.ChevronRight s={18} c="var(--ink-3)" /></span>
                </button>);

            })}
          </div>
        </div>

        <div className="flt-footer">
          <div className="fh-hint">{active ? `${count} filter${count > 1 ? 's' : ''} applied` : 'No filters — all members will be shown'}</div>
          <button className="flt-cta" onClick={close}>Select members</button>
        </div>
      </div>
    </IOSDevice>);

}

/* =================== SUB-SCREEN =================== */
function FilterSubScreen({ catKey }) {
  const cat = FILTER_DATA[catKey];
  const [sel, setSel] = useState(() => loadFilters()[cat.key] || null);
  const [q, setQ] = useState('');

  const list = cat.options.filter((o) => !cat.search || o.toLowerCase().includes(q.trim().toLowerCase()));

  const back = () => {window.location.href = hubHref(loadFilters());};
  const apply = () => {
    const f = loadFilters();
    if (sel) f[cat.key] = sel;else delete f[cat.key];
    saveFilters(f);
    window.location.href = hubHref(f);
  };

  return (
    <IOSDevice width={402} height={874}>
      <div className="app fs">
        <div className="flt-header">
          <button className="flt-nav" onClick={back} aria-label="Back to Filters">
            <Ic.ChevronLeft s={20} c="var(--ink)" /><span className="flt-nav-lbl">Filters</span>
          </button>
          <div className="flt-title">Filters</div>
        </div>

        <div className="fs-body">
          <h2 className="fs-cat">{cat.name}</h2>

          {cat.search &&
          <div className="fs-search">
              <div className="search" style={{ height: 46 }}>
                <Ic.Search s={19} />
                <input value={q} onChange={(e) => setQ(e.target.value)} placeholder={'Search ' + cat.name.toLowerCase()} aria-label="Search" />
                {q && <button className="filter-btn" onClick={() => setQ('')} aria-label="Clear"><Ic.Close s={16} /></button>}
              </div>
            </div>
          }

          {list.length === 0 ?
          <div className="fs-empty">No options match “{q.trim()}”.</div> :
          list.map((o) => {
            const on = sel === o;
            return (
              <button key={o} className={'fs-opt' + (on ? ' sel' : '')} onClick={() => setSel(on ? null : o)} role="radio" aria-checked={on}>
                    <span className="fs-radio">{on && <span className="fs-dot"></span>}</span>
                    <span className="fs-opt-label">{o}</span>
                  </button>);

          })}
        </div>

        <div className="flt-footer">
          <div className="fs-hint">{sel ? `Apply “${sel}”` : 'No selection — applying clears this filter'}</div>
          <button className="flt-cta" onClick={apply}>Apply</button>
        </div>
      </div>
    </IOSDevice>);

}

Object.assign(window, { FilterHub, FilterSubScreen, FILTER_DATA });