/* ============================================
   TEAM VIEW — member directory, workload, profiles
   ============================================ */

const TeamView = ({ tasks, onScopeToMember, onOpenTask, currentUser }) => {
  const [search, setSearch] = React.useState('');
  const [expanded, setExpanded] = React.useState(null);

  const members = USERS.map(u => {
    const userTasks = tasks.filter(t => t.assignee === u.id || t.pic === u.id);
    const active = userTasks.filter(t => !['Done','Cancel','Archived'].includes(t.status));
    const done = userTasks.filter(t => t.status === 'Done');
    const overdue = active.filter(t => {
      const d = daysFromToday(t.dueDate);
      return d !== null && d < 0;
    });
    const projectIds = [...new Set(userTasks.map(t => t.project).filter(Boolean))];

    // capacity (rough: 5 active = 100%)
    const capacity = Math.min(100, Math.round((active.length / 5) * 100));

    return { user: u, userTasks, active, done, overdue, projectIds, capacity };
  });

  const filtered = members.filter(m =>
    !search ||
    m.user.name.toLowerCase().includes(search.toLowerCase()) ||
    m.user.role.toLowerCase().includes(search.toLowerCase())
  );

  // totals
  const totalActive = members.reduce((a, b) => a + b.active.length, 0);
  const totalDone = members.reduce((a, b) => a + b.done.length, 0);
  const totalOverdue = members.reduce((a, b) => a + b.overdue.length, 0);

  return (
    <div style={{ padding: '24px', maxWidth: 1280, margin: '0 auto' }}>
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 16, marginBottom: 24, flexWrap: 'wrap' }}>
        <div style={{ flex: 1, minWidth: 240 }}>
          <h1 style={{ fontSize: 24, fontWeight: 800, letterSpacing: '-0.03em', marginBottom: 4 }}>Team</h1>
          <p style={{ fontSize: 13.5, color: 'var(--text-muted)', margin: 0 }}>
            {USERS.length} members · {totalActive} active tasks · {totalOverdue} overdue
          </p>
        </div>
        <div className="tb-search" style={{ width: 260 }}>
          <Icon name="search" size={14} />
          <input
            placeholder="Search by name or role…"
            value={search}
            onChange={(e) => setSearch(e.target.value)}
          />
        </div>
        <Btn kind="primary" icon="plus">Invite member</Btn>
      </div>

      {/* Summary cards */}
      <div className="dash-stats" style={{ marginBottom: 20 }}>
        <StatCard icon="users" color="#6D49F2" num={USERS.length} label="Team members" />
        <StatCard icon="clock" color="#3B82F6" num={totalActive} label="Active tasks" />
        <StatCard icon="check" color="#10B981" num={totalDone} label="Done this period" />
        <StatCard icon="warning" color="#F43F5E" num={totalOverdue} label="Total overdue" />
      </div>

      {/* Member grid */}
      <div style={{
        display: 'grid',
        gridTemplateColumns: 'repeat(auto-fill, minmax(280px, 1fr))',
        gap: 14,
      }}>
        {filtered.map(m => {
          const isMe = m.user.id === currentUser.id;
          const isExpanded = expanded === m.user.id;
          let capacityColor = 'var(--c-emerald)';
          if (m.capacity > 80) capacityColor = 'var(--c-rose)';
          else if (m.capacity > 60) capacityColor = 'var(--c-orange)';
          else if (m.capacity > 40) capacityColor = 'var(--c-amber)';

          return (
            <div
              key={m.user.id}
              style={{
                background: 'var(--bg-elevated)',
                border: '1px solid var(--border)',
                borderRadius: 14,
                padding: 18,
                position: 'relative',
                transition: 'all .15s ease',
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.borderColor = 'var(--border-strong)';
                e.currentTarget.style.boxShadow = 'var(--shadow-md)';
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.borderColor = 'var(--border)';
                e.currentTarget.style.boxShadow = '';
              }}
            >
              {isMe && (
                <span style={{
                  position: 'absolute', top: 12, right: 12,
                  fontSize: 10, fontWeight: 700,
                  background: 'var(--brand-50)', color: 'var(--brand-600)',
                  padding: '2px 8px', borderRadius: 99, letterSpacing: '0.04em', textTransform: 'uppercase',
                }}>You</span>
              )}
              <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 12 }}>
                <Avatar user={m.user} size="xl" />
                <div style={{ minWidth: 0, flex: 1 }}>
                  <div style={{ fontSize: 15, fontWeight: 700, letterSpacing: '-0.01em', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>
                    {m.user.name}
                  </div>
                  <div style={{ fontSize: 12, color: 'var(--text-muted)', fontWeight: 500 }}>{m.user.role}</div>
                  <div style={{ fontSize: 11.5, color: 'var(--text-subtle)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{m.user.email}</div>
                </div>
              </div>

              {/* Capacity */}
              <div style={{ marginBottom: 12 }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 5 }}>
                  <span style={{ fontSize: 11, fontWeight: 600, color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.04em' }}>Workload</span>
                  <span style={{ fontSize: 12, fontWeight: 700, color: capacityColor }}>{m.capacity}%</span>
                </div>
                <div className="bar-track">
                  <div className="bar-fill" style={{ width: `${m.capacity}%`, background: capacityColor }} />
                </div>
              </div>

              {/* Stats */}
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 6, marginBottom: 14 }}>
                <div style={{ background: 'var(--surface-2)', padding: '8px 10px', borderRadius: 8, textAlign: 'center' }}>
                  <div style={{ fontSize: 16, fontWeight: 800, color: 'var(--text)', fontFeatureSettings: '"tnum"' }}>{m.active.length}</div>
                  <div style={{ fontSize: 10.5, color: 'var(--text-subtle)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.04em' }}>Active</div>
                </div>
                <div style={{ background: 'var(--surface-2)', padding: '8px 10px', borderRadius: 8, textAlign: 'center' }}>
                  <div style={{ fontSize: 16, fontWeight: 800, color: 'var(--c-emerald)', fontFeatureSettings: '"tnum"' }}>{m.done.length}</div>
                  <div style={{ fontSize: 10.5, color: 'var(--text-subtle)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.04em' }}>Done</div>
                </div>
                <div style={{ background: 'var(--surface-2)', padding: '8px 10px', borderRadius: 8, textAlign: 'center' }}>
                  <div style={{ fontSize: 16, fontWeight: 800, color: m.overdue.length > 0 ? 'var(--c-rose)' : 'var(--text)', fontFeatureSettings: '"tnum"' }}>{m.overdue.length}</div>
                  <div style={{ fontSize: 10.5, color: 'var(--text-subtle)', fontWeight: 600, textTransform: 'uppercase', letterSpacing: '0.04em' }}>Overdue</div>
                </div>
              </div>

              {/* Projects */}
              {m.projectIds.length > 0 && (
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4, marginBottom: 12 }}>
                  {m.projectIds.slice(0, 3).map(pid => {
                    const p = getProject(pid);
                    if (!p) return null;
                    return (
                      <span key={pid} style={{
                        display: 'inline-flex', alignItems: 'center', gap: 4,
                        fontSize: 11, fontWeight: 600,
                        padding: '2px 7px', borderRadius: 5,
                        background: `${p.color}1A`, color: p.color,
                      }}>
                        <span style={{ width: 5, height: 5, borderRadius: '50%', background: p.color }} />
                        {p.name}
                      </span>
                    );
                  })}
                  {m.projectIds.length > 3 && (
                    <span style={{ fontSize: 11, color: 'var(--text-subtle)', padding: '2px 4px' }}>+{m.projectIds.length - 3}</span>
                  )}
                </div>
              )}

              {/* Active tasks preview (expandable) */}
              {isExpanded && m.active.length > 0 && (
                <div style={{ marginTop: 10, paddingTop: 10, borderTop: '1px solid var(--border)' }}>
                  <div style={{ fontSize: 11, fontWeight: 700, color: 'var(--text-subtle)', textTransform: 'uppercase', letterSpacing: '0.05em', marginBottom: 6 }}>
                    Current tasks
                  </div>
                  <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                    {m.active.slice(0, 4).map(t => {
                      const p = getProject(t.project);
                      return (
                        <div
                          key={t.id}
                          onClick={(e) => { e.stopPropagation(); onOpenTask(t.id); }}
                          style={{
                            display: 'flex', alignItems: 'center', gap: 8,
                            padding: '6px 8px',
                            borderRadius: 6,
                            cursor: 'pointer',
                            fontSize: 12,
                          }}
                          onMouseEnter={(e) => e.currentTarget.style.background = 'var(--surface-2)'}
                          onMouseLeave={(e) => e.currentTarget.style.background = 'transparent'}
                        >
                          {p && <span style={{ width: 6, height: 6, borderRadius: '50%', background: p.color, flexShrink: 0 }} />}
                          <span style={{ flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{t.name}</span>
                          <PriorityBadge priority={t.priority} />
                        </div>
                      );
                    })}
                    {m.active.length > 4 && (
                      <button
                        onClick={() => onScopeToMember(m.user.id)}
                        style={{ fontSize: 11.5, color: 'var(--brand-600)', background: 'transparent', border: 'none', padding: '4px 8px', cursor: 'pointer', textAlign: 'left', fontWeight: 600 }}
                      >
                        View all {m.active.length} tasks →
                      </button>
                    )}
                  </div>
                </div>
              )}

              {/* Actions */}
              <div style={{ display: 'flex', gap: 6, marginTop: 6 }}>
                <button
                  className="btn btn-secondary"
                  style={{ flex: 1, justifyContent: 'center', padding: '6px 10px', fontSize: 12 }}
                  onClick={() => setExpanded(e => e === m.user.id ? null : m.user.id)}
                >
                  {isExpanded ? 'Hide tasks' : 'View tasks'}
                </button>
                <button
                  className="btn btn-ghost"
                  style={{ padding: '6px 10px', fontSize: 12 }}
                  onClick={() => onScopeToMember(m.user.id)}
                  title="Filter board to this person"
                >
                  <Icon name="filter" size={13} />
                </button>
                <button className="btn btn-ghost" style={{ padding: '6px 10px', fontSize: 12 }} title="Send message">
                  <Icon name="message" size={13} />
                </button>
              </div>
            </div>
          );
        })}
      </div>

      {filtered.length === 0 && (
        <div className="empty-state">
          <div className="empty-state-icon"><Icon name="users" size={28} /></div>
          <h3>No members found</h3>
          <p>Try a different search.</p>
        </div>
      )}
    </div>
  );
};

Object.assign(window, { TeamView });
