// Team panel: project members, workload, recent activity
const TEAMIcons = window.Icons;

function TeamView({ state, currentUser, onOpenMembers }) {
  const [membersMap, setMembersMap] = React.useState({});
  const [loading,    setLoading]    = React.useState(false);
  const [loadedKey,  setLoadedKey]  = React.useState('');

  const projects    = state.projects || [];
  const tasks       = state.tasks    || [];
  const projById    = React.useMemo(() => Object.fromEntries(projects.map(p => [p.id, p])), [projects]);

  // Tüm kendi (shared olmayan, arşivlenmemiş) projeler — memberCount'a bakma,
  // her zaman API'den sorgula ki accept sonrası sayfa güncel kalsın
  const sharedProjects = React.useMemo(
    () => projects.filter(p => !p._shared && !p.archived),
    [projects]
  );
  const sharedKey = sharedProjects.map(p => p.id).join(',');

  React.useEffect(() => {
    if (!sharedProjects.length || sharedKey === loadedKey) return;
    setLoading(true);
    Promise.all(
      sharedProjects.map(p =>
        fetch(`./api/invite.php?action=members&projectKey=${encodeURIComponent(p.id)}`, { credentials: 'include' })
          .then(r => r.json())
          .then(d => [p.id, d.ok ? { members: d.members || [], pending: d.pending || [] } : { members: [], pending: [] }])
          .catch(() => [p.id, { members: [], pending: [] }])
      )
    ).then(results => {
      setMembersMap(Object.fromEntries(results));
      setLoadedKey(sharedKey);
      setLoading(false);
    });
  }, [sharedKey]);

  // Unique members aggregated across all shared projects
  const allMembers = React.useMemo(() => {
    const list = [];
    const seen = new Set();
    Object.entries(membersMap).forEach(([projectId, d]) => {
      (d.members || []).forEach(m => {
        if (seen.has(m.id)) return;
        seen.add(m.id);
        const memberProjectIds = sharedProjects
          .filter(p => (membersMap[p.id]?.members || []).some(mm => mm.id === m.id))
          .map(p => p.id);
        list.push({
          ...m,
          projectIds:  memberProjectIds,
          activeCount: tasks.filter(t => memberProjectIds.includes(t.projectId) && t.status !== 'done').length,
          doneCount:   tasks.filter(t => memberProjectIds.includes(t.projectId) && t.status === 'done').length,
        });
      });
    });
    return list;
  }, [membersMap, tasks, sharedProjects]);

  // Recent activity — tasks updated in last 7 days
  const recentActivity = React.useMemo(() => {
    const cut = new Date(); cut.setDate(cut.getDate() - 7);
    return [...tasks]
      .filter(t => t.updatedAt && new Date(t.updatedAt) > cut)
      .sort((a, b) => new Date(b.updatedAt) - new Date(a.updatedAt))
      .slice(0, 8);
  }, [tasks]);

  const ownerActiveCount = tasks.filter(t => t.status !== 'done').length;
  const ownerDoneCount   = tasks.filter(t => t.status === 'done').length;

  // API yüklendikten sonra hiç üye yoksa boş durum göster
  const hasAnyMembers = allMembers.length > 0 ||
    Object.values(membersMap).some(d => (d.pending || []).length > 0);

  if (!loading && sharedKey === loadedKey && !hasAnyMembers) {
    return (
      <div className="content">
        <div className="team-empty">
          <div style={{ width: 64, height: 64, borderRadius: 12, background: 'var(--accent-soft)', color: 'var(--accent-text)', display: 'grid', placeItems: 'center' }}>
            <TEAMIcons.Users size={28} />
          </div>
          <h2>Henüz takım üyeniz yok</h2>
          <p>Projenizi ekibinizle paylaşarak birlikte çalışmaya başlayın.</p>
          <p style={{ fontSize: 13, color: 'var(--text-faint)' }}>
            Kenar çubuğunda proje üzerine gelince 👥 simgesine tıklayarak davet oluşturabilirsiniz.
          </p>
        </div>
      </div>
    );
  }

  // Yükleniyor
  if (loading || sharedKey !== loadedKey) {
    return (
      <div className="content">
        <div className="team-empty">
          <div style={{ fontSize: 13, color: 'var(--text-muted)' }}>Ekip bilgileri yükleniyor...</div>
        </div>
      </div>
    );
  }

  // ── Main content ─────────────────────────────────────────
  return (
    <div className="content report-content">
      <div className="report-header">
        <h2 className="report-title">Ekip</h2>
        <span style={{ fontSize: 13, color: 'var(--text-muted)' }}>
          {allMembers.length} üye · {sharedProjects.filter(p => (membersMap[p.id]?.members?.length || 0) + (membersMap[p.id]?.pending?.length || 0) > 0).length} paylaşılan proje
        </span>
      </div>

      <div className="report-grid">

        {/* ── Member list ── */}
        <div className="card report-card report-card-wide">
          <div className="report-card-title">Üyeler</div>

          {/* Owner row */}
          <MemberRow
            name={currentUser?.name || 'Siz'}
            email={currentUser?.email || ''}
            avatarUrl={currentUser?.avatarUrl}
            roleBadge={<span className="member-role-badge role-owner">Sahip</span>}
            activeCount={ownerActiveCount}
            doneCount={ownerDoneCount}
          />

          {loading && <div className="report-empty">Yükleniyor...</div>}

          {!loading && allMembers.length === 0 && (
            <div className="report-empty">Henüz kabul edilmiş üye yok. Davet bağlantısını paylaşın.</div>
          )}

          {!loading && allMembers.map(m => (
            <MemberRow
              key={m.id}
              name={m.name || m.email}
              email={m.email}
              avatarUrl={m.avatarUrl}
              roleBadge={
                <span className={`member-role-badge role-${m.role}`}>
                  {m.role === 'editor' ? 'Editör' : 'Görüntüleyici'}
                </span>
              }
              activeCount={m.activeCount}
              doneCount={m.doneCount}
              projects={m.projectIds.map(pid => projById[pid]).filter(Boolean)}
            />
          ))}
        </div>

        {/* ── Shared projects — sadece gerçek üyesi/bekleyeni olanlar ── */}
        <div className="card report-card">
          <div className="report-card-title">Paylaşılan Projeler</div>
          {sharedProjects.filter(p => {
            const mc = membersMap[p.id]?.members?.length || 0;
            const pc = membersMap[p.id]?.pending?.length || 0;
            return mc > 0 || pc > 0;
          }).map(p => {
            const memberCount = membersMap[p.id]?.members?.length || 0;
            const pending     = membersMap[p.id]?.pending?.length || 0;
            const pTasks      = tasks.filter(t => t.projectId === p.id);
            const pDone       = pTasks.filter(t => t.status === 'done').length;
            const pct         = pTasks.length ? Math.round(pDone / pTasks.length * 100) : 0;
            return (
              <div key={p.id} className="team-project-row">
                <div style={{
                  width: 28, height: 28, borderRadius: 6,
                  background: p.color, flexShrink: 0,
                  display: 'grid', placeItems: 'center', color: 'white', fontWeight: 700, fontSize: 11,
                }}>
                  {(p.name || '?').charAt(0).toUpperCase()}
                </div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontWeight: 600, fontSize: 13.5, color: 'var(--text)' }}>{p.name}</div>
                  <div style={{ fontSize: 12, color: 'var(--text-muted)', marginTop: 2 }}>
                    {memberCount} üye {pending > 0 ? `· ${pending} bekleyen` : ''}
                  </div>
                  <div className="progress-bar" style={{ width: '100%', marginTop: 6 }}>
                    <div className="progress-bar-fill" style={{ width: `${pct}%`, background: p.color }} />
                  </div>
                </div>
                <span style={{ fontWeight: 700, fontSize: 13, color: 'var(--text-muted)', minWidth: 36, textAlign: 'right' }}>{pct}%</span>
                <button className="icon-btn icon-btn-sm" onClick={() => onOpenMembers?.(p)} title="Üyeleri yönet">
                  <TEAMIcons.Users size={14} />
                </button>
              </div>
            );
          })}
          {sharedProjects.every(p => !(membersMap[p.id]?.members?.length || membersMap[p.id]?.pending?.length)) && (
            <div className="report-empty">Henüz paylaşılan proje yok</div>
          )}
        </div>

        {/* ── Workload chart ── */}
        {allMembers.length > 0 && (
          <div className="card report-card report-card-wide">
            <div className="report-card-title">İş Yükü Dağılımı</div>
            <div className="workload-chart">
              {/* Owner row */}
              <WorkloadRow
                name={currentUser?.name || 'Siz'}
                active={ownerActiveCount}
                done={ownerDoneCount}
                maxActive={Math.max(ownerActiveCount, ...allMembers.map(m => m.activeCount), 1)}
              />
              {allMembers.map(m => (
                <WorkloadRow key={m.id} name={m.name || m.email}
                  active={m.activeCount} done={m.doneCount}
                  maxActive={Math.max(ownerActiveCount, ...allMembers.map(mm => mm.activeCount), 1)}
                />
              ))}
            </div>
          </div>
        )}

        {/* ── Recent activity ── */}
        <div className="card report-card">
          <div className="report-card-title">Son Aktiviteler</div>
          {recentActivity.length === 0 ? (
            <div className="report-empty">Bu hafta güncelleme yok</div>
          ) : (
            <div className="report-recent-list">
              {recentActivity.map(t => {
                const proj = projById[t.projectId];
                const statusLabels = { todo: 'Yapılacak', doing: 'Devam Ediyor', review: 'İncelemede', done: 'Tamamlandı' };
                const dateStr = t.updatedAt
                  ? new Date(t.updatedAt).toLocaleDateString('tr-TR', { day: 'numeric', month: 'short' })
                  : '';
                return (
                  <div key={t.id} className="report-recent-item">
                    <span className="project-dot" style={{ background: proj?.color || 'var(--text-faint)' }} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div className="report-recent-title">{t.title}</div>
                      <div style={{ fontSize: 11, color: 'var(--text-faint)' }}>
                        {proj?.name} · {statusLabels[t.status] || t.status}
                      </div>
                    </div>
                    <span className="report-recent-date">{dateStr}</span>
                  </div>
                );
              })}
            </div>
          )}
        </div>

      </div>
    </div>
  );
}

function MemberRow({ name, email, avatarUrl, roleBadge, activeCount, doneCount, projects }) {
  const initials = window.projectAbbr ? window.projectAbbr(name || 'U') : (name || 'U').slice(0, 2).toUpperCase();
  return (
    <div className="team-member-row">
      {avatarUrl
        ? <img src={avatarUrl} className="avatar avatar-img" alt="" style={{ width: 38, height: 38 }} />
        : <div className="avatar" style={{ width: 38, height: 38, fontSize: 13 }}>{initials}</div>
      }
      <div className="team-member-info">
        <div className="team-member-name">{name} {roleBadge}</div>
        <div className="team-member-email">{email}</div>
        {projects && projects.length > 0 && (
          <div className="team-member-projects">
            {projects.map(p => (
              <span key={p.id} className="team-project-chip">
                <span className="project-dot" style={{ background: p.color }} />
                {p.name}
              </span>
            ))}
          </div>
        )}
      </div>
      <div className="team-member-stats">
        <div className="team-stat">
          <span>{activeCount}</span>
          <small>Aktif</small>
        </div>
        <div className="team-stat accent">
          <span>{doneCount}</span>
          <small>Bitti</small>
        </div>
      </div>
    </div>
  );
}

function WorkloadRow({ name, active, done, maxActive }) {
  const pct = maxActive > 0 ? Math.round((active / maxActive) * 100) : 0;
  const tone = pct > 80 ? 'busy' : pct > 50 ? 'balanced' : 'light';
  return (
    <div className="workload-row">
      <span className="workload-name">{name}</span>
      <div className="workload-bar-track">
        <div className={`workload-bar-fill workload-${tone}`} style={{ width: `${pct}%` }} />
      </div>
      <span className="workload-stats">{active} aktif · {done} bitti</span>
    </div>
  );
}

window.TeamView = TeamView;
