// Team Home / Overview tab — at-a-glance summary.
const { useState: useStateOv } = React;

function TeamOverviewTab({ team, user, onNavigate, onSwitchTab }) {
  const store = window.AppStore.useStore();
  const safs = store.getSAFs(team.id);
  const openSAFs = safs.filter(s => s.status !== 'posted');
  const board = window.AppData.EBOARDS[team.id] || [];
  const coach = window.AppData.COACHES[team.id];
  const roster = window.AppData.ROSTERS[team.id] || [];
  const primary = board.find(b => b.primary) || board[0];

  // Upcoming events
  const upcoming = React.useMemo(() => {
    const today = new Date('2026-05-21');
    const list = [];
    window.AppData.EVENTS_APPROVED.forEach(e => {
      if (e.teamId === team.id) {
        const d = new Date(e.date + 'T00:00:00');
        if (d >= today) list.push({ ...e, dt: d, status: 'Approved' });
      }
    });
    window.AppData.EVENTS_PENDING.forEach(e => {
      if (e.teamId === team.id) {
        const d = new Date(e.date + 'T00:00:00');
        if (d >= today) list.push({ ...e, dt: d, status: 'Pending' });
      }
    });
    return list.sort((a, b) => a.dt - b.dt).slice(0, 3);
  }, [team]);

  // Reservations this week
  const myReservations = window.AppData.RESERVATIONS.filter(r => r.team === team.name);

  // Recent activity — synthesize from SAFs, events, roster
  const recent = React.useMemo(() => {
    const items = [];
    safs.slice(0, 5).forEach(s => {
      items.push({
        at: s.submittedAt,
        icon: 'Dollar', tone: 'gold',
        title: `SAF submitted \u00b7 ${s.vendor?.name || s.desc}`,
        sub: `${s.officer?.name} \u00b7 $${s.amount.toLocaleString()}`,
      });
      if (s.workflow?.posted) {
        items.push({
          at: s.workflow.posted.at,
          icon: 'Send', tone: 'success',
          title: `Funds posted \u00b7 ${s.vendor?.name || s.desc}`,
          sub: `${s.workflow.posted.by} \u00b7 sheet updated`,
        });
      }
    });
    window.AppData.EVENTS_APPROVED.forEach(e => {
      if (e.teamId === team.id) {
        items.push({
          at: e.submittedAt,
          icon: 'Calendar', tone: 'blue',
          title: `Event approved \u00b7 ${e.name}`,
          sub: `${e.location} \u00b7 by ${e.approvedBy}`,
        });
      }
    });
    return items.sort((a, b) => (b.at || '').localeCompare(a.at || '')).slice(0, 6);
  }, [team, safs]);

  const allocated = team.budget.allocated;
  const spent = team.budget.spent;
  const remaining = allocated - spent;
  const pct = Math.min(100, Math.round((spent / allocated) * 100));
  const ly = team.lastYearBudget;
  const lyPct = ly ? Math.round(((spent - ly.spent) / ly.spent) * 100) : 0;

  const signedCount = team.starterPack.done;
  const totalCount = team.starterPack.total;

  return (
    <div>
      {/* Top-line stat cards */}
      <div className="metric-grid" style={{ gridTemplateColumns: 'repeat(4, 1fr)' }}>
        <div className="card metric">
          <div className="metric-label">Status</div>
          <div className="metric-value" style={{ fontSize: 18, marginTop: 2 }}>
            <window.StatusBadge status={team.status} />
          </div>
          <div className="metric-trend">last activity {team.lastActivity.toLowerCase()}</div>
        </div>
        <div className="card metric">
          <div className="metric-label">Starter packs</div>
          <div className="metric-value">{signedCount}/{totalCount}</div>
          <div className="metric-trend">
            <span className="progress" style={{ width: '100%', marginRight: 0 }}>
              <span className="progress-fill" style={{ width: `${(signedCount / totalCount) * 100}%` }} />
            </span>
          </div>
        </div>
        <div className="card metric">
          <div className="metric-label">Budget used</div>
          <div className="metric-value cell-mono">{pct}%</div>
          <div className="metric-trend">
            ${spent.toLocaleString()} of ${allocated.toLocaleString()}
            {ly && <span style={{ marginLeft: 6, color: lyPct > 0 ? 'var(--warning)' : 'var(--success)' }}>
              {lyPct > 0 ? '\u25b2' : '\u25bc'} {Math.abs(lyPct)}% YoY
            </span>}
          </div>
        </div>
        <div className="card metric">
          <div className="metric-label">Open SAFs</div>
          <div className="metric-value">{openSAFs.length}</div>
          <div className="metric-trend">${openSAFs.reduce((s, x) => s + x.amount, 0).toLocaleString()} pending</div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 16 }}>
        {/* Left column: events + SAFs */}
        <div className="flex-col" style={{ gap: 16 }}>
          {/* Upcoming events */}
          <div className="card">
            <div className="flex-between" style={{ padding: '14px 18px', borderBottom: '1px solid var(--border)' }}>
              <strong style={{ fontSize: 13 }}>Upcoming events</strong>
              <button className="btn btn-ghost btn-xs" onClick={() => onSwitchTab && onSwitchTab('events')}>
                View all <window.I.ChevronRight size={11} />
              </button>
            </div>
            {upcoming.length === 0 ? (
              <div className="empty" style={{ padding: '32px 20px' }}>
                <div className="empty-title">No upcoming events</div>
                <div className="empty-msg">Bulk-import a season schedule from the Events page.</div>
              </div>
            ) : (
              <div>
                {upcoming.map((e, i) => (
                  <div key={i} style={{
                    padding: '14px 18px',
                    borderBottom: i === upcoming.length - 1 ? 'none' : '1px solid var(--border)',
                    display: 'flex', alignItems: 'center', gap: 14,
                  }}>
                    <div style={{
                      width: 48, textAlign: 'center', flexShrink: 0,
                      background: 'var(--surface-2)', borderRadius: 6, padding: '8px 4px',
                    }}>
                      <div style={{ fontSize: 10, color: 'var(--text-2)', textTransform: 'uppercase', fontWeight: 600 }}>
                        {e.dt.toLocaleDateString('en-US', { month: 'short' })}
                      </div>
                      <div style={{ fontSize: 18, fontWeight: 700 }}>{e.dt.getDate()}</div>
                    </div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontWeight: 600 }}>{e.name}</div>
                      <div className="dim" style={{ fontSize: 12 }}>
                        {e.location} \u00b7 {e.type} game
                      </div>
                    </div>
                    <span className={`badge ${e.status === 'Pending' ? 'warning' : 'success'} dot`}>{e.status}</span>
                  </div>
                ))}
              </div>
            )}
          </div>

          {/* Open SAFs */}
          <div className="card">
            <div className="flex-between" style={{ padding: '14px 18px', borderBottom: '1px solid var(--border)' }}>
              <strong style={{ fontSize: 13 }}>SAFs in pipeline</strong>
              <button className="btn btn-ghost btn-xs" onClick={() => onSwitchTab && onSwitchTab('budget')}>
                Open ledger <window.I.ChevronRight size={11} />
              </button>
            </div>
            {openSAFs.length === 0 ? (
              <div className="empty" style={{ padding: '32px 20px' }}>
                <div className="empty-title">Everything posted</div>
                <div className="empty-msg">No SAFs in the workflow right now.</div>
              </div>
            ) : (
              <table className="data">
                <tbody>
                  {openSAFs.slice(0, 4).map(s => {
                    const stMap = {
                      submitted: { label: 'Awaiting Stoney', kind: 'warning' },
                      'stoney-signed': { label: 'Awaiting Val', kind: 'gold' },
                      'val-confirmed': { label: 'Posting', kind: 'gold' },
                      returned: { label: 'Returned', kind: 'danger' },
                    };
                    const st = stMap[s.status] || { label: s.status, kind: 'neutral' };
                    return (
                      <tr key={s.id}>
                        <td>
                          <div style={{ fontWeight: 600 }}>{s.vendor?.name || s.desc}</div>
                          <div className="dim" style={{ fontSize: 11 }}>{s.category} \u00b7 {s.officer?.name}</div>
                        </td>
                        <td><span className={`badge ${st.kind} dot`}>{st.label}</span></td>
                        <td className="cell-mono" style={{ textAlign: 'right', fontWeight: 600 }}>
                          ${s.amount.toLocaleString()}
                        </td>
                      </tr>
                    );
                  })}
                </tbody>
              </table>
            )}
          </div>
        </div>

        {/* Right column: people + recent activity */}
        <div className="flex-col" style={{ gap: 16 }}>
          {/* Primary contact */}
          <div className="card card-pad">
            <div className="section-title" style={{ margin: '0 0 10px' }}>Primary contact</div>
            {primary && (
              <div className="flex-gap-12">
                <span className="eboard-avatar" style={{ width: 40, height: 40, fontSize: 13, background: 'rgba(200,151,58,0.15)', color: 'var(--gold)', borderColor: 'var(--gold-soft)' }}>
                  {primary.name.split(' ').map(p => p[0]).slice(0, 2).join('')}
                </span>
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 600 }}>{primary.name}</div>
                  <div className="dim" style={{ fontSize: 12 }}>{primary.position} \u00b7 {primary.email}</div>
                </div>
                <button className="btn btn-ghost btn-sm"><window.I.Mail size={13} /></button>
              </div>
            )}
            <div style={{ borderTop: '1px solid var(--border)', marginTop: 12, paddingTop: 12 }}>
              <div className="section-title" style={{ margin: '0 0 8px' }}>Coach / advisor</div>
              {coach ? (
                <div className="flex-gap-12" style={{ fontSize: 12 }}>
                  <span className="eboard-avatar" style={{ width: 28, height: 28, fontSize: 11 }}>
                    {coach.name.split(' ').slice(-2).map(p => p[0]).slice(0, 2).join('')}
                  </span>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontWeight: 600 }}>{coach.name}</div>
                    <div className="dim">{coach.kind} \u00b7 {coach.volunteer ? 'Volunteer' : 'Paid'}</div>
                  </div>
                </div>
              ) : (
                <div className="dim" style={{ fontSize: 12 }}>None on file</div>
              )}
            </div>
            <div style={{ borderTop: '1px solid var(--border)', marginTop: 12, paddingTop: 12 }}>
              <div className="flex-between" style={{ fontSize: 12 }}>
                <span className="dim">E-board size</span>
                <strong>{board.length}</strong>
              </div>
              <div className="flex-between" style={{ fontSize: 12, marginTop: 4 }}>
                <span className="dim">Roster size</span>
                <strong>{roster.length}</strong>
              </div>
              <div className="flex-between" style={{ fontSize: 12, marginTop: 4 }}>
                <span className="dim">Practice slots booked</span>
                <strong>{myReservations.length}</strong>
              </div>
            </div>
          </div>

          {/* Recent activity */}
          <div className="card">
            <div style={{ padding: '14px 18px', borderBottom: '1px solid var(--border)' }}>
              <strong style={{ fontSize: 13 }}>Recent activity</strong>
            </div>
            <ol style={{ listStyle: 'none', padding: 16, margin: 0, display: 'flex', flexDirection: 'column', gap: 14 }}>
              {recent.length === 0 ? (
                <div className="dim" style={{ fontSize: 12 }}>No recent activity.</div>
              ) : recent.map((it, i) => {
                const Ic = window.I[it.icon] || window.I.FileText;
                return (
                  <li key={i} style={{ display: 'flex', gap: 10, fontSize: 12 }}>
                    <span className={`task-icon ${it.tone}`} style={{ width: 26, height: 26, borderRadius: 5 }}>
                      <Ic size={12} />
                    </span>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontWeight: 500 }}>{it.title}</div>
                      <div className="dim" style={{ fontSize: 11 }}>
                        {it.sub} \u00b7 {window.Fmt.dateTime(it.at)}
                      </div>
                    </div>
                  </li>
                );
              })}
            </ol>
          </div>
        </div>
      </div>
    </div>
  );
}

window.TeamOverviewTab = TeamOverviewTab;
