/* global React, Icon, Card, Avatar, Pill, Button, Dropdown */
// Schools.ArtemenkoCRM — Сотрудники

const ROLE_META = {
  teacher: { label: 'Преподаватель', bg: 'var(--brand-soft)', fg: 'var(--brand-ink)' },
  manager: { label: 'Менеджер', bg: 'var(--green-bg)', fg: 'var(--green-ink)' },
  admin:   { label: 'Администратор', bg: 'var(--gold-soft)', fg: 'var(--gold-ink)' },
};
const STATUS_META = {
  active:   { label: 'Работает', dot: 'var(--green)', fg: 'var(--green-ink)' },
  vacation: { label: 'Отпуск', dot: 'var(--amber)', fg: 'var(--amber-ink)' },
  fired:    { label: 'Уволен', dot: 'var(--text-dim)', fg: 'var(--text-dim)' },
};

function Staff({ onToast, onAdd, onOpen }) {
  const { STAFF } = window.CRM_DATA;
  const [role, setRole] = React.useState(null);
  const [q, setQ] = React.useState('');
  const [hideFired, setHideFired] = React.useState(true);

  const roleOpts = [{ value: null, label: 'Все роли' }, { value: 'teacher', label: 'Преподаватели' }, { value: 'manager', label: 'Менеджеры' }, { value: 'admin', label: 'Администраторы' }];
  const firedCount = STAFF.filter(s => s.status === 'fired').length;
  const rows = STAFF.filter(s => {
    if (role && s.role !== role) return false;
    if (hideFired && s.status === 'fired') return false;
    if (q && !(`${s.name} ${s.tg} ${s.contact}`.toLowerCase().includes(q.toLowerCase()))) return false;
    return true;
  }).sort((a, b) => (a.status === 'fired' ? 1 : 0) - (b.status === 'fired' ? 1 : 0)); // уволенные — внизу

  const th = { textAlign: 'left', fontSize: 11.5, fontWeight: 700, letterSpacing: '0.04em', textTransform: 'uppercase', color: 'var(--text-dim)', padding: '0 18px 13px', whiteSpace: 'nowrap' };
  const td = { padding: '13px 18px', borderTop: '1px solid var(--border)', fontSize: 14, color: 'var(--text)', verticalAlign: 'middle' };

  const byRole = (r) => STAFF.filter(s => s.role === r && s.status === 'active').length;

  return (
    <div style={{ padding: '24px 32px 40px' }}>
      {/* KPI */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 20, marginBottom: 22 }}>
        {[['teacher', 'Преподаватели'], ['manager', 'Менеджеры'], ['admin', 'Администраторы']].map(([r, lbl]) => (
          <Card key={r} pad={20}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ width: 9, height: 9, borderRadius: '50%', background: ROLE_META[r].fg }} />
              <span style={{ fontSize: 13, fontWeight: 700, letterSpacing: '0.06em', textTransform: 'uppercase', color: 'var(--text-dim)' }}>{lbl}</span>
            </div>
            <div style={{ fontFamily: 'var(--font-mono)', fontSize: 26, fontWeight: 700, marginTop: 12, color: 'var(--text)' }}>{byRole(r)}</div>
          </Card>
        ))}
      </div>

      {/* Toolbar */}
      <div style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 10, marginBottom: 18 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, background: 'var(--bg-card)', border: '1px solid var(--border)', borderRadius: 'var(--radius-sm)', padding: '8px 12px', width: 240 }}>
          <Icon name="search" size={16} style={{ color: 'var(--text-dim)' }} />
          <input value={q} onChange={e => setQ(e.target.value)} placeholder="Поиск по сотрудникам…" style={{ border: 'none', outline: 'none', background: 'transparent', flex: 1, fontFamily: 'var(--font-sans)', fontSize: 13.5, color: 'var(--text)' }} />
        </div>
        <Dropdown value={role} onChange={setRole} options={roleOpts} placeholder="Все роли" width={180} />
        {firedCount > 0 && (
          <button onClick={() => setHideFired(v => !v)} style={{
            display: 'inline-flex', alignItems: 'center', gap: 7, padding: '8px 13px', cursor: 'pointer',
            background: hideFired ? 'var(--bg-card)' : 'var(--bg-soft)', border: '1px solid ' + (hideFired ? 'var(--border)' : 'var(--border-strong)'),
            borderRadius: 'var(--radius-sm)', fontFamily: 'var(--font-sans)', fontSize: 13.5, fontWeight: 600, color: 'var(--text-secondary)',
            transition: 'background var(--dur-fast) var(--ease), border-color var(--dur-fast) var(--ease)',
          }}>
            <Icon name={hideFired ? 'eye-off' : 'eye'} size={15} />{hideFired ? `Показать уволенных (${firedCount})` : 'Скрыть уволенных'}
          </button>
        )}
        <div style={{ flex: 1 }} />
        <Button icon="add-student" onClick={onAdd}>Добавить сотрудника</Button>
      </div>

      <Card pad={0} style={{ overflow: 'hidden' }}>
        {rows.length > 0 ? (
        <div style={{ overflowX: 'auto' }}>
          <table style={{ width: '100%', borderCollapse: 'collapse', minWidth: 1040 }}>
            <thead><tr>
              <th style={{ ...th, paddingTop: 16 }}>Сотрудник</th>
              <th style={{ ...th, paddingTop: 16 }}>Роль</th>
              <th style={{ ...th, paddingTop: 16 }}>Должность</th>
              <th style={{ ...th, paddingTop: 16 }}>Предметы</th>
              <th style={{ ...th, paddingTop: 16, textAlign: 'right' }}>Ставка</th>
              <th style={{ ...th, paddingTop: 16 }}>Контакт</th>
              <th style={{ ...th, paddingTop: 16 }}>Статус</th>
              <th style={{ ...th, paddingTop: 16, textAlign: 'right' }}>С нами с</th>
            </tr></thead>
            <tbody key={`${role}|${q}`}>
              {rows.map((s, ri) => {
                const rm = ROLE_META[s.role]; const sm = STATUS_META[s.status];
                return (
                <tr key={s.id} className="row-hover st-row om-row-in" style={{ animationDelay: Math.min(ri * 24, 280) + 'ms', cursor: 'pointer', opacity: s.status === 'fired' ? 0.6 : 1 }} onClick={() => onOpen(s)}>
                  <td style={td}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
                      <span className="st-av"><Avatar animal={s.animal} tone={s.tone} size={34} /></span>
                      <div>
                        <div className="st-name" style={{ fontWeight: 600, textDecoration: s.status === 'fired' ? 'line-through' : 'none', color: s.status === 'fired' ? 'var(--text-dim)' : 'var(--text)' }}>{s.name}</div>
                        <div style={{ fontFamily: 'var(--font-mono)', fontSize: 12, color: 'var(--text-dim)' }}>{s.tg}</div>
                      </div>
                    </div>
                  </td>
                  <td style={td}><span className="st-chip" style={{ display: 'inline-block', padding: '3px 10px', borderRadius: 'var(--radius-pill)', fontSize: 12, fontWeight: 600, background: rm.bg, color: rm.fg }}>{rm.label}</span></td>
                  <td style={{ ...td, fontSize: 13, color: s.position ? 'var(--text-secondary)' : 'var(--text-dim)' }}>{s.position ? <span className="st-chip" style={{ display: 'inline-block', padding: '2px 9px', borderRadius: 'var(--radius-xs)', fontSize: 12, fontWeight: 600, background: 'var(--bg-soft)', color: 'var(--text-secondary)', border: '1px solid var(--border)' }}>{s.position}</span> : '—'}</td>
                  <td style={td}>
                    {s.subjects.length ? <div style={{ display: 'flex', gap: 5, flexWrap: 'wrap' }}>{s.subjects.map(sub => <span key={sub} className="st-chip" style={{ display: 'inline-block', padding: '2px 9px', borderRadius: 'var(--radius-xs)', fontSize: 12.5, fontWeight: 600, background: 'var(--brand-soft)', color: 'var(--brand-ink)', border: '1px solid #CBD9F0' }}>{sub}</span>)}</div> : <span style={{ color: 'var(--text-dim)' }}>—</span>}
                  </td>
                  <td style={{ ...td, textAlign: 'right', fontFamily: 'var(--font-mono)', color: s.rate ? 'var(--text-secondary)' : 'var(--text-dim)' }}>{s.rate ? new Intl.NumberFormat('ru-RU').format(s.rate) + ' ₽' : '—'}</td>
                  <td style={{ ...td, fontFamily: 'var(--font-mono)', fontSize: 13, color: 'var(--text-secondary)' }}>{s.contact}</td>
                  <td style={td}><span className="st-chip" style={{ display: 'inline-flex', alignItems: 'center', gap: 7, fontSize: 13, fontWeight: 600, color: sm.fg }}><span style={{ width: 8, height: 8, borderRadius: '50%', background: sm.dot }} />{sm.label}</span></td>
                  <td style={{ ...td, textAlign: 'right', color: 'var(--text-dim)', fontSize: 13, whiteSpace: 'nowrap' }}>{s.since}</td>
                </tr>
                );
              })}
            </tbody>
          </table>
        </div>
        ) : (
          <div style={{ padding: '48px 24px', textAlign: 'center', color: 'var(--text-dim)', fontSize: 14 }}>Сотрудников по фильтру нет</div>
        )}
      </Card>
    </div>
  );
}

Object.assign(window, { Staff });
