// ============================================================
//   FilterBar — the shipped filter row + popover, shared by every layout.
//
//   Modelled on production rather than invented: the row is the existing
//   select-all + "Most recent conversations" + sort-direction control, and the
//   popover is the shipped VIEW / CONVERSATIONS / SORT panel — radios, not
//   dropdowns, with "Unreads only" disabled unless you're on My conversations.
//
//   SOURCE is added as a new section rather than a separate control on the
//   bar. That's a deliberate demotion: the evidence on applied-vs-sourced
//   splits by segment (staffing adamant, direct employers indifferent), so it
//   doesn't earn a permanent slot in the panel's most valuable row. The cost
//   is that we can no longer watch whether people reach for it unprompted.
// ============================================================
const { color: FB } = window.FF;

const FB_SORTS = [
  { v:'recent',  label:'Most recent message' },
  { v:'score',   label:'Applicant Score' },
  { v:'applied', label:'Date of application' },
];
const FB_SOURCES = [
  { v:'all',     label:'All' },
  { v:'applied', label:'Applicant' },
  { v:'sourced', label:'AI Sourced' },
];

function useFilterBar() {
  const [source, setSource]         = React.useState('all');
  const [conversations, setConv]    = React.useState('all');   // all | my
  const [unreadOnly, setUnreadOnly] = React.useState(false);
  const [sort, setSort]             = React.useState('recent');
  const [desc, setDesc]             = React.useState(true);

  // Unreads only is meaningless across the whole account, so production gates
  // it behind My conversations — mirror that rather than letting it apply.
  const unreadActive = unreadOnly && conversations === 'my';

  const matchSource    = (c) => source === 'all' || (c && c.source === source);
  const matchSecondary = (c) =>
    (conversations === 'all' || (c && c.mine)) && (!unreadActive || (c && c.unread));

  const sortFn = {
    recent:  () => 0,
    score:   (a, b) => (b.score || 0) - (a.score || 0),
    applied: (a, b) => (a.appliedAge || 99) - (b.appliedAge || 99),
  }[sort];

  return {
    source, setSource, conversations, setConv, unreadOnly, setUnreadOnly,
    sort, setSort, desc, setDesc, unreadActive,
    matchSource, matchSecondary,
    sortFn: (a, b) => (desc ? 1 : -1) * sortFn(a, b),
    active: source !== 'all' || conversations !== 'all' || unreadActive || sort !== 'recent',
    sortLabel: FB_SORTS.find(s => s.v === sort).label,
    clear: () => { setSource('all'); setConv('all'); setUnreadOnly(false); setSort('recent'); setDesc(true); },
  };
}

function FilterBar({ f }) {
  const [open, setOpen] = React.useState(false);

  const Section = ({ label, children }) => (
    <div style={{ padding:'10px 0 2px' }}>
      <div style={{ fontSize:10, fontWeight:800, letterSpacing:'.07em', textTransform:'uppercase', color: FB.shade[800], marginBottom:7 }}>{label}</div>
      {children}
    </div>
  );
  const Radio = ({ on, label, onClick, disabled }) => (
    <button onClick={onClick} disabled={disabled} style={{
      display:'flex', alignItems:'center', gap:9, width:'100%', textAlign:'left',
      padding:'6px 0', background:'transparent', border:0,
      cursor: disabled ? 'not-allowed' : 'pointer', opacity: disabled ? .45 : 1,
    }}>
      <span style={{
        width:15, height:15, borderRadius:'50%', flex:'none', display:'inline-flex',
        alignItems:'center', justifyContent:'center',
        border:`1.5px solid ${on ? FB.highlight[500] : FB.tint[100]}`, background:'#fff',
      }}>
        {on && <span style={{ width:7, height:7, borderRadius:'50%', background: FB.highlight[500] }}/>}
      </span>
      <span style={{ fontSize:13, color: FB.shade[880] }}>{label}</span>
    </button>
  );
  const Switch = ({ on, onClick, label, disabled }) => (
    <div style={{ display:'flex', alignItems:'center', gap:9, padding:'2px 0', opacity: disabled ? .45 : 1 }}>
      <button onClick={onClick} role="switch" aria-checked={on} disabled={disabled} style={{
        width:34, height:20, borderRadius:9999, border:0, padding:2, flex:'none',
        cursor: disabled ? 'not-allowed' : 'pointer',
        background: on ? FB.highlight[500] : FB.tint[100], transition:'background .12s',
      }}>
        <span style={{ display:'block', width:16, height:16, borderRadius:'50%', background:'#fff',
          transform: on ? 'translateX(14px)' : 'none', transition:'transform .12s', boxShadow:'0 1px 2px rgba(0,0,0,.2)' }}/>
      </button>
      <span style={{ fontSize:13, color: disabled ? FB.shade[800] : FB.shade[880] }}>{label}</span>
    </div>
  );

  return (
    <div style={{ padding:'12px 16px 8px', display:'flex', alignItems:'center', justifyContent:'space-between', position:'relative' }}>
      {/* Left: production's select-all cluster */}
      <div style={{ display:'flex', alignItems:'center', gap:8 }}>
        <input type="checkbox" style={{ width:16, height:16, accentColor: FB.highlight[500] }}/>
        <img src="assets/icons/chevron-down.svg" width={14} height={14}/>
      </div>

      {/* Right: the sort/filter trigger + direction, as shipped */}
      <div style={{ display:'flex', alignItems:'center', gap:10 }}>
        <button onClick={() => setOpen(o => !o)} style={{
          display:'inline-flex', alignItems:'center', gap:7, padding:'6px 10px',
          background: f.active ? FB.highlight[50] : FB.tint[20],
          border:`1px solid ${f.active ? FB.highlight[500] : FB.tint[80]}`,
          borderRadius:6, fontSize:12, fontWeight:600, color: FB.shade[820], cursor:'pointer',
        }}>
          {f.sortLabel}
          <img src="assets/icons/filter-lines-20.svg" width={14} height={14}/>
        </button>
        <button onClick={() => f.setDesc(!f.desc)} title={f.desc ? 'Descending' : 'Ascending'} style={{
          background:'transparent', border:0, cursor:'pointer', padding:2, lineHeight:1,
          fontSize:14, color: FB.shade[820], transform: f.desc ? 'none' : 'scaleY(-1)',
        }}>⇅</button>
      </div>

      {open && (
        <React.Fragment>
          <div onClick={() => setOpen(false)} style={{ position:'fixed', inset:0, zIndex:19 }}/>
          <div style={{
            position:'absolute', top:'100%', right:16, zIndex:20, width:268,
            background:'#fff', border:`1px solid ${FB.tint[100]}`, borderRadius:10,
            boxShadow:'0 8px 28px rgba(13,10,44,.16)', padding:'6px 16px 14px',
          }}>
            <Section label="Source">
              {FB_SOURCES.map(s => (
                <Radio key={s.v} on={f.source === s.v} label={s.label} onClick={() => f.setSource(s.v)}/>
              ))}
            </Section>
            <div style={{ height:1, background: FB.tint[60] }}/>
            <Section label="View">
              <Switch on={f.unreadActive} label="Unreads only" disabled={f.conversations !== 'my'}
                onClick={() => f.setUnreadOnly(v => !v)}/>
            </Section>
            <div style={{ height:1, background: FB.tint[60] }}/>
            <Section label="Conversations">
              <Radio on={f.conversations === 'all'} label="All conversations" onClick={() => f.setConv('all')}/>
              <Radio on={f.conversations === 'my'}  label="My conversations"  onClick={() => f.setConv('my')}/>
            </Section>
            <div style={{ height:1, background: FB.tint[60] }}/>
            <Section label="Sort">
              {FB_SORTS.map(s => (
                <Radio key={s.v} on={f.sort === s.v} label={s.label} onClick={() => f.setSort(s.v)}/>
              ))}
            </Section>
          </div>
        </React.Fragment>
      )}
    </div>
  );
}

// Off-filter attention items fold rather than vanish — a filter must never
// silently suppress attention.
function FoldedAttention({ n, otherSource, open, onToggle, children }) {
  if (!n) return null;
  return (
    <div style={{ borderTop:`1px solid ${FB.tint[80]}`, background: FB.tint[20] + '55' }}>
      <button onClick={onToggle} aria-expanded={open} style={{
        width:'100%', textAlign:'left', display:'flex', alignItems:'center', gap:7,
        padding:'10px 16px', background:'transparent', border:0, cursor:'pointer',
        fontSize:11.5, fontWeight:700, color: FB.primary[600],
      }}>
        <span style={{ fontSize:14, lineHeight:1, width:12, display:'inline-block' }}>{open ? '–' : '+'}</span>
        {open ? `Hide ${n} ${otherSource}` : `Show ${n} ${otherSource} outside your filter`}
      </button>
      {open && children}
    </div>
  );
}

Object.assign(window, { useFilterBar, FilterBar, FoldedAttention });
