// itrymo — Input-driven filter variant
// Sort: compact (top 2 + More); Tags: one input per group with scoped autosuggest.

// ─────────────────────────────────────────────────────────────
// CompactSort — top N options shown; rest behind "More"
// ─────────────────────────────────────────────────────────────
function CompactSort({ value, onChange, primaryCount = 2 }) {
  const [open, setOpen] = React.useState(false);
  const primary = SORTS.slice(0, primaryCount);
  const overflow = SORTS.slice(primaryCount);
  const inOverflow = overflow.find((s) => s.id === value);
  return (
    <div style={{ display: 'flex', gap: 6, alignItems: 'center', position: 'relative' }}>
      {primary.map((s) => {
        const on = s.id === value;
        return (
          <button key={s.id} onClick={() => onChange(s.id)} style={{
            all: 'unset', cursor: 'pointer',
            height: 34, padding: '0 12px', borderRadius: 10,
            background: on ? T.selBg : '#fff',
            color: on ? T.selFg : T.faintInk,
            border: `1px solid ${on ? T.selBg : T.border}`,
            fontSize: 12, fontWeight: 600, whiteSpace: 'nowrap',
          }}>{s.label}</button>
        );
      })}
      <button onClick={() => setOpen((v) => !v)} style={{
        all: 'unset', cursor: 'pointer',
        height: 34, padding: '0 12px', borderRadius: 10,
        background: inOverflow ? T.selBg : '#fff',
        color: inOverflow ? T.selFg : T.muted,
        border: `1px solid ${inOverflow ? T.selBg : T.border}`,
        display: 'inline-flex', alignItems: 'center', gap: 4, fontSize: 12, fontWeight: 600,
      }}>
        {inOverflow ? inOverflow.label : 'More'}
        <Icon name="chev" size={10} />
      </button>
      {open && (
        <>
          <div onClick={() => setOpen(false)} style={{ position: 'fixed', inset: 0, zIndex: 40 }} />
          <div style={{
            position: 'absolute', top: 40, right: 0, zIndex: 50,
            minWidth: 220, background: '#fff', borderRadius: 12,
            border: `1px solid ${T.border}`, boxShadow: '0 12px 32px rgba(0,0,0,0.12)',
            padding: 6,
          }}>
            {SORTS.map((s) => {
              const on = s.id === value;
              return (
                <button key={s.id} onClick={() => { onChange(s.id); setOpen(false); }} style={{
                  all: 'unset', cursor: 'pointer', display: 'flex', width: '100%',
                  boxSizing: 'border-box',
                  padding: '8px 10px', borderRadius: 8, gap: 10, alignItems: 'flex-start',
                  background: on ? T.bg : 'transparent',
                }}>
                  <div style={{ width: 16, paddingTop: 2 }}>
                    {on && <Icon name="check" size={14} color={T.accent} />}
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13, fontWeight: 600 }}>{s.label}</div>
                    <div style={{ fontSize: 11, color: T.muted, marginTop: 1 }}>{s.hint}</div>
                  </div>
                </button>
              );
            })}
          </div>
        </>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// TagInput — single group: chips-inside-input + scoped autosuggest
// Short groups (<= SHORT_THRESHOLD tags) render as plain chip rows instead.
// ─────────────────────────────────────────────────────────────
const SHORT_GROUP_THRESHOLD = 7;

function TagInput({ groupLabel, tags, selected, onToggle, placeholder, tagCounts }) {
  // Short groups: just show all chips inline — faster than typing.
  if (tags.length <= SHORT_GROUP_THRESHOLD) {
    return (
      <div>
        <div style={{
          fontSize: 10, color: T.muted, letterSpacing: 0.6,
          textTransform: 'uppercase', fontWeight: 700, marginBottom: 6,
        }}>{groupLabel}</div>
        <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
          {tags.map((tg) => (
            <Pill key={tg} small active={selected.includes(tg)} onClick={() => onToggle(tg)}>
              {tg}
            </Pill>
          ))}
        </div>
      </div>
    );
  }

  return <TagInputCombobox
    groupLabel={groupLabel} tags={tags} selected={selected}
    onToggle={onToggle} placeholder={placeholder} tagCounts={tagCounts}
  />;
}

function TagInputCombobox({ groupLabel, tags, selected, onToggle, placeholder, tagCounts }) {
  const [query, setQuery] = React.useState('');
  const [focused, setFocused] = React.useState(false);
  const wrapRef = React.useRef(null);

  // Close dropdown on outside click
  React.useEffect(() => {
    if (!focused) return;
    const onDoc = (e) => {
      if (wrapRef.current && !wrapRef.current.contains(e.target)) setFocused(false);
    };
    document.addEventListener('mousedown', onDoc);
    return () => document.removeEventListener('mousedown', onDoc);
  }, [focused]);

  // Suggest within THIS group's tags only
  const suggestions = React.useMemo(() => {
    const fauxGroup = [{ id: 'g', label: groupLabel, tags }];
    if (!query) {
      // Empty input: show all tags alphabetically (preserves data-order intent)
      return tags
        .filter((t) => !selected.includes(t))
        .map((t) => ({ tag: t, group: groupLabel, groupId: 'g', count: (tagCounts.get(t) || 0), active: false }))
        .sort((a, b) => a.tag.localeCompare(b.tag));
    }
    return suggestTags(query, fauxGroup, tagCounts, selected, 12);
  }, [query, tags, selected, groupLabel, tagCounts]);

  return (
    <div ref={wrapRef} style={{ position: 'relative' }}>
      <div style={{
        fontSize: 10, color: T.muted, letterSpacing: 0.6,
        textTransform: 'uppercase', fontWeight: 700, marginBottom: 6,
      }}>{groupLabel}</div>

      <div onClick={() => setFocused(true)} style={{
        minHeight: 40, borderRadius: 12,
        background: '#fff',
        border: `1px solid ${focused ? T.selBg : T.border}`,
        padding: '5px 8px 5px 10px',
        display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 6,
        cursor: 'text', boxShadow: focused ? `0 0 0 3px ${T.accentBg}` : 'none',
        transition: 'border-color .15s, box-shadow .15s',
      }}>
        {selected.map((tg) => (
          <span key={tg} style={{
            display: 'inline-flex', alignItems: 'center', gap: 4,
            height: 24, padding: '0 4px 0 10px', borderRadius: 999,
            background: T.accentBg, color: T.accent,
            border: `1px solid ${T.accentBd}`,
            fontSize: 12, fontWeight: 500,
          }}>
            {tg}
            <button onClick={(e) => { e.stopPropagation(); onToggle(tg); }} style={{
              all: 'unset', cursor: 'pointer', width: 18, height: 18, borderRadius: 9,
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center', opacity: 0.85,
            }}>
              <Icon name="close" size={10} />
            </button>
          </span>
        ))}
        <input
          value={query}
          onChange={(e) => setQuery(e.target.value)}
          onFocus={() => setFocused(true)}
          placeholder={selected.length === 0 ? placeholder : ''}
          style={{
            all: 'unset', flex: 1, minWidth: 60,
            fontSize: 13, color: T.ink, fontFamily: T.fontUI,
            padding: '4px 2px',
          }}
        />
        {(query || focused) && (
          <button onClick={(e) => { e.stopPropagation(); setQuery(''); setFocused(false); }} style={{
            all: 'unset', cursor: 'pointer', color: T.muted, padding: 4,
          }}>
            <Icon name="chev" size={12} style={{ transform: focused ? 'rotate(180deg)' : 'none' }} />
          </button>
        )}
      </div>

      {focused && (
        <div style={{
          marginTop: 6,
          background: '#fff', borderRadius: 12, border: `1px solid ${T.border}`,
          boxShadow: '0 8px 24px rgba(0,0,0,0.08)',
          maxHeight: 260, overflowY: 'auto', padding: 6,
        }}>
          {suggestions.length === 0 ? (
            <div style={{ padding: '12px 10px', fontSize: 12, color: T.muted }}>
              {query ? `No matches in ${groupLabel}.` : 'All tags selected.'}
            </div>
          ) : (
            suggestions.map((s) => (
              <TagSuggestion key={s.tag} s={{ ...s, active: selected.includes(s.tag) }}
                             query={query} onToggle={onToggle} showGroup={false} />
            ))
          )}
          {selected.length > 0 && (
            <div style={{ borderTop: `1px solid ${T.borderSoft}`, marginTop: 4, padding: '8px 10px' }}>
              <button onClick={() => selected.forEach(onToggle)} style={{
                all: 'unset', cursor: 'pointer', fontSize: 12, color: T.accent, fontWeight: 600,
              }}>Clear {groupLabel}</button>
            </div>
          )}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { CompactSort, TagInput });
