﻿// AI Отдел — все экраны приложения. Каждый принимает (T, nav, ...).
// Данные отделов и helpers (buildTeam, getMember, getTask, getActivity…) — в departments.jsx.

const TOAST_DEFAULT_MS = 1800;

// ──────────────────────────────────────────────────────────────
// Building blocks: clickable, header, scrollable area
// ──────────────────────────────────────────────────────────────
function Tap({ children, onClick, style = {}, hoverGlow }) {
  return (
    <button onClick={onClick} className="tap-btn" style={{
      all: 'unset', cursor: 'pointer', display: 'block',
      ...style,
    }}>{children}</button>
  );
}

function ScreenHeader({ T, title, back, right }) {
  return (
    <div style={{
      padding: '6px 18px 14px', display: 'flex', alignItems: 'center', gap: 10,
    }}>
      {back && (
        <Tap onClick={back} style={{
          width: 38, height: 38, borderRadius: 12,
          background: T.card, border: `1px solid ${T.line}`,
          display: 'flex', alignItems: 'center', justifyContent: 'center',
        }}>
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none">
            <path d="M15 6l-6 6 6 6" stroke={T.ink} strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"/>
          </svg>
        </Tap>
      )}
      <h1 style={{
        margin: 0, fontSize: 18, fontWeight: 700, letterSpacing: -0.3, color: T.ink, flex: 1,
      }}>{title}</h1>
      {right}
    </div>
  );
}

function Scroller({ children, style = {} }) {
  return (
    <div className="phone-scroll" style={{
      flex: 1, overflow: 'auto', paddingBottom: 6, ...style,
    }}>{children}</div>
  );
}

// ──────────────────────────────────────────────────────────────
// HERO BANNER (used on Home)
// ──────────────────────────────────────────────────────────────
function HeroBanner({ working, T, onClick }) {
  if (working.length === 0) {
    return (
      <div style={{ padding: '0 14px' }}>
        <div style={{
          background: `linear-gradient(135deg, ${T.accent}, ${T.accent}DD 60%, ${T.accent}AA)`,
          borderRadius: 22, padding: 16, color: '#fff', position: 'relative', overflow: 'hidden',
          boxShadow: `0 16px 32px -16px ${T.accent}AA`,
          boxSizing: 'border-box',
        }}>
          <div style={{
            position: 'absolute', right: -40, top: -40,
            width: 180, height: 180, borderRadius: '50%',
            background: 'rgba(255,255,255,0.08)',
          }} />
          <div style={{ position: 'relative', zIndex: 2 }}>
            <div style={{
              fontSize: 10.5, fontWeight: 700, letterSpacing: 0.8, textTransform: 'uppercase',
              opacity: 0.7, display: 'flex', alignItems: 'center', gap: 6,
            }}>
              <span style={{ width: 6, height: 6, borderRadius: 6, background: 'rgba(255,255,255,0.6)', display: 'inline-block' }} />
              В ожидании задачи
            </div>
            <div style={{ marginTop: 6, fontSize: 19, fontWeight: 800, letterSpacing: -0.5, lineHeight: 1.2, opacity: 0.55 }}>
              Команда свободна
            </div>
            <div style={{ marginTop: 4, fontSize: 12, opacity: 0.7 }}>Сотрудники в ожидании задачи</div>
            <div style={{ marginTop: 14, display: 'flex', alignItems: 'center', gap: 6 }}>
              {PHASES.map((p, i) => (
                <React.Fragment key={p.key}>
                  <div style={{ width: 8, height: 8, borderRadius: 12, background: 'rgba(255,255,255,0.25)' }} />
                  {i < PHASES.length - 1 && (
                    <div style={{ flex: 1, height: 2, background: 'rgba(255,255,255,0.15)', borderRadius: 2 }} />
                  )}
                </React.Fragment>
              ))}
            </div>
            <div style={{
              marginTop: 8, display: 'grid', gridTemplateColumns: `repeat(${PHASES.length}, 1fr)`,
              fontSize: 9, opacity: 0.4, letterSpacing: -0.05,
            }}>
              {PHASES.map(p => (
                <span key={p.key} style={{ textAlign: 'center', fontWeight: 500 }}>{p.short}</span>
              ))}
            </div>
          </div>
        </div>
      </div>
    );
  }
  const _phaseOrder = PHASES.map(p => p.key);
  // lead = самый продвинутый сотрудник: сначала по фазе, при равной фазе — по % прогресса.
  // (имя/роль/текст/фаза в баннере согласованы; при равной фазе показываем кто дальше, напр. Марк 15% > Елена 5%)
  const lead = working.reduce(function(best, m) {
    const pm = _phaseOrder.indexOf(m.task.phase), pb = _phaseOrder.indexOf(best.task.phase);
    if (pm !== pb) return pm > pb ? m : best;
    return (m.livePct || 0) > (best.livePct || 0) ? m : best;
  }, working[0]);
  const _currentPhaseKey = lead.task.phase;
  const phase = PHASES.find(ph => ph.key === _currentPhaseKey);
  const phaseIdx = PHASES.findIndex(ph => ph.key === _currentPhaseKey);
  return (
    <div style={{ padding: '0 14px' }}>
      <Tap onClick={onClick} style={{ display: 'block', width: '100%' }}>
        <div style={{
          background: `linear-gradient(135deg, ${T.accent}, ${T.accent}DD 60%, ${T.accent}AA)`,
          borderRadius: 22, padding: 16, color: '#fff', position: 'relative', overflow: 'hidden',
          boxShadow: `0 16px 32px -16px ${T.accent}AA`,
          width: '100%', boxSizing: 'border-box',
        }}>
          <div style={{
            position: 'absolute', right: -40, top: -40,
            width: 180, height: 180, borderRadius: '50%',
            background: 'rgba(255,255,255,0.08)',
          }} />
          <div style={{ position: 'relative', zIndex: 2 }}>
            <div style={{
              fontSize: 10.5, fontWeight: 700, letterSpacing: 0.8, textTransform: 'uppercase',
              opacity: 0.85, display: 'flex', alignItems: 'center', gap: 6,
            }}>
              <span className="pulse-dot" style={{ width: 6, height: 6, borderRadius: 6, background: '#fff' }} />
              Сейчас в работе
            </div>
            <div style={{ marginTop: 6, fontSize: 19, fontWeight: 800, letterSpacing: -0.5, lineHeight: 1.2 }}>
              {lead.task.live}
            </div>
            <div style={{ marginTop: 4, fontSize: 12, opacity: 0.85 }}>
              {lead.name} · {lead.role} · этап «{phase.label}»
            </div>
            <div style={{ marginTop: 14, display: 'flex', alignItems: 'center', gap: 6 }}>
              {PHASES.map((p, i) => (
                <React.Fragment key={p.key}>
                  <div style={{
                    width: i <= phaseIdx ? 12 : 8, height: i <= phaseIdx ? 12 : 8,
                    borderRadius: 12,
                    background: i < phaseIdx ? '#fff' : i === phaseIdx ? '#fff' : 'rgba(255,255,255,0.3)',
                    boxShadow: i === phaseIdx ? '0 0 0 3px rgba(255,255,255,0.25)' : 'none',
                    transition: 'all .3s',
                  }} />
                  {i < PHASES.length - 1 && (
                    <div style={{ flex: 1, height: 2, background: i < phaseIdx ? '#fff' : 'rgba(255,255,255,0.25)', borderRadius: 2 }} />
                  )}
                </React.Fragment>
              ))}
            </div>
            <div style={{
              marginTop: 8, display: 'grid', gridTemplateColumns: `repeat(${PHASES.length}, 1fr)`,
              fontSize: 9, opacity: 0.7, letterSpacing: -0.05,
            }}>
              {PHASES.map((p, i) => (
                <span key={p.key} style={{
                  textAlign: 'center', opacity: i === phaseIdx ? 1 : 0.6, fontWeight: i === phaseIdx ? 700 : 500,
                }}>{p.short}</span>
              ))}
            </div>
          </div>
        </div>
      </Tap>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────
// ACTIVITY FEED
// ──────────────────────────────────────────────────────────────
function ActivityFeed({ T, nav, onTapItem }) {
  const items = getActivity(nav.dept);
  return (
    <div style={{ padding: '18px 14px 12px' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', padding: '0 6px 10px' }}>
        <h3 style={{ margin: 0, fontSize: 16, fontWeight: 700, letterSpacing: -0.3, color: T.ink }}>Активность</h3>
        <span style={{ fontSize: 12, color: T.accent, fontWeight: 600 }}>Все →</span>
      </div>
      <div style={{
        background: T.card, borderRadius: 18, border: `1px solid ${T.line}`, overflow: 'hidden',
      }}>
        {items.map((it, i) => (
          <Tap key={i} onClick={() => onTapItem && onTapItem(it)}>
            <div style={{
              padding: '12px 14px', display: 'flex', gap: 10, alignItems: 'center',
              borderBottom: i < items.length - 1 ? `1px solid ${T.divider}` : 'none',
            }}>
              <div style={{
                width: 34, height: 34, borderRadius: 34, overflow: 'hidden',
                flexShrink: 0, background: T.portraitBg,
              }}>
                <img src={PORTRAIT[it.portrait || it.id]} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 12.5, color: T.ink, letterSpacing: -0.1 }}>
                  <strong style={{ fontWeight: 700 }}>{it.name}</strong>{' '}
                  <span style={{ color: T.mute }}>{it.text}</span>
                </div>
                <div style={{ fontSize: 10.5, color: T.mute, marginTop: 2 }}>{it.time}</div>
              </div>
              {it.tag && (
                <span style={{
                  padding: '4px 8px', borderRadius: 8,
                  background: it.tag === 'Готово' ? T.okBg : `${T.accent}15`,
                  color: it.tag === 'Готово' ? T.okText : T.accent,
                  fontSize: 10.5, fontWeight: 700, whiteSpace: 'nowrap',
                }}>{it.tag}</span>
              )}
            </div>
          </Tap>
        ))}
      </div>
    </div>
  );
}

// ──────────────────────────────────────────────────────────────
// SCREEN: HUB (рабочие пространства / лаунчер отделов)
// ──────────────────────────────────────────────────────────────
function HubScreen({ T, nav, stateMode, onToggleTheme, activeProject, setActiveProject, activeProjectName, setActiveProjectName }) {
  var [showProjectSheet, setShowProjectSheet] = React.useState(false);

  // Load project display name whenever active project changes
  React.useEffect(function() {
    if (!activeProject || !window.AI_API || !window.AI_API.getToken()) return;
    window.AI_API.getProjects().then(function(ps) {
      var found = (ps || []).find(function(p) { return p.slug === activeProject; });
      if (found && found.name && setActiveProjectName) setActiveProjectName(found.name);
    }).catch(function(){});
  }, [activeProject]);
  var [showSprintModal, setShowSprintModal] = React.useState(false);
  var [sprintStatus, setSprintStatus] = React.useState(null);
  var [sprintTask, setSprintTask] = React.useState('');

  function handleSelectProject(slug, name) {
    setShowProjectSheet(false);
    setActiveProject(slug);
    if (name && setActiveProjectName) setActiveProjectName(name);
    if (window.AI_API && window.AI_API.getToken()) {
      try { localStorage.setItem('ai_active_project', slug); if (name) localStorage.setItem('ai_active_project_name', name); } catch (e) {}
      window.AI_API.patchMe({ active_project_slug: slug }).catch(function() {});
    }
  }

  return (
    <React.Fragment>
      {showProjectSheet && window.ProjectsBottomSheet && (
        <ProjectsBottomSheet
          T={T} nav={nav}
          currentSlug={activeProject}
          onSelect={handleSelectProject}
          onClose={function() { setShowProjectSheet(false); }}
        />
      )}
      <Tap onClick={function() { setShowProjectSheet(true); }}>
        <div style={{
          margin: '12px 14px 4px', padding: '10px 14px',
          background: T.card, borderRadius: 14, border: '1px solid ' + T.line,
          display: 'flex', alignItems: 'center', gap: 10,
        }}>
          <div style={{ width: 32, height: 32, borderRadius: 9, background: T.accent + '18', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
              <path d="M3 7a2 2 0 012-2h4l2 2h8a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V7z" stroke={T.accent} strokeWidth="1.7" strokeLinecap="round"/>
            </svg>
          </div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 10, fontWeight: 700, color: T.mute, letterSpacing: 0.5, textTransform: 'uppercase' }}>ПРОЕКТ</div>
            <div style={{ fontSize: 14, fontWeight: 800, color: T.ink, letterSpacing: -0.3, marginTop: 1 }}>
              {activeProjectName || 'Выбрать...'}
            </div>
          </div>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
            <path d="M6 9l6 6 6-6" stroke={T.mute} strokeWidth="1.8" strokeLinecap="round"/>
          </svg>
        </div>
      </Tap>
      <Scroller>
        <div style={{ padding: '8px 20px 4px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
            <div>
              <div style={{ fontSize: 12.5, color: T.mute, fontWeight: 500 }}>Доброе утро,</div>
              <h1 style={{ margin: '2px 0 0', fontSize: 25, fontWeight: 800, letterSpacing: -0.8, color: T.ink }}>Рабочие пространства</h1>
              <div style={{ fontSize: 12.5, color: T.mute, marginTop: 3 }}>Выбери отдел, чтобы открыть команду</div>
            </div>
            <Tap onClick={onToggleTheme}>
              <div style={{
                width: 38, height: 38, borderRadius: 12, background: T.card, border: `1px solid ${T.line}`,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>{T.name === 'light' ? I.moon(T.ink) : I.sun(T.ink)}</div>
            </Tap>
          </div>
        </div>

        <div style={{ padding: '16px 14px 0', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          {DEPARTMENTS.map(d => {
            const team = buildTeam(d.id, stateMode);
            const working = team.filter(p => p.task).length;
            return (
              <Tap key={d.id} onClick={() => nav.enterDept(d.id)}>
                <div style={{
                  background: T.card, borderRadius: 20, padding: 16,
                  border: `1.5px solid ${T.line}`,
                  boxShadow: T.shadow,
                  display: 'flex', flexDirection: 'column', gap: 10, minHeight: 152, boxSizing: 'border-box',
                }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
                    <div style={{ width: 46, height: 46, borderRadius: 14, background: `${d.tint}1A`, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>{I[d.icon](d.tint)}</div>
                    {working > 0 && (
                      <div style={{ display: 'flex', alignItems: 'center', gap: 4, padding: '3px 7px', background: `${d.tint}16`, borderRadius: 99 }}>
                        <span className="pulse-dot" style={{ width: 5, height: 5, borderRadius: 5, background: d.tint }} />
                        <span style={{ fontSize: 10, fontWeight: 700, color: d.tint }}>{working}</span>
                      </div>
                    )}
                  </div>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 16, fontWeight: 800, color: T.ink, letterSpacing: -0.3 }}>{d.name}</div>
                    <div style={{ fontSize: 11, color: T.mute, marginTop: 2 }}>{team.length} сотрудников</div>
                  </div>
                  <MiniProgress pct={team.length ? working / team.length * 100 : 0} T={{ ...T, accent: d.tint }} height={4} />
                </div>
              </Tap>
            );
          })}
        </div>

        <div style={{ height: 16 }} />
      </Scroller>
    </React.Fragment>
  );
}

// ──────────────────────────────────────────────────────────────
// SCREEN: HOME
// ──────────────────────────────────────────────────────────────
function HomeScreen({ T, nav, stateMode, showActivity, onToggleTheme, activeProject, setActiveProject, activeProjectName, setActiveProjectName }) {
  // When sprint running, show team as active
  const effectiveMode = sprintStatus === 'running' ? 'mixed' : stateMode;
  const team = buildTeam(nav.dept, effectiveMode);
  const working = team.filter(p => p.task);
  const d = getDept(nav.dept);
  var [showProjectSheet, setShowProjectSheet] = React.useState(false);
  var [showSprintModal, setShowSprintModal] = React.useState(false);
  var [sprintStatus, setSprintStatus] = React.useState(null);
  var [sprintTask, setSprintTask] = React.useState('');
  var [attachedFiles, setAttachedFiles] = React.useState([]);
  // Режим Ревью: тоггл + список отчётов проекта + выбранный файл
  var [sprintMode, setSprintMode] = React.useState('sprint');  // 'sprint' | 'review'
  var [reports, setReports] = React.useState([]);
  var [selectedReport, setSelectedReport] = React.useState(null);

  // Подгружаем отчёты проекта при открытии модалки (для пикера ревью)
  React.useEffect(function() {
    if (!showSprintModal || !window.AI_API || !window.AI_API.getToken()) return;
    window.AI_API.getReports().then(function(list) {
      setReports(Array.isArray(list) ? list : []);
    }).catch(function() { setReports([]); });
  }, [showSprintModal]);

  function handleSelectProject(slug, name) {
    setShowProjectSheet(false);
    setActiveProject(slug);
    if (name && setActiveProjectName) setActiveProjectName(name);
    if (window.AI_API && window.AI_API.getToken()) {
      try { localStorage.setItem('ai_active_project', slug); if (name) localStorage.setItem('ai_active_project_name', name); } catch (e) {}
      window.AI_API.patchMe({ active_project_slug: slug }).catch(function() {});
    }
  }

  return (
    <React.Fragment>
      {showProjectSheet && window.ProjectsBottomSheet && (
        <ProjectsBottomSheet
          T={T} nav={nav}
          currentSlug={activeProject}
          onSelect={handleSelectProject}
          onClose={function() { setShowProjectSheet(false); }}
        />
      )}
      <Scroller>
        <div style={{ padding: '6px 18px 4px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 11, minWidth: 0 }}>
              <Tap onClick={() => nav.openHub()}>
                <div style={{
                  width: 40, height: 40, borderRadius: 13, flexShrink: 0,
                  background: `${d.tint}1F`, display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>{I[d.icon](d.tint)}</div>
              </Tap>
              <Tap onClick={() => nav.openHub()}>
                <div style={{ minWidth: 0 }}>
                  <div style={{ fontSize: 11.5, color: T.mute, fontWeight: 500, display: 'flex', alignItems: 'center', gap: 4 }}>
                    {I.grid(T.mute)} Все отделы
                  </div>
                  <div style={{ display: 'flex', alignItems: 'center' }}>
                    <h1 style={{ margin: '1px 0 0', fontSize: 22, fontWeight: 800, letterSpacing: -0.6, color: T.ink, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{d.name}</h1>
                    <Tap onClick={function() { setShowProjectSheet(true); }}>
                      <div style={{
                        display: 'inline-flex', alignItems: 'center', gap: 4, marginLeft: 8,
                        padding: '3px 8px', borderRadius: 99,
                        background: T.accent + '18', border: '1px solid ' + T.accent + '30',
                      }}>
                        <svg width="10" height="10" viewBox="0 0 24 24" fill="none">
                          <path d="M3 7a2 2 0 012-2h4l2 2h8a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V7z" stroke={T.accent} strokeWidth="1.8" strokeLinecap="round"/>
                        </svg>
                        <span style={{ fontSize: 11, fontWeight: 700, color: T.accent }}>
                          {activeProjectName || '—'}
                        </span>
                        <svg width="8" height="8" viewBox="0 0 24 24" fill="none">
                          <path d="M6 9l6 6 6-6" stroke={T.accent} strokeWidth="2.2" strokeLinecap="round"/>
                        </svg>
                      </div>
                    </Tap>
                  </div>
                </div>
              </Tap>
            </div>
            <div style={{ display: 'flex', gap: 8, alignItems: 'center', flexShrink: 0 }}>
              <Tap onClick={onToggleTheme}>
                <div style={{
                  width: 38, height: 38, borderRadius: 12,
                  background: T.card, border: `1px solid ${T.line}`,
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  {T.name === 'light' ? I.moon(T.ink) : I.sun(T.ink)}
                </div>
              </Tap>
              <Tap onClick={() => nav.push({ kind: 'notifications' })}>
                <div style={{
                  width: 38, height: 38, borderRadius: 12,
                  background: T.card, border: `1px solid ${T.line}`,
                  display: 'flex', alignItems: 'center', justifyContent: 'center', position: 'relative',
                }}>
                  {I.bell(T.ink)}
                  {working.length > 0 && (
                    <span style={{
                      position: 'absolute', top: 8, right: 9, width: 7, height: 7,
                      borderRadius: 7, background: T.accent, border: `2px solid ${T.card}`,
                    }} />
                  )}
                </div>
              </Tap>
            </div>
          </div>
        </div>

        <div style={{ height: 14 }} />

        <HeroBanner
          working={working}
          T={T}
          onClick={() => working.length
            ? nav.push({ kind: 'task', employeeId: working[0].id })
            : nav.push({ kind: 'new-task' })}
        />

        <div style={{ padding: '18px 14px 4px', display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
          <h3 style={{ margin: 0, fontSize: 16, fontWeight: 700, letterSpacing: -0.3, color: T.ink, paddingLeft: 6 }}>Команда</h3>
          <Tap onClick={() => nav.setTab('team')}>
            <span style={{ fontSize: 12, color: T.mute, paddingRight: 6 }}>
              <span style={{ color: T.accent, fontWeight: 700 }}>{working.length}</span> · {team.length - working.length} свободны
            </span>
          </Tap>
        </div>

        <div style={{ padding: '0 14px', display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          {team.map(p => (
            <Tap key={p.id} onClick={() => nav.push({ kind: 'employee', employeeId: p.id })}>
              <EmployeeCard p={p} T={T} />
            </Tap>
          ))}
        </div>

        <div style={{ padding: '18px 14px 6px', display: 'grid', gridTemplateColumns: '1.3fr 1fr', gap: 10 }}>
          <Tap onClick={() => nav.push({ kind: 'new-task' })}>
            <div style={{
              padding: '14px 16px', background: T.accent, color: '#fff',
              borderRadius: 18, fontSize: 16, fontWeight: 700, letterSpacing: -0.2,
              display: 'flex', flexDirection: 'column', gap: 2, alignItems: 'flex-start',
              boxShadow: `0 10px 24px -12px ${T.accent}AA`,
            }}>
              <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>{I.plus('#fff')} Поручить задачу</span>
              <span style={{ fontSize: 11.5, fontWeight: 500, opacity: 0.85 }}>одному сотруднику</span>
            </div>
          </Tap>
          <Tap onClick={function() { setShowSprintModal(true); }}>
            <div style={{
              padding: '14px 16px', background: T.card, color: T.ink,
              border: `1px solid ${T.line}`, borderRadius: 18,
              fontSize: 16, fontWeight: 700, letterSpacing: -0.2,
              display: 'flex', flexDirection: 'column', gap: 2, alignItems: 'flex-start',
            }}>
              <span style={{ display: 'flex', alignItems: 'center', gap: 6 }}>{I.team(T.ink)} Команде</span>
              <span style={{ fontSize: 11.5, fontWeight: 500, color: T.mute }}>несколько ролей</span>
            </div>
          </Tap>
        </div>

        {showActivity && <ActivityFeed T={T} nav={nav} onTapItem={(it) => nav.push({ kind: 'task', employeeId: it.id })} />}
      </Scroller>

      <GlobalStatusBar working={working} T={T} onClick={() => working.length && nav.setTab('tasks')} />

      {showSprintModal && (
        <div onClick={function() { if (sprintStatus !== 'running') setShowSprintModal(false); }}
          style={{
            position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, zIndex: 200,
            background: 'rgba(0,0,0,0.55)', backdropFilter: 'blur(10px)',
            WebkitBackdropFilter: 'blur(10px)',
            display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
          }}>
          <div onClick={function(e) { e.stopPropagation(); }} style={{
            background: T.card, borderRadius: '20px 20px 0 0',
            padding: '20px 18px 20px', width: '100%', maxWidth: 500, height: '62vh', display: 'flex', flexDirection: 'column', overflow: 'hidden',
          }}>
            <div style={{ width: 36, height: 4, borderRadius: 4, background: T.line, margin: '0 auto 16px' }} />
            <div style={{ fontSize: 18, fontWeight: 800, color: T.ink, marginBottom: 6 }}>
              {sprintStatus === 'running' ? (sprintMode === 'review' ? '🔎 Идёт ревью' : '⚡ Команда работает') :
               sprintStatus === 'done' ? '✅ Готово' : (sprintMode === 'review' ? '🔎 Ревью документа' : 'Задание команде')}
            </div>

            {(!sprintStatus || sprintStatus === 'error') && (
              <React.Fragment>
                <div style={{ display: 'flex', gap: 6, marginBottom: 12, background: T.bg, border: '1px solid ' + T.line, borderRadius: 12, padding: 4, flexShrink: 0 }}>
                  {[['sprint', 'Спринт'], ['review', 'Ревью']].map(function(m) { return (
                    <Tap key={m[0]} onClick={function() { setSprintMode(m[0]); }} style={{ flex: 1 }}>
                      <div style={{
                        textAlign: 'center', padding: '8px 0', borderRadius: 9, fontSize: 14, fontWeight: 700,
                        background: sprintMode === m[0] ? T.accent : 'transparent',
                        color: sprintMode === m[0] ? '#fff' : T.mute,
                      }}>{m[1]}</div>
                    </Tap>
                  ); })}
                </div>

                {sprintMode === 'review' && (
                  <div style={{ marginBottom: 10, flexShrink: 0 }}>
                    <div style={{ fontSize: 12, color: T.mute, marginBottom: 6 }}>Файл на ревью:</div>
                    {reports.length === 0 ? (
                      <div style={{ fontSize: 13, color: T.mute, padding: '10px 12px', background: T.bg, border: '1px solid ' + T.line, borderRadius: 10 }}>
                        В проекте пока нет отчётов для ревью.
                      </div>
                    ) : (
                      <div style={{ display: 'flex', flexDirection: 'column', gap: 6, maxHeight: 130, overflowY: 'auto' }} className="phone-scroll">
                        {reports.map(function(r) { return (
                          <Tap key={r.file_id} onClick={function() { setSelectedReport(r); }}>
                            <div style={{
                              padding: '10px 12px', borderRadius: 10, fontSize: 13, fontWeight: 600,
                              background: (selectedReport && selectedReport.file_id === r.file_id) ? T.accent + '18' : T.bg,
                              border: '1px solid ' + ((selectedReport && selectedReport.file_id === r.file_id) ? T.accent : T.line),
                              color: T.ink, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
                            }}>📄 {r.name}</div>
                          </Tap>
                        ); })}
                      </div>
                    )}
                  </div>
                )}

                <textarea
                  value={sprintTask}
                  onChange={function(e) { setSprintTask(e.target.value); }}
                  placeholder={sprintMode === 'review' ? 'На что обратить внимание (опционально)...' : 'Опиши задачу для всей команды...'}
                  style={{
                    width: '100%', boxSizing: 'border-box', flex: 1, minHeight: 120,
                    padding: '12px 14px', borderRadius: 12, resize: 'none',
                    background: T.bg, border: '1px solid ' + T.line,
                    fontSize: 15, color: T.ink, fontFamily: 'inherit', outline: 'none',
                    marginBottom: 8,
                  }}
                />
                {sprintMode !== 'review' && (
                <React.Fragment>
                <input type="file" id="sprint-file-input" multiple style={{ display: 'none' }}
                  onChange={function(e) {
                    var file = e.target.files && e.target.files[0];
                    if (!file || !window.AI_API || !window.AI_API.getToken()) return;
                    var files = Array.from(e.target.files || []);
                    files.forEach(function(file) {
                      setAttachedFiles(function(prev) { return prev.concat([{ file: file, name: file.name, status: 'pending' }]); });
                    });
                    e.target.value = '';
                  }}
                />
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8, overflow: 'hidden', flexShrink: 0 }}>
                  <Tap onClick={function() { document.getElementById('sprint-file-input').click(); }} style={{ flexShrink: 0 }}>
                    <div style={{
                      width: 36, height: 36, borderRadius: 99, flexShrink: 0,
                      background: T.bg, border: '1px solid ' + T.line,
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                    }}>
                      <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                        <path d="M21.44 11.05l-9.19 9.19a6 6 0 01-8.49-8.49l9.19-9.19a4 4 0 015.66 5.66l-9.2 9.19a2 2 0 01-2.83-2.83l8.49-8.48" stroke={T.mute} strokeWidth="1.8" strokeLinecap="round"/>
                      </svg>
                    </div>
                  </Tap>
                  <div style={{ display: 'flex', gap: 6, overflowX: 'auto', flexShrink: 1, paddingBottom: 2 }}
                    className="phone-scroll">
                    {attachedFiles.length === 0 && (
                      <span style={{ fontSize: 12, color: T.mute, alignSelf: 'center', whiteSpace: 'nowrap' }}>Файлы не прикреплены</span>
                    )}
                    {attachedFiles.map(function(fname, fi) { return (
                      <div key={fi} style={{
                        display: 'flex', alignItems: 'center', gap: 5,
                        padding: '5px 10px', borderRadius: 99,
                        background: T.accent + '18', border: '1px solid ' + T.accent + '40',
                        flexShrink: 0,
                      }}>
                        <span style={{ fontSize: 12, color: T.accent, fontWeight: 600, maxWidth: 110, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{fname.name || fname}</span>
                        <Tap onClick={function() { setAttachedFiles(function(prev) { return prev.filter(function(_, i) { return i !== fi; }); }); }}>
                          <svg width="9" height="9" viewBox="0 0 24 24" fill="none">
                            <path d="M6 18L18 6M6 6l12 12" stroke={T.mute} strokeWidth="2.5" strokeLinecap="round"/>
                          </svg>
                        </Tap>
                      </div>
                    ); })}
                  </div>
                </div>
                </React.Fragment>
                )}
                {sprintStatus === 'error' && (
                  <div style={{ fontSize: 13, color: '#E15B58', marginBottom: 8 }}>Ошибка. Попробуй снова.</div>
                )}
                <div style={{ fontSize: 11, color: T.mute, marginBottom: 16 }}>
                  {sprintMode === 'review'
                    ? '⚠️ Ревью ~$0.20–0.50 · Вердикт придёт в чат и Telegram'
                    : '⚠️ Стоимость ~$0.50–2.00 · Результат придёт в Telegram'}
                </div>
                <Tap onClick={function() {
                  if (!window.AI_API || !window.AI_API.getToken()) return;
                  function poll(res) {
                    if (window.AI_LIVE_START) window.AI_LIVE_START(res.sprint_id, nav.dept);  // #4 — оживить карточки
                    var interval = setInterval(function() {
                      window.AI_API.getSprintStatus(res.sprint_id).then(function(s) {
                        setSprintStatus(s.status);
                        if (s.status === 'done' || s.status === 'error') clearInterval(interval);
                      }).catch(function() {});
                    }, 8000);
                  }
                  if (sprintMode === 'review') {
                    if (!selectedReport) return;
                    setSprintStatus('running');
                    window.AI_API.runReview(selectedReport.file_id, selectedReport.name, sprintTask.trim(), nav.dept)
                      .then(poll).catch(function() { setSprintStatus('error'); });
                    return;
                  }
                  if (!sprintTask.trim()) return;
                  var task = sprintTask.trim();
                  setSprintStatus('running');
                  var toUpload = attachedFiles.filter(function(f) { return f.file; });
                  var uploads = toUpload.map(function(f) {
                    return window.AI_API.uploadFile(f.file).catch(function() { return null; });
                  });
                  Promise.all(uploads).then(function() {
                    return window.AI_API.runSprint(task, activeProject, nav.dept);
                  }).then(poll).catch(function() { setSprintStatus('error'); });
                }}>
                  <div style={{
                    background: (sprintMode === 'review' ? !!selectedReport : sprintTask.trim()) ? T.accent : T.line,
                    borderRadius: 12, padding: '14px',
                    textAlign: 'center', fontSize: 15, fontWeight: 700,
                    color: (sprintMode === 'review' ? !!selectedReport : sprintTask.trim()) ? '#fff' : T.mute,
                  }}>{sprintMode === 'review' ? 'Запустить ревью' : 'Отправить задачу команде'}</div>
                </Tap>
              </React.Fragment>
            )}

            {sprintStatus === 'running' && (
              <div style={{ textAlign: 'center', padding: '20px 0' }}>
                <div style={{ fontSize: 14, color: T.mute }}>
                  {sprintMode === 'review'
                    ? 'Команда читает документ... Вердикт придёт в чат и Telegram через ~2-3 минуты.'
                    : 'Команда работает... Результат придёт в Telegram через ~2-5 минут.'}
                </div>
                <Tap onClick={function() { setShowSprintModal(false); }}>
                  <div style={{ marginTop: 20, color: T.accent, fontWeight: 700, fontSize: 14 }}>Закрыть (продолжится в фоне)</div>
                </Tap>
              </div>
            )}

            {sprintStatus === 'done' && (
              <div style={{ textAlign: 'center', padding: '16px 0' }}>
                <div style={{ fontSize: 14, color: T.mute }}>
                  {sprintMode === 'review'
                    ? 'Вердикт отправлен в чат отдела и в Telegram.'
                    : 'Результаты отправлены в Telegram и сохранены на GDrive.'}
                </div>
                <Tap onClick={function() { setShowSprintModal(false); setSprintStatus(null); setSprintTask(''); setAttachedFiles([]); setSelectedReport(null); }}>
                  <div style={{ marginTop: 16, background: T.accent, color: '#fff', borderRadius: 12, padding: '12px', fontWeight: 700, fontSize: 14 }}>Закрыть</div>
                </Tap>
              </div>
            )}
          </div>
        </div>
      )}
    </React.Fragment>
  );
}

// ──────────────────────────────────────────────────────────────
// SCREEN: TASK / EMPLOYEE DETAIL
// ──────────────────────────────────────────────────────────────
function TaskScreen({ T, nav, employeeId }) {
  const p = getMember(nav.dept, employeeId);
  const task = getTask(nav.dept, employeeId);
  const phaseIdx = task ? PHASES.findIndex(ph => ph.key === task.phase) : -1;
  const working = phaseIdx >= 0;
  return (
    <React.Fragment>
      <ScreenHeader T={T} title={working ? 'Задача в работе' : p.name} back={nav.pop}
        right={
          <Tap onClick={() => nav.push({ kind: 'new-task', employeeId: p.id })}>
            <div style={{
              padding: '8px 12px', background: T.accent, color: '#fff',
              borderRadius: 10, fontSize: 12, fontWeight: 700,
            }}>Новая задача</div>
          </Tap>
        }
      />
      <Scroller style={{ padding: '0 14px' }}>
        {/* Hero — portrait + name + status */}
        <div style={{
          background: T.card, borderRadius: 22, padding: 18,
          border: `1px solid ${T.line}`,
          display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 12,
        }}>
          <Portrait id={p.id} size={96} working={working} T={T} />
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontSize: 20, fontWeight: 800, letterSpacing: -0.5, color: T.ink }}>{p.name}</div>
            <div style={{ fontSize: 15.5, color: T.mute, marginTop: 2 }}>{p.role}</div>
          </div>
          <div style={{
            padding: '6px 12px', borderRadius: 99,
            background: working ? `${T.accent}18` : T.okBg,
            color: working ? T.accent : T.okText,
            fontSize: 11.5, fontWeight: 700,
            display: 'flex', alignItems: 'center', gap: 6,
          }}>
            <span style={{ width: 6, height: 6, borderRadius: 6, background: working ? T.accent : T.ok }} />
            {working ? 'Работает прямо сейчас' : 'Готов к задаче'}
          </div>
          <div style={{
            fontSize: 11, color: T.mute, textAlign: 'center', maxWidth: 280, lineHeight: 1.4,
          }}>{p.specialty}</div>
        </div>

        {working && (
          <React.Fragment>
            {/* Current task title */}
            <div style={{
              marginTop: 12, padding: 16, background: T.card, borderRadius: 18, border: `1px solid ${T.line}`,
            }}>
              <div style={{ fontSize: 10.5, fontWeight: 700, color: T.accent, letterSpacing: 0.6, textTransform: 'uppercase' }}>Текущая задача</div>
              <div style={{ marginTop: 6, fontSize: 17, fontWeight: 700, color: T.ink, letterSpacing: -0.3 }}>{task.title}</div>
              <div style={{
                marginTop: 12, padding: '10px 12px',
                background: T.name === 'light' ? 'rgba(110,92,244,0.06)' : 'rgba(139,123,251,0.10)',
                borderRadius: 12, border: `1px solid ${T.accent}1A`,
                fontSize: 15.5, color: T.ink, lineHeight: 1.4,
              }}>
                <LiveText key={task.live} text={task.live} T={T} />
              </div>
              <div style={{ marginTop: 12 }}>
                <MiniProgress pct={Math.round(((phaseIdx + 0.7) / PHASES.length) * 100)} T={T} height={5} />
              </div>
              <div style={{ marginTop: 6, display: 'flex', justifyContent: 'space-between', fontSize: 11, color: T.mute }}>
                <span>Запуск: {(function() {
                  var t = (window.AI_LIVE && window.AI_LIVE.startedAt) || Number(localStorage.getItem('ai_active_sprint_start')) || 0;
                  return t ? new Date(t).toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' }) : '—';
                })()}</span>
                <span>~{14 - phaseIdx * 2} мин до конца</span>
              </div>
            </div>

            {/* Vertical timeline */}
            <div style={{
              marginTop: 12, padding: 18, background: T.card, borderRadius: 18, border: `1px solid ${T.line}`,
            }}>
              <div style={{ fontSize: 12, fontWeight: 700, color: T.ink, letterSpacing: -0.2, marginBottom: 14 }}>
                Прогресс выполнения
              </div>
              {PHASES.map((s, i) => {
                const done = i < phaseIdx, here = i === phaseIdx;
                return (
                  <div key={s.key} style={{ display: 'flex', gap: 12 }}>
                    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center' }}>
                      <div style={{
                        width: 20, height: 20, borderRadius: 20,
                        background: done ? T.accent : here ? T.card : T.card,
                        border: `2px solid ${done || here ? T.accent : T.line.includes('rgba') ? T.mute : T.line}`,
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                        boxShadow: here ? `0 0 0 4px ${T.accent}33` : 'none', flexShrink: 0,
                      }}>
                        {done && <svg width="10" height="10" viewBox="0 0 24 24" fill="none"><path d="M5 12l5 5L20 7" stroke="#fff" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/></svg>}
                        {here && <div style={{ width: 7, height: 7, borderRadius: 7, background: T.accent }} />}
                      </div>
                      {i < PHASES.length - 1 && (
                        <div style={{ width: 2, flex: 1, background: done ? T.accent : T.divider, minHeight: 26 }} />
                      )}
                    </div>
                    <div style={{ paddingBottom: i < PHASES.length - 1 ? 22 : 0, flex: 1 }}>
                      <div style={{
                        fontSize: 16, fontWeight: here ? 700 : 600,
                        color: done || here ? T.ink : T.mute, letterSpacing: -0.2,
                      }}>{s.label}</div>
                      <div style={{ fontSize: 11.5, color: T.mute, marginTop: 2 }}>
                        {done && '✓ завершено'}
                        {here && <span style={{ color: T.accent, fontWeight: 600 }}>● в процессе</span>}
                        {!done && !here && 'ожидает'}
                      </div>
                    </div>
                  </div>
                );
              })}
            </div>

            {/* Actions */}
            <div style={{ marginTop: 12, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
              <Tap onClick={() => nav.toast('Сотрудник остановлен')}>
                <div style={{
                  padding: 14, borderRadius: 14, background: T.card, border: `1px solid ${T.line}`,
                  display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                  fontSize: 15.5, fontWeight: 700, color: T.ink,
                }}>⏸ Пауза</div>
              </Tap>
              <Tap onClick={() => nav.toast('Сотрудник переключён')}>
                <div style={{
                  padding: 14, borderRadius: 14, background: T.card, border: `1px solid ${T.line}`,
                  display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                  fontSize: 15.5, fontWeight: 700, color: T.ink,
                }}>↻ Сменить</div>
              </Tap>
            </div>
          </React.Fragment>
        )}

        {!working && (
          <div style={{
            marginTop: 12, padding: 18, background: T.card, borderRadius: 18, border: `1px solid ${T.line}`,
          }}>
            <div style={{ fontSize: 15.5, fontWeight: 700, color: T.ink, letterSpacing: -0.2 }}>Поручить задачу</div>
            <div style={{ marginTop: 4, fontSize: 12, color: T.mute, lineHeight: 1.4 }}>
              {p.name} сейчас свободен. Дай задачу — и она будет в работе через 5 секунд.
            </div>
            <Tap onClick={() => nav.push({ kind: 'new-task', employeeId: p.id })}>
              <div style={{
                marginTop: 14, padding: 14, background: T.accent, color: '#fff',
                borderRadius: 14, textAlign: 'center', fontSize: 14, fontWeight: 700,
              }}>+ Новая задача для {p.name}</div>
            </Tap>
          </div>
        )}

        <div style={{ height: 20 }} />
      </Scroller>
    </React.Fragment>
  );
}

// ──────────────────────────────────────────────────────────────
// SCREEN: NEW TASK
// ──────────────────────────────────────────────────────────────
function NewTaskScreen({ T, nav, employeeId, mode }) {
  const deptMembers = getDept(nav.dept).members;
  const initialAssignee = employeeId ? [employeeId] : (mode === 'team' ? deptMembers.slice(0, 3).map(m => m.id) : [deptMembers[0].id]);
  const [text, setText] = React.useState('');
  const [assignees, setAssignees] = React.useState(initialAssignee);
  const [priority, setPriority] = React.useState('normal');
  const [attachments, setAttachments] = React.useState([]);
  const fileInputRef = React.useRef(null);
  const teamMode = mode === 'team' || assignees.length > 1;

  const suggestions = [
    'Сделай 3 варианта рекламного баннера для запуска',
    'Подготовь отчёт по конкурентам в нашей нише',
    'Напиши тексты для главной страницы лендинга',
    'Собери семантическое ядро для блога',
  ];

  function toggleAssignee(id) {
    setAssignees(a => a.includes(id) ? a.filter(x => x !== id) : [...a, id]);
  }

  function onFiles(fileList) {
    const files = Array.from(fileList || []);
    const next = files.map(f => ({
      id: Math.random().toString(36).slice(2),
      name: f.name,
      size: f.size,
      type: f.type,
      isImage: f.type.startsWith('image/'),
      url: f.type.startsWith('image/') ? URL.createObjectURL(f) : null,
    }));
    setAttachments(a => [...a, ...next]);
  }

  function removeAttachment(id) {
    setAttachments(a => {
      const found = a.find(x => x.id === id);
      if (found && found.url) URL.revokeObjectURL(found.url);
      return a.filter(x => x.id !== id);
    });
  }

  function formatSize(n) {
    if (n < 1024) return n + ' B';
    if (n < 1024 * 1024) return (n / 1024).toFixed(1) + ' КБ';
    return (n / 1024 / 1024).toFixed(1) + ' МБ';
  }

  return (
    <React.Fragment>
      <ScreenHeader T={T} title={teamMode ? 'Задача команде' : 'Новая задача'} back={nav.pop} />
      <Scroller style={{ padding: '0 14px' }}>
        {/* Task description */}
        <div style={{
          background: T.card, borderRadius: 18, padding: 14, border: `1px solid ${T.line}`,
        }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: T.mute, letterSpacing: 0.4, textTransform: 'uppercase' }}>Опишите задачу</div>
          <textarea
            value={text}
            onChange={e => setText(e.target.value)}
            placeholder="Например: подготовь рекламный баннер для запуска нового продукта…"
            style={{
              width: '100%', marginTop: 8, padding: 12,
              background: T.bg2 || T.bg, color: T.ink,
              border: `1px solid ${T.line}`, borderRadius: 12,
              fontSize: 14, fontFamily: 'inherit', resize: 'none', height: 90,
              outline: 'none', boxSizing: 'border-box',
            }}
          />

          {/* Hidden file input */}
          <input
            ref={fileInputRef}
            type="file"
            multiple
            accept="image/*,application/pdf,.doc,.docx,.txt,.csv,.xls,.xlsx,.fig,.sketch"
            style={{ display: 'none' }}
            onChange={(e) => { onFiles(e.target.files); e.target.value = ''; }}
          />

          {/* Attachments preview row */}
          {attachments.length > 0 && (
            <div style={{
              marginTop: 10, display: 'flex', gap: 8, flexWrap: 'wrap',
            }}>
              {attachments.map(att => (
                <div key={att.id} style={{
                  position: 'relative',
                  display: 'flex', alignItems: 'center', gap: 8,
                  padding: att.isImage ? 0 : '6px 10px 6px 8px',
                  background: T.bg2 || T.bg, borderRadius: 10,
                  border: `1px solid ${T.line}`,
                  maxWidth: '100%',
                }}>
                  {att.isImage ? (
                    <div style={{
                      width: 64, height: 64, borderRadius: 10, overflow: 'hidden',
                      background: T.portraitBg,
                    }}>
                      <img src={att.url} alt={att.name} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                    </div>
                  ) : (
                    <React.Fragment>
                      <div style={{
                        width: 28, height: 28, borderRadius: 8,
                        background: `${T.accent}18`, color: T.accent,
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                        flexShrink: 0,
                      }}>
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none"><path d="M7 3h7l4 4v13a1 1 0 01-1 1H7a1 1 0 01-1-1V4a1 1 0 011-1z" stroke={T.accent} strokeWidth="1.8" strokeLinejoin="round"/><path d="M14 3v4h4" stroke={T.accent} strokeWidth="1.8" strokeLinejoin="round"/></svg>
                      </div>
                      <div style={{ minWidth: 0, maxWidth: 140 }}>
                        <div style={{ fontSize: 11.5, fontWeight: 600, color: T.ink, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{att.name}</div>
                        <div style={{ fontSize: 10, color: T.mute, marginTop: 1 }}>{formatSize(att.size)}</div>
                      </div>
                    </React.Fragment>
                  )}
                  <button onClick={() => removeAttachment(att.id)} style={{
                    all: 'unset', cursor: 'pointer',
                    position: 'absolute',
                    top: att.isImage ? 4 : '50%',
                    right: att.isImage ? 4 : 8,
                    transform: att.isImage ? 'none' : 'translateY(-50%)',
                    width: 18, height: 18, borderRadius: 18,
                    background: att.isImage ? 'rgba(0,0,0,0.6)' : 'transparent',
                    color: att.isImage ? '#fff' : T.mute,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontSize: 11, fontWeight: 700,
                  }}>×</button>
                </div>
              ))}
            </div>
          )}

          {/* Toolbar: attach + suggestions */}
          <div style={{ marginTop: 10, display: 'flex', gap: 6, alignItems: 'center', flexWrap: 'wrap' }}>
            <Tap onClick={() => fileInputRef.current?.click()}>
              <div style={{
                display: 'flex', alignItems: 'center', gap: 5,
                padding: '5px 10px 5px 8px',
                background: `${T.accent}12`, color: T.accent,
                borderRadius: 99, fontWeight: 700, fontSize: 11,
                border: `1px solid ${T.accent}20`,
              }}>
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none">
                  <path d="M21 11.5l-8.5 8.5a5 5 0 11-7-7l8.5-8.5a3.5 3.5 0 014.95 4.95L10.5 18" stroke={T.accent} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"/>
                </svg>
                Прикрепить
              </div>
            </Tap>
            {suggestions.map((s, i) => (
              <Tap key={i} onClick={() => setText(s)}>
                <span style={{
                  fontSize: 11, padding: '5px 10px',
                  background: `${T.accent}12`, color: T.accent,
                  borderRadius: 99, fontWeight: 600,
                }}>{s.slice(0, 30)}…</span>
              </Tap>
            ))}
          </div>
        </div>

        {/* Assignees */}
        <div style={{
          marginTop: 12, background: T.card, borderRadius: 18, padding: 14, border: `1px solid ${T.line}`,
        }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
            <div style={{ fontSize: 11, fontWeight: 700, color: T.mute, letterSpacing: 0.4, textTransform: 'uppercase' }}>
              {teamMode ? `Команда (${assignees.length})` : 'Исполнитель'}
            </div>
            <span style={{ fontSize: 11, color: T.accent, fontWeight: 600 }}>{teamMode ? 'выбери ролей' : 'тапни чтобы поменять'}</span>
          </div>
          <div style={{
            marginTop: 10, display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 8,
          }}>
            {deptMembers.map(p => {
              const on = assignees.includes(p.id);
              return (
                <Tap key={p.id} onClick={() => toggleAssignee(p.id)}>
                  <div style={{
                    display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 4,
                    opacity: on ? 1 : 0.45,
                  }}>
                    <div style={{
                      width: 48, height: 48, borderRadius: 48, overflow: 'hidden',
                      boxShadow: on ? `0 0 0 2px ${T.accent}` : 'none',
                      background: T.portraitBg, position: 'relative',
                    }}>
                      <img src={PORTRAIT[p.portrait || p.id]} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                      {on && (
                        <div style={{
                          position: 'absolute', right: -2, bottom: -2,
                          width: 18, height: 18, borderRadius: 18, background: T.accent,
                          display: 'flex', alignItems: 'center', justifyContent: 'center',
                          boxShadow: `0 0 0 2px ${T.card}`,
                        }}>
                          <svg width="10" height="10" viewBox="0 0 24 24" fill="none"><path d="M5 12l5 5L20 7" stroke="#fff" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"/></svg>
                        </div>
                      )}
                    </div>
                    <div style={{ fontSize: 10.5, fontWeight: 600, color: T.ink, textAlign: 'center' }}>{p.name}</div>
                  </div>
                </Tap>
              );
            })}
          </div>
        </div>

        {/* Priority */}
        <div style={{
          marginTop: 12, background: T.card, borderRadius: 18, padding: 14, border: `1px solid ${T.line}`,
        }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: T.mute, letterSpacing: 0.4, textTransform: 'uppercase', marginBottom: 10 }}>Приоритет</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
            {[
              { v: 'low',    l: 'Низкий',   c: T.mute },
              { v: 'normal', l: 'Обычный',  c: T.accent },
              { v: 'high',   l: 'Срочный',  c: '#E15B58' },
            ].map(o => {
              const on = priority === o.v;
              return (
                <Tap key={o.v} onClick={() => setPriority(o.v)}>
                  <div style={{
                    padding: '10px 8px', borderRadius: 12,
                    background: on ? `${o.c}18` : 'transparent',
                    border: `1px solid ${on ? o.c : T.line}`,
                    textAlign: 'center', fontSize: 12, fontWeight: 700,
                    color: on ? o.c : T.ink,
                  }}>{o.l}</div>
                </Tap>
              );
            })}
          </div>
        </div>

        {/* Cost */}
        <div style={{
          marginTop: 12, padding: 14, background: T.card, borderRadius: 18, border: `1px solid ${T.line}`,
          display: 'flex', justifyContent: 'space-between', alignItems: 'center',
        }}>
          <div>
            <div style={{ fontSize: 11, color: T.mute }}>Оценка времени</div>
            <div style={{ marginTop: 2, fontSize: 17, fontWeight: 800, color: T.ink, letterSpacing: -0.3 }}>
              ~{8 + assignees.length * 3} мин
            </div>
          </div>
          <span style={{ fontSize: 11, color: T.mute }}>{assignees.length} исп.</span>
        </div>

        <div style={{ height: 16 }} />

        {/* Submit */}
        <Tap onClick={() => { nav.toast(`✓ Задача отправлена ${teamMode ? 'команде' : 'сотруднику'}`); nav.popToHome(); }}>
          <div style={{
            padding: 16, background: text.trim() ? T.accent : T.line,
            color: text.trim() ? '#fff' : T.mute,
            borderRadius: 16, textAlign: 'center',
            fontSize: 15, fontWeight: 700, letterSpacing: -0.2,
            boxShadow: text.trim() ? `0 12px 28px -12px ${T.accent}AA` : 'none',
            transition: 'all .2s',
          }}>Отправить задачу{teamMode ? ' команде' : ''}</div>
        </Tap>

        <div style={{ height: 24 }} />
      </Scroller>
    </React.Fragment>
  );
}

// ──────────────────────────────────────────────────────────────
// SCREEN: NOTIFICATIONS
// ──────────────────────────────────────────────────────────────
function NotificationsScreen({ T, nav }) {
  const items = getNotifications(nav.dept);
  return (
    <React.Fragment>
      <ScreenHeader T={T} title="Уведомления" back={nav.pop}
        right={<Tap onClick={() => nav.toast('Прочитано всё')}><span style={{ fontSize: 12, color: T.accent, fontWeight: 600 }}>Прочитать всё</span></Tap>}
      />
      <Scroller style={{ padding: '0 14px' }}>
        <div style={{
          background: T.card, borderRadius: 18, border: `1px solid ${T.line}`, overflow: 'hidden',
        }}>
          {items.map((it, i) => {
            const p = getMember(nav.dept, it.id);
            return (
              <Tap key={i} onClick={() => nav.push({ kind: 'task', employeeId: it.id })}>
                <div style={{
                  padding: '14px 14px', display: 'flex', gap: 12, alignItems: 'flex-start',
                  borderBottom: i < items.length - 1 ? `1px solid ${T.divider}` : 'none',
                  background: it.unread ? `${T.accent}06` : 'transparent',
                  position: 'relative',
                }}>
                  {it.unread && (
                    <span style={{
                      position: 'absolute', left: 4, top: '50%', transform: 'translateY(-50%)',
                      width: 6, height: 6, borderRadius: 6, background: T.accent,
                    }} />
                  )}
                  <div style={{
                    width: 38, height: 38, borderRadius: 38, overflow: 'hidden',
                    flexShrink: 0, background: T.portraitBg, marginLeft: it.unread ? 8 : 0,
                  }}>
                    <img src={PORTRAIT[it.portrait || it.id]} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 15.5, color: T.ink, letterSpacing: -0.1 }}>
                      <strong style={{ fontWeight: 700 }}>{p.name}</strong>{' '}
                      <span style={{ color: T.mute }}>{it.text}</span>
                    </div>
                    <div style={{ fontSize: 11, color: T.mute, marginTop: 2 }}>{it.when}</div>
                  </div>
                  {it.tag && (
                    <span style={{
                      padding: '4px 8px', borderRadius: 8, alignSelf: 'center',
                      background: it.tag === 'Готово' ? T.okBg : `${T.accent}15`,
                      color: it.tag === 'Готово' ? T.okText : T.accent,
                      fontSize: 10.5, fontWeight: 700,
                    }}>{it.tag}</span>
                  )}
                </div>
              </Tap>
            );
          })}
        </div>
      </Scroller>
    </React.Fragment>
  );
}

// ──────────────────────────────────────────────────────────────
// SCREEN: BALANCE / TOP-UP
// ──────────────────────────────────────────────────────────────
function BalanceScreen({ T, nav }) {
  const [selected, setSelected] = React.useState('mid');
  const packages = [
    { v: 'small',  amount: '10 000',  price: '990 ₽',   tag: null },
    { v: 'mid',    amount: '50 000',  price: '3 990 ₽', tag: 'Популярный' },
    { v: 'large',  amount: '120 000', price: '8 490 ₽', tag: 'Выгодно' },
    { v: 'xl',     amount: '300 000', price: '19 900 ₽',tag: null },
  ];
  return (
    <React.Fragment>
      <ScreenHeader T={T} title="Баланс" back={nav.pop} />
      <Scroller style={{ padding: '0 14px' }}>
        {/* Balance hero */}
        <div style={{
          background: `linear-gradient(135deg, ${T.accent}, ${T.accent}CC)`,
          borderRadius: 22, padding: 22, color: '#fff', position: 'relative', overflow: 'hidden',
          boxShadow: `0 16px 32px -16px ${T.accent}AA`,
        }}>
          <div style={{ position: 'absolute', right: -50, top: -50, width: 200, height: 200, borderRadius: '50%', background: 'rgba(255,255,255,0.08)' }} />
          <div style={{ position: 'relative' }}>
            <div style={{ fontSize: 12, opacity: 0.85, letterSpacing: 0.4, textTransform: 'uppercase', fontWeight: 700 }}>Текущий баланс</div>
            <div style={{ marginTop: 8, display: 'flex', alignItems: 'baseline', gap: 8 }}>
              {I.diamond('#fff')}
              <span style={{ fontSize: 38, fontWeight: 800, letterSpacing: -1.2, fontVariantNumeric: 'tabular-nums' }}>12 450</span>
              <span style={{ fontSize: 14, opacity: 0.8 }}>кред.</span>
            </div>
            <div style={{ marginTop: 6, fontSize: 12, opacity: 0.85 }}>≈ 69 задач среднего объёма</div>
          </div>
        </div>

        {/* Packages */}
        <div style={{ marginTop: 16, fontSize: 11, fontWeight: 700, color: T.mute, letterSpacing: 0.4, textTransform: 'uppercase', paddingLeft: 6 }}>Пополнить</div>
        <div style={{ marginTop: 10, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          {packages.map(pkg => {
            const on = selected === pkg.v;
            return (
              <Tap key={pkg.v} onClick={() => setSelected(pkg.v)}>
                <div style={{
                  padding: 14, background: T.card, borderRadius: 16,
                  border: `2px solid ${on ? T.accent : T.line}`,
                  position: 'relative',
                  boxShadow: on ? `0 10px 24px -16px ${T.accent}77` : T.shadow,
                  transition: 'all .15s',
                }}>
                  {pkg.tag && (
                    <span style={{
                      position: 'absolute', top: -8, left: 12,
                      padding: '3px 8px', borderRadius: 6,
                      background: T.accent, color: '#fff',
                      fontSize: 10, fontWeight: 700,
                    }}>{pkg.tag}</span>
                  )}
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                    {I.diamond(T.accent)}
                    <span style={{ fontSize: 17, fontWeight: 800, color: T.ink, fontVariantNumeric: 'tabular-nums' }}>{pkg.amount}</span>
                  </div>
                  <div style={{ marginTop: 4, fontSize: 15.5, fontWeight: 700, color: T.accent }}>{pkg.price}</div>
                </div>
              </Tap>
            );
          })}
        </div>

        <Tap onClick={() => { nav.toast('✓ Платёж принят'); nav.pop(); }}>
          <div style={{
            marginTop: 18, padding: 16, background: T.accent, color: '#fff',
            borderRadius: 16, textAlign: 'center',
            fontSize: 15, fontWeight: 700, letterSpacing: -0.2,
            boxShadow: `0 12px 28px -12px ${T.accent}AA`,
          }}>Оплатить · {packages.find(x => x.v === selected).price}</div>
        </Tap>

        {/* Recent transactions */}
        <div style={{ marginTop: 18, fontSize: 11, fontWeight: 700, color: T.mute, letterSpacing: 0.4, textTransform: 'uppercase', paddingLeft: 6 }}>История</div>
        <div style={{
          marginTop: 10, background: T.card, borderRadius: 18,
          border: `1px solid ${T.line}`, overflow: 'hidden',
        }}>
          {[
            { t: 'Задача · Анализ конкурентов',   when: '10:35', d: -1800 },
            { t: 'Задача · Тексты лендинга',       when: '09:12', d: -1200 },
            { t: 'Пополнение баланса',             when: 'Вчера', d: +50000 },
            { t: 'Задача · Баннеры',               when: 'Вчера', d: -2400 },
          ].map((tx, i) => (
            <div key={i} style={{
              padding: '12px 14px', display: 'flex', justifyContent: 'space-between',
              borderBottom: i < 3 ? `1px solid ${T.divider}` : 'none',
            }}>
              <div>
                <div style={{ fontSize: 15.5, color: T.ink, fontWeight: 600 }}>{tx.t}</div>
                <div style={{ fontSize: 11, color: T.mute, marginTop: 1 }}>{tx.when}</div>
              </div>
              <span style={{
                fontSize: 14, fontWeight: 700,
                color: tx.d > 0 ? T.ok : T.ink,
                fontVariantNumeric: 'tabular-nums',
              }}>{tx.d > 0 ? '+' : ''}{tx.d.toLocaleString('ru')}</span>
            </div>
          ))}
        </div>

        <div style={{ height: 20 }} />
      </Scroller>
    </React.Fragment>
  );
}

// ──────────────────────────────────────────────────────────────
// TAB SCREENS
// ──────────────────────────────────────────────────────────────
function TasksTab({ T, nav, stateMode }) {
  const [filter, setFilter] = React.useState('Все');
  const team = buildTeam(nav.dept, stateMode);
  const working = team.filter(p => p.task);
  return (
    <React.Fragment>
      <ScreenHeader T={T} title="Задачи"
        right={<Tap onClick={() => nav.push({ kind: 'new-task' })}>
          <div style={{ padding: '8px 12px', background: T.accent, color: '#fff', borderRadius: 10, fontSize: 12, fontWeight: 700, display: 'flex', alignItems: 'center', gap: 4 }}>
            {I.plus('#fff')} Новая
          </div>
        </Tap>}
      />
      <Scroller style={{ padding: '0 14px' }}>
        <div style={{ display: 'flex', gap: 6, marginBottom: 12 }}>
          {['Все', 'В работе', 'Готово'].map((t) => (
            <Tap key={t} onClick={function() { setFilter(t); }}>
              <span style={{
                padding: '6px 12px', borderRadius: 99,
                background: filter === t ? T.accent : T.card,
                color: filter === t ? '#fff' : T.ink,
                border: filter === t ? 'none' : '1px solid ' + T.line,
                fontSize: 12, fontWeight: 600, display: 'block',
              }}>{t}</span>
            </Tap>
          ))}
        </div>

        {working.length === 0 && filter !== 'Готово' && (
          <div style={{
            padding: 32, background: T.card, borderRadius: 18, border: '1px solid ' + T.line,
            textAlign: 'center', color: T.mute, fontSize: 15.5,
          }}>Нет активных задач. Поручи что-нибудь команде.</div>
        )}

        {(filter === 'Все' || filter === 'В работе') && working.map(p => {
          const idx = PHASES.findIndex(ph => ph.key === p.task.phase);
          const pct = Math.round(((idx + 0.7) / PHASES.length) * 100);
          return (
            <Tap key={p.id} onClick={() => nav.push({ kind: 'task', employeeId: p.id })}>
              <div style={{
                marginBottom: 10, padding: 14, background: T.card,
                borderRadius: 16, border: `1px solid ${T.line}`, boxShadow: T.shadow,
              }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <Portrait id={p.id} size={42} working={true} T={T} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 16, fontWeight: 700, color: T.ink, letterSpacing: -0.2 }}>{p.task.title}</div>
                    <div style={{ fontSize: 11.5, color: T.mute, marginTop: 2 }}>{p.name} · {p.role}</div>
                  </div>
                  <span style={{ fontSize: 11, color: T.mute, fontWeight: 600 }}>{pct}%</span>
                </div>
                <div style={{ marginTop: 10 }}>
                  <MiniProgress pct={pct} T={T} />
                </div>
                <div style={{ marginTop: 6, fontSize: 11, color: T.accent, fontWeight: 600 }}>
                  {PHASES[idx].label} · ~{14 - idx * 2} мин
                </div>
              </div>
            </Tap>
          );
        })}

        {(filter === 'Все' || filter === 'Готово') && (
          <div style={{ marginTop: 8, marginBottom: 8, fontSize: 11, fontWeight: 700, color: T.mute, letterSpacing: 0.4, textTransform: 'uppercase', paddingLeft: 6 }}>Готово сегодня</div>
        )}
        {(filter === 'Все' || filter === 'Готово') && getDone(nav.dept).map((t, i) => (
          <Tap key={i} onClick={() => nav.push({ kind: 'task', employeeId: t.id })}>
            <div style={{
              marginBottom: 8, padding: 14, background: T.card,
              borderRadius: 16, border: `1px solid ${T.line}`,
              display: 'flex', alignItems: 'center', gap: 10,
            }}>
              <div style={{
                width: 36, height: 36, borderRadius: 36, overflow: 'hidden',
                background: T.portraitBg, flexShrink: 0,
              }}>
                <img src={PORTRAIT[t.portrait || t.id]} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontSize: 15.5, fontWeight: 700, color: T.ink, letterSpacing: -0.2 }}>{t.title}</div>
                <div style={{ fontSize: 11, color: T.mute, marginTop: 1 }}>{t.time}</div>
              </div>
              <span style={{
                padding: '4px 8px', borderRadius: 8, background: T.okBg, color: T.okText,
                fontSize: 10.5, fontWeight: 700,
              }}>✓ Готово</span>
            </div>
          </Tap>
        ))}
        <div style={{ height: 20 }} />
      </Scroller>
    </React.Fragment>
  );
}

function TeamTab({ T, nav, stateMode }) {
  const team = buildTeam(nav.dept, stateMode);
  return (
    <React.Fragment>
      <ScreenHeader T={T} title="Команда" />
      <Scroller style={{ padding: '0 14px' }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          {team.map(p => (
            <Tap key={p.id} onClick={() => nav.push({ kind: 'employee', employeeId: p.id })}>
              <EmployeeCard p={p} T={T} />
            </Tap>
          ))}
        </div>
        <div style={{ height: 20 }} />
      </Scroller>
    </React.Fragment>
  );
}

function ProfileTab({ T, nav, onToggleTheme, apiUser, activeProject, setActiveProject, activeProjectName, setActiveProjectName }) {
  var [showProjectSheet, setShowProjectSheet] = React.useState(false);
  var [showSprintModal, setShowSprintModal] = React.useState(false);
  var [sprintStatus, setSprintStatus] = React.useState(null);
  var [sprintTask, setSprintTask] = React.useState('');

  function handleSelectProject(slug, name) {
    setShowProjectSheet(false);
    setActiveProject(slug);
    if (name && setActiveProjectName) setActiveProjectName(name);
    if (window.AI_API && window.AI_API.getToken()) {
      try { localStorage.setItem('ai_active_project', slug); if (name) localStorage.setItem('ai_active_project_name', name); } catch (e) {}
      window.AI_API.patchMe({ active_project_slug: slug }).catch(function() {});
    }
  }

  return (
    <React.Fragment>
      {showProjectSheet && window.ProjectsBottomSheet && (
        <ProjectsBottomSheet
          T={T} nav={nav}
          currentSlug={activeProject}
          onSelect={handleSelectProject}
          onClose={function() { setShowProjectSheet(false); }}
        />
      )}
      <ScreenHeader T={T} title="Профиль" />
      <Scroller style={{ padding: '0 14px' }}>
        <div style={{
          background: T.card, borderRadius: 22, padding: 22, border: `1px solid ${T.line}`,
          display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 10,
        }}>
          <div style={{
            width: 80, height: 80, borderRadius: 80,
            background: `linear-gradient(135deg, ${T.accent}, ${T.accent}AA)`,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            color: '#fff', fontSize: 32, fontWeight: 800, letterSpacing: -1,
          }}>{ (apiUser && apiUser.first_name) ? apiUser.first_name[0].toUpperCase() : "А" }</div>
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontSize: 18, fontWeight: 800, color: T.ink }}>{ (apiUser && apiUser.first_name) || "Пользователь" }</div>
            <div style={{ fontSize: 12, color: T.mute, marginTop: 2 }}>{ apiUser ? ("@" + (apiUser.username || "telegram")) : "Открой в Telegram" }</div>
          </div>
        </div>

        {/* Рабочий контекст */}
        <div style={{ margin: '20px 14px 0' }}>
          <div style={{ fontSize: 11, fontWeight: 700, color: T.mute, letterSpacing: 0.5, textTransform: 'uppercase', marginBottom: 8 }}>
            Рабочий контекст
          </div>
          <div style={{ background: T.card, borderRadius: 16, border: '1px solid ' + T.line, overflow: 'hidden' }}>
            <Tap onClick={function() { setShowProjectSheet(true); }}>
              <div style={{ padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 12, borderBottom: '1px solid ' + T.divider }}>
                <div style={{ width: 36, height: 36, borderRadius: 10, background: T.accent + '18', display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  <svg width="17" height="17" viewBox="0 0 24 24" fill="none">
                    <path d="M3 7a2 2 0 012-2h4l2 2h8a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V7z" stroke={T.accent} strokeWidth="1.7" strokeLinecap="round"/>
                  </svg>
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, color: T.mute }}>Активный проект</div>
                  <div style={{ fontSize: 15, fontWeight: 700, color: T.accent, marginTop: 1 }}>
                    {activeProjectName || 'Не выбран'}
                  </div>
                </div>
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                  <path d="M9 6l6 6-6 6" stroke={T.mute} strokeWidth="1.8" strokeLinecap="round"/>
                </svg>
              </div>
            </Tap>
            <Tap onClick={function() { setShowProjectSheet(true); }}>
              <div style={{ padding: '14px 16px', display: 'flex', alignItems: 'center', gap: 12 }}>
                <div style={{ width: 36, height: 36, borderRadius: 10, background: T.bg, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                  <svg width="17" height="17" viewBox="0 0 24 24" fill="none">
                    <rect x="3" y="3" width="7" height="7" rx="1.5" stroke={T.mute} strokeWidth="1.7"/>
                    <rect x="14" y="3" width="7" height="7" rx="1.5" stroke={T.mute} strokeWidth="1.7"/>
                    <rect x="3" y="14" width="7" height="7" rx="1.5" stroke={T.mute} strokeWidth="1.7"/>
                    <rect x="14" y="14" width="7" height="7" rx="1.5" stroke={T.mute} strokeWidth="1.7"/>
                  </svg>
                </div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 15, fontWeight: 600, color: T.ink }}>Все проекты</div>
                </div>
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none">
                  <path d="M9 6l6 6-6 6" stroke={T.mute} strokeWidth="1.8" strokeLinecap="round"/>
                </svg>
              </div>
            </Tap>
          </div>
          <div style={{ fontSize: 11.5, color: T.mute, marginTop: 8 }}>
            Проект задаёт контекст для всех отделов сразу.
          </div>
        </div>

        <div style={{
          marginTop: 12, background: T.card, borderRadius: 18, border: `1px solid ${T.line}`, overflow: 'hidden',
        }}>
          {[
            { l: 'Тариф',         v: 'Pro' },
            { l: 'Подписка до',   v: '14 июня 2026' },
            { l: 'Команда',       v: '8 AI-сотрудников' },
            { l: 'Задач за месяц',v: '142' },
          ].map((r, i) => (
            <Tap key={i} onClick={() => nav.toast('Настройки откроются позже')}>
              <div style={{
                padding: '14px 16px', display: 'flex', justifyContent: 'space-between',
                borderBottom: i < 3 ? `1px solid ${T.divider}` : 'none',
              }}>
                <span style={{ fontSize: 15.5, color: T.ink }}>{r.l}</span>
                <span style={{ fontSize: 15.5, color: T.mute, fontWeight: 600 }}>{r.v}</span>
              </div>
            </Tap>
          ))}
        </div>

        <div style={{
          marginTop: 12, background: T.card, borderRadius: 18, border: `1px solid ${T.line}`, overflow: 'hidden',
        }}>
          {[
            { l: 'Уведомления',          to: 'notifications' },
            { l: 'Подключённые сервисы', to: null },
            { l: 'Безопасность',         to: null },
            { l: 'Помощь и поддержка',   to: null },
          ].map((r, i) => (
            <Tap key={i} onClick={() => r.to ? nav.push({ kind: r.to }) : nav.toast('Скоро будет')}>
              <div style={{
                padding: '14px 16px', display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                borderBottom: i < 3 ? `1px solid ${T.divider}` : 'none',
              }}>
                <span style={{ fontSize: 15.5, color: T.ink, fontWeight: 600 }}>{r.l}</span>
                {I.chevron(T.mute)}
              </div>
            </Tap>
          ))}
        </div>

        <div style={{ height: 20 }} />
      </Scroller>
    </React.Fragment>
  );
}

Object.assign(window, {
  ACTIVITY: null,
  HubScreen, HomeScreen, TaskScreen, NewTaskScreen, NotificationsScreen, BalanceScreen,
  TasksTab, TeamTab, ProfileTab,
  Tap, ScreenHeader, Scroller,
});
