// account_bar.jsx — Top bar with player/team switcher + cross-team "All Upcoming"

// ─────────────────────────────────────────────────────────────
// AccountBar — persistent top bar (below status bar)
// Shows active player + team, opens a switcher sheet
// ─────────────────────────────────────────────────────────────
function AccountBar({ T, activePlayerId, activeTeamId, onSwitchTo, onOpenInbox }) {
  const [open, setOpen] = React.useState(false);
  const player = ACCOUNT.players.find(p => p.id === activePlayerId) || ACCOUNT.players[0];
  const team = player.teams.find(t => t.id === activeTeamId) || player.teams[0];
  const totalUnread = ACCOUNT.players.flatMap(p => p.teams).reduce((s,t) => s + (t.unread||0), 0);
  const otherUnread = Math.max(0, totalUnread - (team.unread||0));

  return (
    <>
      <div style={{
        padding: '6px 12px 8px', display:'flex', alignItems:'center', gap: 8,
        background: T.bg, borderBottom: `0.5px solid ${T.sep}`, flexShrink: 0,
        position: 'relative', zIndex: 5,
      }}>
        <button onClick={() => setOpen(true)} style={{
          flex: 1, display:'flex', alignItems:'center', gap: 10,
          padding: '6px 10px 6px 6px', borderRadius: 14,
          background: T.fill2, border:'none', cursor:'pointer',
          minWidth: 0, fontFamily: T.font, textAlign:'left',
        }}>
          <div style={{
            width: 36, height: 36, borderRadius: 10,
            background: `linear-gradient(135deg, ${team.accent}, oklch(0.45 0.15 ${(hueFromHex(team.accent)+30)%360}))`,
            display:'flex', alignItems:'center', justifyContent:'center',
            color:'#fff', fontSize: 16, fontWeight: 700, flexShrink: 0,
          }}>{team.emoji}</div>
          <div style={{ minWidth: 0, flex: 1 }}>
            <div style={{ display:'flex', alignItems:'center', gap: 4 }}>
              <span style={{ color: T.label, fontWeight: 700, fontSize: 14, letterSpacing: -0.2,
                whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>{team.name}</span>
              <Icon name="chevron-down" size={14} color={T.label2} weight={2.5} />
            </div>
            <div style={{ display:'flex', alignItems:'center', gap: 5, marginTop: 1 }}>
              <Avatar initials={player.initials} hue={player.hue} size={14} />
              <span style={{ color: T.label2, fontSize: 11.5, fontWeight: 500,
                whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis' }}>
                {player.name} · {team.level}
              </span>
            </div>
          </div>
        </button>

        <button onClick={onOpenInbox} style={{
          width: 38, height: 38, borderRadius: 12, border:'none',
          background: T.fill2, cursor:'pointer', position:'relative',
          display:'flex', alignItems:'center', justifyContent:'center', flexShrink: 0,
        }} title="All upcoming across teams">
          <Icon name="calendar" size={19} color={T.label} weight={1.9} />
          {otherUnread > 0 && (
            <div style={{
              position:'absolute', top: 3, right: 3, minWidth: 14, height: 14, borderRadius: 7,
              background: T.red, color:'#fff', fontSize: 9, fontWeight: 700,
              display:'flex', alignItems:'center', justifyContent:'center', padding:'0 3px',
              border: `1.5px solid ${T.bg}`,
            }}>{otherUnread}</div>
          )}
        </button>
      </div>

      {open && (
        <SwitcherSheet T={T}
          activePlayerId={activePlayerId} activeTeamId={activeTeamId}
          onClose={() => setOpen(false)}
          onPick={(pid, tid) => { onSwitchTo(pid, tid); setOpen(false); }}
        />
      )}
    </>
  );
}

// ─────────────────────────────────────────────────────────────
// Switcher sheet — grouped by player, showing their teams
// ─────────────────────────────────────────────────────────────
function SwitcherSheet({ T, activePlayerId, activeTeamId, onClose, onPick }) {
  return (
    <div style={{
      position:'absolute', inset: 0, zIndex: 100,
      background:'rgba(0,0,0,0.35)', backdropFilter:'blur(4px)',
      display:'flex', alignItems:'flex-start', justifyContent:'center',
      paddingTop: 12,
    }} onClick={onClose}>
      <div onClick={e => e.stopPropagation()} style={{
        width: 'calc(100% - 16px)', maxHeight:'70%', overflow:'auto',
        background: T.card, borderRadius: 22, padding: 16,
        boxShadow: '0 20px 60px rgba(0,0,0,0.35)',
      }}>
        <div style={{ display:'flex', alignItems:'center', justifyContent:'space-between', marginBottom: 10 }}>
          <div>
            <div style={{ fontSize: 18, fontWeight: 700, color: T.label, letterSpacing: -0.3, fontFamily: T.displayFont }}>Switch</div>
            <div style={{ fontSize: 12, color: T.label2, marginTop: 1 }}>{ACCOUNT.name}'s family · {ACCOUNT.players.length} players</div>
          </div>
          <button onClick={onClose} style={{
            width: 30, height: 30, borderRadius: 15, border:'none', background: T.fill,
            cursor:'pointer', display:'flex', alignItems:'center', justifyContent:'center',
          }}>
            <Icon name="x" size={16} color={T.label} weight={2.4} />
          </button>
        </div>

        {ACCOUNT.players.map(p => (
          <div key={p.id} style={{ marginTop: 10 }}>
            <div style={{ display:'flex', alignItems:'center', gap: 10, padding: '4px 2px 8px' }}>
              <Avatar initials={p.initials} hue={p.hue} size={28} />
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 14, fontWeight: 700, color: T.label }}>{p.name}</div>
                <div style={{ fontSize: 11, color: T.label2 }}>Age {p.age} · {p.teams.length} teams</div>
              </div>
            </div>
            <div style={{ display:'flex', flexDirection:'column', gap: 4 }}>
              {p.teams.map(t => {
                const active = p.id === activePlayerId && t.id === activeTeamId;
                return (
                  <button key={t.id} onClick={() => onPick(p.id, t.id)} style={{
                    display:'flex', alignItems:'center', gap: 12, padding: '8px 10px',
                    borderRadius: 12, border: 'none', cursor:'pointer',
                    background: active ? hexA(t.accent, 0.12) : T.fill2,
                    boxShadow: active ? `inset 0 0 0 1.5px ${t.accent}` : 'none',
                    fontFamily: T.font, textAlign:'left',
                  }}>
                    <div style={{
                      width: 34, height: 34, borderRadius: 10,
                      background:`linear-gradient(135deg, ${t.accent}, oklch(0.45 0.15 ${(hueFromHex(t.accent)+30)%360}))`,
                      color:'#fff', fontWeight: 700, fontSize: 16,
                      display:'flex', alignItems:'center', justifyContent:'center', flexShrink: 0,
                    }}>{t.emoji}</div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 14, fontWeight: 600, color: T.label }}>{t.name}</div>
                      <div style={{ fontSize: 11.5, color: T.label2 }}>{t.sport} · {t.level}</div>
                    </div>
                    {t.unread > 0 && (
                      <div style={{
                        minWidth: 20, height: 20, borderRadius: 10, padding:'0 6px',
                        background: T.red, color:'#fff', fontSize: 11, fontWeight: 700,
                        display:'flex', alignItems:'center', justifyContent:'center',
                      }}>{t.unread}</div>
                    )}
                    {active && <Icon name="check" size={18} color={t.accent} weight={2.8} />}
                  </button>
                );
              })}
            </div>
          </div>
        ))}

        <div style={{ marginTop: 12, paddingTop: 10, borderTop: `0.5px solid ${T.sep}`, display:'flex', gap: 8 }}>
          <button style={{
            flex: 1, padding:'10px', borderRadius: 12, border:'none', cursor:'pointer',
            background: T.fill, color: T.label, fontFamily: T.font, fontSize: 13, fontWeight: 600,
            display:'inline-flex', alignItems:'center', justifyContent:'center', gap: 6,
          }}>
            <Icon name="plus" size={14} color={T.label} weight={2.5} /> Add player
          </button>
          <button style={{
            flex: 1, padding:'10px', borderRadius: 12, border:'none', cursor:'pointer',
            background: T.fill, color: T.label, fontFamily: T.font, fontSize: 13, fontWeight: 600,
            display:'inline-flex', alignItems:'center', justifyContent:'center', gap: 6,
          }}>
            <Icon name="team" size={14} color={T.label} weight={2} /> Join team
          </button>
        </div>
      </div>
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// InboxScreen — Cross-team "All Upcoming" feed
// Groups events by day, color-codes by team, flags conflicts
// ─────────────────────────────────────────────────────────────
function InboxScreen({ T, onBack, onSwitchTo }) {
  const [filter, setFilter] = React.useState('all'); // all | arjun | maya
  const allPlayerIds = ACCOUNT.players.map(p => p.id);
  const events = CROSS_EVENTS.filter(e => filter === 'all' || e.playerId === filter);

  // Group by dayKey
  const groups = {};
  events.forEach(e => { (groups[e.dayKey] = groups[e.dayKey] || []).push(e); });
  const dayKeys = Object.keys(groups).map(Number).sort((a,b)=>a-b);

  // Conflict detection: same dayKey + overlapping times approx
  const conflicts = {};
  dayKeys.forEach(k => {
    if (groups[k].length > 1) {
      // mark any pair with adjacent playerId differences? here we just flag if >1
      groups[k].forEach(e => {
        if (groups[k].some(o => o.playerId === e.playerId && o.id !== e.id)) {
          conflicts[e.id] = true;
        }
      });
    }
  });

  const counts = {
    games: events.filter(e => e.type === 'game').length,
    practices: events.filter(e => e.type === 'practice').length,
    social: events.filter(e => e.type === 'social').length,
  };

  return (
    <div style={{ paddingBottom: 40 }}>
      <ScreenHeader T={T} title="All Upcoming" subtitle={`Across ${ACCOUNT.players.length} players · ${ACCOUNT.players.flatMap(p=>p.teams).length} teams`} onBack={onBack} />

      {/* Filter chips: everyone + one per player */}
      <div style={{ padding:'8px 16px 0', display:'flex', gap: 8, overflowX:'auto' }}>
        <FilterChip T={T} active={filter==='all'} onClick={()=>setFilter('all')} label="Everyone" />
        {ACCOUNT.players.map(p => (
          <FilterChip key={p.id} T={T} active={filter===p.id} onClick={()=>setFilter(p.id)}
            label={p.name.split(' ')[0]} avatar={<Avatar initials={p.initials} hue={p.hue} size={18} />} />
        ))}
      </div>

      {/* Summary stats */}
      <div style={{ padding:'12px 16px 0', display:'flex', gap: 10 }}>
        <StatTile T={T} label="Next 10d" value={events.length} sub="events" icon="calendar" />
        <StatTile T={T} label="Games" value={counts.games} sub="incl. meets" icon="soccer" tint={T.accent} />
        <StatTile T={T} label="Practices" value={counts.practices} sub="weekly" icon="whistle" />
      </div>

      {/* Conflict banner */}
      {Object.keys(conflicts).length > 0 && (
        <div style={{ padding:'14px 16px 0' }}>
          <div style={{
            padding: 12, borderRadius: 14,
            background: hexA(T.yellow, 0.14),
            border: `0.5px solid ${hexA(T.yellow, 0.35)}`,
            display:'flex', gap: 10, alignItems:'center',
          }}>
            <div style={{ fontSize: 22 }}>⚠️</div>
            <div style={{ flex: 1 }}>
              <div style={{ fontSize: 13, fontWeight: 700, color: T.label }}>Schedule conflicts flagged</div>
              <div style={{ fontSize: 12, color: T.label2, marginTop: 1 }}>Arjun has overlapping events Fri Apr 24.</div>
            </div>
          </div>
        </div>
      )}

      {/* Grouped list */}
      <div style={{ padding:'14px 16px 0' }}>
        {dayKeys.map(k => {
          const sample = groups[k][0];
          return (
            <div key={k} style={{ marginBottom: 14 }}>
              <div style={{
                display:'flex', alignItems:'baseline', justifyContent:'space-between',
                padding:'0 4px 6px',
              }}>
                <div>
                  <div style={{ fontSize: 11, fontWeight: 700, color: T.label2, textTransform:'uppercase', letterSpacing: 0.5 }}>
                    {sample.date.split(' ')[0]}
                  </div>
                  <div style={{ fontSize: 18, fontWeight: 700, color: T.label, letterSpacing: -0.3, fontFamily: T.displayFont }}>
                    {sample.date.replace(/^\w+\s/, '')}
                  </div>
                </div>
                <span style={{ fontSize: 12, color: T.label2 }}>{groups[k].length} event{groups[k].length>1?'s':''}</span>
              </div>

              <div style={{ background: T.card, borderRadius: T.listRadius, overflow:'hidden' }}>
                {groups[k].map((e, i, a) => (
                  <CrossEventRow key={e.id} T={T} e={e} isLast={i === a.length-1}
                    hasConflict={conflicts[e.id]} onClick={() => onSwitchTo(e.playerId, e.teamId, 'event')} />
                ))}
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

function FilterChip({ T, active, onClick, label, avatar }) {
  return (
    <button onClick={onClick} style={{
      padding: avatar ? '5px 12px 5px 5px' : '7px 14px', borderRadius: 15, border:'none',
      background: active ? T.label : T.fill,
      color: active ? T.bg : T.label, cursor:'pointer',
      fontSize: 13, fontWeight: 600, fontFamily: T.font, whiteSpace:'nowrap',
      display:'inline-flex', alignItems:'center', gap: 6,
    }}>
      {avatar}{label}
    </button>
  );
}

function CrossEventRow({ T, e, isLast, hasConflict, onClick }) {
  return (
    <div onClick={onClick} style={{
      display:'flex', alignItems:'center', gap: 12, padding:'12px 14px',
      borderBottom: isLast ? 'none' : `0.5px solid ${T.sep}`,
      cursor:'pointer', position:'relative',
    }}>
      {/* color stripe for team */}
      <div style={{
        position:'absolute', left: 0, top: 8, bottom: 8,
        width: 3, borderRadius: '0 2px 2px 0', background: e.teamAccent,
      }}/>
      {/* event type icon */}
      <div style={{
        width: 40, height: 40, borderRadius: 12,
        background: hexA(e.teamAccent, 0.14),
        display:'flex', alignItems:'center', justifyContent:'center', flexShrink: 0,
      }}>
        <Icon name={e.type === 'game' ? 'soccer' : e.type === 'social' ? 'star' : 'whistle'} size={20} color={e.teamAccent} weight={2.2} />
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ display:'flex', alignItems:'center', gap: 6 }}>
          <span style={{ color: T.label, fontWeight: 600, fontSize: 15, letterSpacing: -0.2 }}>{e.title}</span>
          {hasConflict && (
            <span style={{
              padding:'1px 6px', borderRadius: 6,
              background: hexA(T.yellow, 0.2), color: '#8a6b00',
              fontSize: 10, fontWeight: 700, textTransform:'uppercase', letterSpacing: 0.3,
            }}>⚠ Conflict</span>
          )}
        </div>
        <div style={{ display:'flex', alignItems:'center', gap: 6, marginTop: 2, fontSize: 12, color: T.label2, flexWrap:'wrap' }}>
          <span style={{
            padding:'1px 6px', borderRadius: 5,
            background: hexA(e.teamAccent, 0.12), color: e.teamAccent,
            fontSize: 10.5, fontWeight: 700,
          }}>{e.playerName}</span>
          <span>{e.teamName}</span>
          <span>·</span>
          <span>{e.time}</span>
          <span>·</span>
          <span>{e.loc}</span>
        </div>
      </div>
      {e.rsvp && <RsvpBadge T={T} status={e.rsvp} />}
    </div>
  );
}

Object.assign(window, { AccountBar, SwitcherSheet, InboxScreen, CrossEventRow, FilterChip });
