// ════════════════════════════════════════════════════════════
// 권한관리 (마스터 전용) — 서브탭: 교육공무직 / 충실이
// ════════════════════════════════════════════════════════════
const PERM_FILTER_LABELS = { all: '전체', allowed: '허용', denied: '비허용' };

// 모드별 어댑터: list/bulk API, value 계산, update 페이로드 빌더 등
const PERM_MODES = {
  eduworks: {
    id: 'eduworks',
    label: '교육공무직 권한',
    title: '교육공무직관리프로그램 권한',
    desc: '회원별 edustaff(교육공무직) 서비스 접근 권한 — 기본값 차단, 명시적으로 허용한 회원만 접근 가능.',
    defaultAllowed: false,
    listApi: () => TSL_API.permissionsList().then(arr => ({
      items: arr.map(m => ({
        member_id: m.member_id,
        name: m.name || '',
        phone: m.phone || '',
        name_phone_key: m.name_phone_key || '',
        region: m.region || '',
        // eduworks 모드: allowed_servers 배열에 'eduworks' 있는지로 판단
        allowed: Array.isArray(m.allowed_servers) && m.allowed_servers.indexOf('eduworks') !== -1,
        source: 'main',
      })),
      sejong_error: null,
    })),
    bulkApi: (changes) => TSL_API.permissionsBulk(
      changes.map(c => ({ member_id: c.member_id, allowed_servers: c.allowed ? ['eduworks'] : [] }))
    ),
  },
  chungsil: {
    id: 'chungsil',
    label: '충실이 권한',
    title: '충실이 권한',
    desc: '회원별 충실이(chungsil.kr) AI 지침서 검색 서비스 이용 권한 — 기본값 허용, 명시적으로 차단된 회원만 차단됨.',
    defaultAllowed: true,
    listApi: () => TSL_API.chungsilPermissionsList().then(res => ({
      // ★세종 회원 화면 숨김 (프론트 필터, 가역) — 백엔드 브리지 통합조회는 그대로, 렌더 전 source==='sejong' 만 제외.
      //   원복: 아래 .filter(...) 한 줄만 삭제하면 세종 회원이 다시 표시됨.
      items: (res.items || []).filter(m => (m.source || 'main') !== 'sejong').map(m => ({
        member_id: m.member_id,
        name: m.name || '',
        phone: m.phone || '',
        name_phone_key: m.name_phone_key || '',
        region: m.region || '',
        // chungsil 모드: chungsil_blocked false/unset 이면 허용
        allowed: !m.chungsil_blocked,
        source: m.source || 'main',
      })),
      sejong_error: res.sejong_error || null,
    })),
    bulkApi: (changes) => TSL_API.chungsilPermissionsBulk(
      changes.map(c => ({
        member_id: c.member_id,
        chungsil_blocked: !c.allowed,
        source: c.source || 'main',
      }))
    ),
  },
};

// ────────────────────────────────────────────────────────────
// 권한관리 패널 — 모드별로 같은 UI 로직 공유
// ────────────────────────────────────────────────────────────
const PermissionPanel = ({ mode }) => {
  const toast = useToast();

  const [items, setItems] = React.useState([]);
  const [loading, setLoading] = React.useState(true);
  const [errMsg, setErrMsg] = React.useState('');
  const [sejongWarn, setSejongWarn] = React.useState('');
  const [originalPerms, setOriginalPerms] = React.useState({});
  const [pendingPerms, setPendingPerms] = React.useState({});
  const [detailRegion, setDetailRegion] = React.useState(null);
  const [confirmModal, setConfirmModal] = React.useState(null);

  // 모달 검색/필터
  const [modalSearch, setModalSearch] = React.useState('');
  const [modalFilter, setModalFilter] = React.useState('all');
  // 모달 로컬 변경 (적용 누르기 전까지는 pendingPerms 안 건드림)
  const [modalLocal, setModalLocal] = React.useState({});

  // 개인별 조회 검색/필터
  const [lookupSearch, setLookupSearch] = React.useState('');
  const [lookupFilter, setLookupFilter] = React.useState('all');

  const reload = React.useCallback(async () => {
    setLoading(true);
    setErrMsg('');
    setSejongWarn('');
    try {
      const { items: rows, sejong_error } = await mode.listApi();
      const orig = {};
      rows.forEach(r => { orig[r.member_id] = !!r.allowed; });
      setItems(rows);
      setOriginalPerms(orig);
      setPendingPerms({ ...orig });
      if (sejong_error) setSejongWarn('세종 서버 동기화 경고: ' + sejong_error);
    } catch (e) {
      console.error(e);
      setErrMsg('권한 목록 로드 실패: ' + (e.message || e));
    } finally {
      setLoading(false);
    }
  }, [mode]);
  React.useEffect(() => { reload(); }, [reload]);

  // 안전 접근자 — pendingPerms/originalPerms에 키 없으면 mode.defaultAllowed 폴백 (race/누락 대응)
  const effectivePending = React.useCallback((id) =>
    pendingPerms.hasOwnProperty(id) ? pendingPerms[id] : mode.defaultAllowed
  , [pendingPerms, mode]);
  const effectiveOriginal = React.useCallback((id) =>
    originalPerms.hasOwnProperty(id) ? originalPerms[id] : mode.defaultAllowed
  , [originalPerms, mode]);

  const pendingCount = React.useMemo(() =>
    items.filter(m => effectivePending(m.member_id) !== effectiveOriginal(m.member_id)).length
  , [items, effectivePending, effectiveOriginal]);

  const regions = React.useMemo(() => {
    const groups = {};
    items.forEach(m => {
      const r = m.region || '(미지정)';
      if (!groups[r]) groups[r] = [];
      groups[r].push(m);
    });
    return Object.entries(groups)
      .map(([name, members]) => ({
        name, members,
        total: members.length,
        allowed: members.filter(m => effectivePending(m.member_id)).length,
        hasChange: members.some(m => effectivePending(m.member_id) !== effectiveOriginal(m.member_id)),
      }))
      .sort((a, b) => a.name.localeCompare(b.name, 'ko'));
  }, [items, effectivePending, effectiveOriginal]);

  const setRegionAll = (regionName, value) => {
    const target = items.filter(m => (m.region || '(미지정)') === regionName);
    setPendingPerms(prev => {
      const next = { ...prev };
      target.forEach(m => { next[m.member_id] = value; });
      return next;
    });
  };

  const toggleMember = (memberId) => {
    setPendingPerms(prev => {
      const cur = prev.hasOwnProperty(memberId) ? prev[memberId] : mode.defaultAllowed;
      return { ...prev, [memberId]: !cur };
    });
  };

  const toggleInModal = (memberId, currentValue) => {
    setModalLocal(prev => {
      const next = { ...prev };
      const newVal = !currentValue;
      const basePending = effectivePending(memberId);
      if (newVal === basePending) delete next[memberId];
      else next[memberId] = newVal;
      return next;
    });
  };

  const allowedInModal = (memberId) =>
    modalLocal.hasOwnProperty(memberId) ? modalLocal[memberId] : effectivePending(memberId);

  const applyModal = () => {
    if (Object.keys(modalLocal).length > 0) {
      setPendingPerms(prev => ({ ...prev, ...modalLocal }));
    }
    setModalLocal({});
    setDetailRegion(null);
  };

  const cancelModal = () => {
    setModalLocal({});
    setDetailRegion(null);
  };

  const onRevert = () => {
    if (pendingCount === 0) return;
    setConfirmModal({
      title: '되돌리기',
      msg: '미저장 변경 ' + pendingCount + '건을 모두 되돌립니다.',
      tone: 'warn',
      onYes: () => setPendingPerms({ ...originalPerms })
    });
  };

  const onSave = () => {
    const changes = [];
    items.forEach(m => {
      const id = m.member_id;
      const pend = effectivePending(id);
      const orig = effectiveOriginal(id);
      if (pend !== orig) {
        changes.push({ member_id: id, allowed: pend, source: m.source || 'main' });
      }
    });
    if (changes.length === 0) return;
    setConfirmModal({
      title: '저장',
      msg: changes.length + '건의 변경사항을 저장합니다.\n저장 후에는 되돌리기 버튼으로 복원할 수 없습니다.',
      confirmLabel: '저장',
      onYes: async () => {
        try {
          const data = await mode.bulkApi(changes);
          const succ = (data && data.succeeded != null) ? data.succeeded : changes.length;
          const failed = (data && data.failed) || 0;
          if (failed > 0) {
            toast('warn', '일부 실패: ' + succ + '/' + changes.length + (data && data.sejong_error ? ' (세종: ' + data.sejong_error + ')' : ''));
          } else {
            toast('success', '저장 완료 (' + succ + '/' + changes.length + ')');
          }
          setOriginalPerms({ ...pendingPerms });
          // 세종 부분 실패가 있었다면 재조회로 정확한 상태 동기화
          if (failed > 0 || (data && data.sejong_error)) {
            await reload();
          }
        } catch (e) {
          toast('error', '저장 실패: ' + (e.message || e));
        }
      }
    });
  };

  const hasLookupFilter = !!lookupSearch.trim() || lookupFilter !== 'all';
  const lookupResults = React.useMemo(() => {
    if (!hasLookupFilter) return [];
    let rows = items.slice();
    if (lookupFilter === 'allowed') rows = rows.filter(m => effectivePending(m.member_id));
    else if (lookupFilter === 'denied') rows = rows.filter(m => !effectivePending(m.member_id));
    if (lookupSearch.trim()) {
      const s = lookupSearch.trim().toLowerCase();
      // DB는 name 앞 2글자만 저장 — 입력의 앞 2글자로 name 매칭, 고유번호는 전체 입력 사용
      const nameKey = s.slice(0, 2);
      rows = rows.filter(m =>
        (nameKey && (m.name || '').toLowerCase().includes(nameKey)) ||
        (m.name_phone_key || '').toLowerCase().includes(s)
      );
    }
    rows.sort((a, b) =>
      (a.region || '').localeCompare(b.region || '', 'ko') ||
      (a.name || '').localeCompare(b.name || '', 'ko')
    );
    return rows;
  }, [items, lookupSearch, lookupFilter, effectivePending, hasLookupFilter]);

  return (
    <div>
      <SectionHeader title={mode.title} desc={mode.desc} />

      {sejongWarn && (
        <Card style={{ marginBottom: 12, borderColor: 'oklch(0.78 0.12 60)', background: 'oklch(0.98 0.03 60)' }}>
          <div style={{ color: 'oklch(0.50 0.14 60)', fontSize: 12.5, padding: '8px 12px' }}>⚠ {sejongWarn}</div>
        </Card>
      )}

      <Toolbar style={{ marginBottom: 16 }}>
        <span style={{
          color: pendingCount > 0 ? 'var(--danger)' : 'var(--ink-3)',
          fontSize: 13, fontWeight: 600,
        }}>
          {pendingCount > 0 ? '● 미저장 ' + pendingCount + '건' : '변경 없음'}
        </span>
        <span style={{ marginLeft: 'auto' }} />
        <Button onClick={onRevert} disabled={pendingCount === 0}>되돌리기</Button>
        <Button variant="primary" onClick={onSave} disabled={pendingCount === 0}>저장</Button>
      </Toolbar>

      {errMsg && (
        <Card style={{ marginBottom: 16, borderColor: 'var(--danger)' }}>
          <div style={{ color: 'var(--danger)', fontSize: 13 }}>{errMsg}</div>
        </Card>
      )}

      {loading && <div style={{ padding: 60, textAlign: 'center', color: 'var(--ink-3)' }}>로딩 중...</div>}

      {!loading && regions.length === 0 && !errMsg && (
        <EmptyState title="회원이 없습니다" />
      )}

      {!loading && regions.length > 0 && (
        <div style={{
          display: 'grid',
          gridTemplateColumns: 'repeat(auto-fill, minmax(220px, 1fr))',
          gap: 12,
          marginBottom: 28,
        }}>
          {regions.map(r => {
            const allAllowed  = r.allowed === r.total;
            const noneAllowed = r.allowed === 0;
            return (
              <div key={r.name} style={{
                border: '1px solid ' + (r.hasChange ? '#facc15' : 'var(--line)'),
                borderRadius: 12,
                padding: 14,
                background: r.hasChange ? '#fffbeb' : '#fff',
                position: 'relative',
              }}>
                {r.hasChange && (
                  <span style={{ position: 'absolute', top: 10, right: 12, fontSize: 10, color: '#d97706', fontWeight: 700 }}>● 변경</span>
                )}
                <div style={{ fontSize: 15, fontWeight: 700, marginBottom: 6, color: 'var(--ink)' }}>{r.name}</div>
                <div style={{ fontSize: 12, color: 'var(--ink-3)', marginBottom: 10 }}>
                  총 {r.total}명 · 허용 {' '}
                  <strong style={{
                    color: allAllowed ? 'oklch(0.55 0.16 155)'
                         : noneAllowed ? 'var(--ink-3)'
                         : 'oklch(0.62 0.16 75)'
                  }}>{r.allowed}</strong>/{r.total}
                </div>
                <div style={{ display: 'flex', gap: 6, marginBottom: 8 }}>
                  <button onClick={() => setRegionAll(r.name, true)} disabled={allAllowed}
                    style={pillBtnStyle('oklch(0.55 0.16 155)', allAllowed)}>모두 허용</button>
                  <button onClick={() => setRegionAll(r.name, false)} disabled={noneAllowed}
                    style={pillBtnStyle('var(--danger)', noneAllowed)}>모두 차단</button>
                </div>
                <button
                  onClick={() => { setModalSearch(''); setModalFilter('all'); setModalLocal({}); setDetailRegion(r.name); }}
                  style={{
                    width: '100%', padding: '7px 10px', fontSize: 12,
                    color: 'var(--ink-2)', background: '#f1f5f9',
                    border: '1px solid var(--line)', borderRadius: 8,
                    cursor: 'pointer', fontWeight: 500,
                  }}>회원별 권한</button>
              </div>
            );
          })}
        </div>
      )}

      {!loading && items.length > 0 && (
        <div style={{ marginTop: 8 }}>
          <SectionHeader title="개인별 권한 조회" desc="이름이나 고유번호로 검색해 개별 권한을 토글할 수 있습니다." />
          <Toolbar style={{ marginBottom: 12 }}>
            <TextInput placeholder="이름 또는 고유번호"
              value={lookupSearch} onChange={setLookupSearch} width={260} />
            {Object.entries(PERM_FILTER_LABELS).map(([key, label]) => (
              <Chip key={key} active={lookupFilter === key} onClick={() => setLookupFilter(key)}>{label}</Chip>
            ))}
            <span style={{ marginLeft: 'auto', fontSize: 12, color: 'var(--ink-3)' }}>{lookupResults.length}건</span>
          </Toolbar>
          {!hasLookupFilter ? (
            <EmptyState title={`이름·고유번호로 검색하거나 ${PERM_FILTER_LABELS.allowed}/${PERM_FILTER_LABELS.denied} 필터를 선택해주세요`} />
          ) : lookupResults.length === 0 ? (
            <EmptyState title="조건에 맞는 회원이 없습니다" />
          ) : (
            <div style={{ border: '1px solid var(--line)', borderRadius: 10, overflow: 'hidden', maxHeight: 480, overflowY: 'auto' }}>
              <table style={{ width: '100%', fontSize: 13, borderCollapse: 'collapse' }}>
                <thead>
                  <tr style={{ background: '#fafbfc', position: 'sticky', top: 0 }}>
                    <th style={{ textAlign: 'left', padding: '10px 14px', fontSize: 12, color: 'var(--ink-3)', borderBottom: '1px solid var(--line)' }}>지역</th>
                    <th style={{ textAlign: 'left', padding: '10px 14px', fontSize: 12, color: 'var(--ink-3)', borderBottom: '1px solid var(--line)' }}>이름</th>
                    <th style={{ textAlign: 'left', padding: '10px 14px', fontSize: 12, color: 'var(--ink-3)', borderBottom: '1px solid var(--line)' }}>고유번호</th>
                    <th style={{ textAlign: 'right', padding: '10px 14px', fontSize: 12, color: 'var(--ink-3)', borderBottom: '1px solid var(--line)' }}>권한</th>
                  </tr>
                </thead>
                <tbody>
                  {lookupResults.map((m, idx) => {
                    const allowed = effectivePending(m.member_id);
                    const changed = effectivePending(m.member_id) !== effectiveOriginal(m.member_id);
                    return (
                      <tr key={m.member_id + '_' + idx} style={{
                        borderBottom: '1px solid var(--line)',
                        background: changed ? '#fffbeb' : 'transparent',
                      }}>
                        <td style={{ padding: '8px 14px', color: 'var(--ink-2)' }}>{m.region || '-'}</td>
                        <td style={{ padding: '8px 14px', fontWeight: 500 }}>{m.name}</td>
                        <td style={{ padding: '8px 14px', color: 'var(--ink-3)', fontFamily: 'ui-monospace, monospace' }}>{m.name_phone_key}</td>
                        <td style={{ padding: '8px 14px', textAlign: 'right' }}>
                          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
                            <span style={{
                              fontSize: 12, fontWeight: 600,
                              color: allowed ? 'oklch(0.55 0.16 155)' : 'var(--ink-3)'
                            }}>{allowed ? '허용' : '차단'}</span>
                            <Toggle value={allowed} onChange={() => toggleMember(m.member_id)} />
                          </div>
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            </div>
          )}
        </div>
      )}

      {/* 회원별 세부 모달 */}
      <Modal
        open={!!detailRegion}
        onClose={cancelModal}
        title={(detailRegion || '') + ' — 회원별 권한'}
        width={580}
      >
        {detailRegion && (() => {
          let list = items.filter(m => (m.region || '(미지정)') === detailRegion);
          if (modalFilter === 'allowed') list = list.filter(m => allowedInModal(m.member_id));
          else if (modalFilter === 'denied') list = list.filter(m => !allowedInModal(m.member_id));
          if (modalSearch.trim()) {
            const s = modalSearch.trim().toLowerCase();
            const nameKey = s.slice(0, 2);
            list = list.filter(m =>
              (nameKey && (m.name || '').toLowerCase().includes(nameKey)) ||
              (m.name_phone_key || '').toLowerCase().includes(s)
            );
          }
          return (
            <div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12, paddingBottom: 10, borderBottom: '1px solid var(--line)' }}>
                <div style={{ flex: 1, display: 'flex', alignItems: 'center', gap: 6, overflow: 'hidden', minHeight: 26 }}>
                  {Object.keys(modalLocal).length === 0 ? (
                    <span style={{ fontSize: 12, color: 'var(--ink-3)' }}>변경된 내용이 없습니다</span>
                  ) : (
                    <>
                      <span style={{ fontSize: 12, color: 'var(--danger)', fontWeight: 700, whiteSpace: 'nowrap' }}>변경 {Object.keys(modalLocal).length}건</span>
                      <div style={{ flex: 1, display: 'flex', gap: 4, overflowX: 'auto', flexWrap: 'nowrap' }}>
                        {Object.keys(modalLocal).map(id => {
                          const m = items.find(x => x.member_id === id);
                          const willBeAllowed = modalLocal[id];
                          return (
                            <span key={id} style={{
                              display: 'inline-flex', alignItems: 'center', gap: 4,
                              padding: '3px 9px', borderRadius: 999,
                              background: willBeAllowed ? 'oklch(0.95 0.05 155)' : 'oklch(0.95 0.05 25)',
                              color: willBeAllowed ? 'oklch(0.42 0.14 155)' : 'oklch(0.50 0.17 25)',
                              fontSize: 11, fontWeight: 600, whiteSpace: 'nowrap', flexShrink: 0,
                            }}>{m?.name || '?'} · {willBeAllowed ? '허용' : '차단'}</span>
                          );
                        })}
                      </div>
                    </>
                  )}
                </div>
                <Button variant="primary" onClick={applyModal}>적용</Button>
              </div>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12, flexWrap: 'wrap' }}>
                <TextInput placeholder="이름 또는 고유번호 검색"
                  value={modalSearch} onChange={setModalSearch} width={220} />
                {Object.entries(PERM_FILTER_LABELS).map(([key, label]) => (
                  <Chip key={key} active={modalFilter === key} onClick={() => setModalFilter(key)}>{label}</Chip>
                ))}
                <span style={{ marginLeft: 'auto', fontSize: 12, color: 'var(--ink-3)' }}>{list.length}건</span>
              </div>
              {list.length === 0 ? (
                <div style={{ padding: 30, textAlign: 'center', color: 'var(--ink-3)' }}>해당 조건의 회원이 없습니다.</div>
              ) : (
                <div style={{ maxHeight: '50vh', overflowY: 'auto', border: '1px solid var(--line)', borderRadius: 8 }}>
                  <table style={{ width: '100%', fontSize: 13, borderCollapse: 'collapse' }}>
                    <thead>
                      <tr>
                        <th style={{ textAlign: 'left', padding: '10px 14px', fontSize: 12, color: 'var(--ink-3)', borderBottom: '1px solid var(--line)', background: '#fafbfc', position: 'sticky', top: 0, zIndex: 2 }}>이름</th>
                        <th style={{ textAlign: 'left', padding: '10px 14px', fontSize: 12, color: 'var(--ink-3)', borderBottom: '1px solid var(--line)', background: '#fafbfc', position: 'sticky', top: 0, zIndex: 2 }}>고유번호</th>
                        <th style={{ textAlign: 'right', padding: '10px 14px', fontSize: 12, color: 'var(--ink-3)', borderBottom: '1px solid var(--line)', background: '#fafbfc', position: 'sticky', top: 0, zIndex: 2 }}>권한</th>
                      </tr>
                    </thead>
                    <tbody>
                      {list.map((m, idx) => {
                        const allowed = allowedInModal(m.member_id);
                        const inModalChange = modalLocal.hasOwnProperty(m.member_id);
                        return (
                          <tr key={m.member_id + '_' + idx} style={{
                            borderBottom: '1px solid var(--line)',
                            background: inModalChange ? '#fffbeb' : 'transparent',
                          }}>
                            <td style={{ padding: '10px 14px', fontWeight: 500 }}>{m.name}</td>
                            <td style={{ padding: '10px 14px', color: 'var(--ink-3)', fontFamily: 'ui-monospace, monospace' }}>{m.name_phone_key}</td>
                            <td style={{ padding: '10px 14px', textAlign: 'right' }}>
                              <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8 }}>
                                <span style={{
                                  fontSize: 12, fontWeight: 600,
                                  color: allowed ? 'oklch(0.55 0.16 155)' : 'var(--ink-3)'
                                }}>{allowed ? '허용' : '차단'}</span>
                                <Toggle value={allowed} onChange={() => toggleInModal(m.member_id, allowed)} />
                              </div>
                            </td>
                          </tr>
                        );
                      })}
                    </tbody>
                  </table>
                </div>
              )}
            </div>
          );
        })()}
      </Modal>

      <ConfirmDialog
        open={!!confirmModal}
        title={confirmModal?.title || ''}
        message={confirmModal?.msg || ''}
        tone={confirmModal?.tone}
        confirmLabel={confirmModal?.confirmLabel || '확인'}
        onClose={() => setConfirmModal(null)}
        onConfirm={() => {
          const fn = confirmModal?.onYes;
          if (typeof fn === 'function') fn();
        }}
      />
    </div>
  );
};

// ────────────────────────────────────────────────────────────
// MemberPermissionsView — 서브탭 래퍼 (교육공무직 / 충실이)
// ────────────────────────────────────────────────────────────
const MemberPermissionsView = () => {
  const [tab, setTab] = React.useState('chungsil');
  const modeIds = ['chungsil', 'eduworks'];
  return (
    <div>
      <div style={{
        display: 'flex', gap: 2, marginBottom: 14,
        borderBottom: '1px solid var(--line)',
      }}>
        {modeIds.map(id => {
          const m = PERM_MODES[id];
          const active = tab === id;
          return (
            <button key={id} onClick={() => setTab(id)} style={{
              padding: '10px 18px', fontSize: 13.5, fontWeight: active ? 700 : 500,
              color: active ? 'var(--accent-ink)' : 'var(--ink-3)',
              background: 'transparent', border: 'none',
              borderBottom: '2px solid ' + (active ? 'var(--accent)' : 'transparent'),
              marginBottom: -1, cursor: 'pointer', fontFamily: 'inherit',
            }}>{m.label}</button>
          );
        })}
      </div>
      {/* key prop으로 탭 전환 시 state 초기화 — 모드 간 cross-contamination 방지 */}
      <PermissionPanel key={tab} mode={PERM_MODES[tab]} />
    </div>
  );
};

function pillBtnStyle(color, disabled) {
  return {
    flex: 1, padding: '7px 10px', fontSize: 12, fontWeight: 600,
    color: '#fff', background: disabled ? '#cbd5e1' : color,
    border: 0, borderRadius: 8,
    cursor: disabled ? 'not-allowed' : 'pointer',
  };
}

Object.assign(window, { MemberPermissionsView });
