// screens-membership.jsx — membership-based identity switcher
// A user's identity in the app = (team × role) = one membership.
// Same team + multiple roles (Anitha: Teacher AND Parent at DPS)
// Same role + multiple teams (Suresh: Parent at DPS for Aarav, at GIIS for Diya)
// Same person + history (Anand: Student at old school + Student at new school)

const MEMBERSHIPS = [
  // Aarav — single-role student
  { id:'m0', teamId:'dps', team:'DPS Hyderabad', kind:'School · CBSE', glyph:'🏫', bg:'var(--p50)', clr:'var(--p600)',
    role:'Student', context:'Class 8-B · Roll 14', badge:4, roleType:'student', state:'active' },
  // Anitha — same team, two roles
  { id:'m1', teamId:'dps', team:'DPS Hyderabad', kind:'School · CBSE', glyph:'🏫', bg:'var(--p50)', clr:'var(--p600)',
    role:'Class teacher', context:'Class 5-A · Mathematics', badge:12, roleType:'teacher', state:'active', primary:true },
  { id:'m2', teamId:'dps', team:'DPS Hyderabad', kind:'School · CBSE', glyph:'🏫', bg:'var(--p50)', clr:'var(--p600)',
    role:'Parent', context:"Maya R. · Class 2-B", badge:3, roleType:'parent', state:'active' },

  // Same person, different teams
  { id:'m3', teamId:'sai', team:'Sai Travels', kind:'Transport provider', glyph:'🚌', bg:'#FFF7ED', clr:'#9A3412',
    role:'Owner', context:'14 buses · 4 schools', badge:5, roleType:'admin', state:'active' },

  // Suresh-style — parent at two schools (different children)
  { id:'m4', teamId:'giis', team:'GIIS Pune', kind:'School · IB', glyph:'🏫', bg:'var(--c50)', clr:'var(--c600)',
    role:'Parent', context:'Diya R. · Class 5-A', badge:2, roleType:'parent', state:'active' },
  { id:'m5', teamId:'aakash', team:'Aakash Tuitions', kind:'Coaching · NEET', glyph:'📚', bg:'var(--success-50)', clr:'var(--success)',
    role:'Parent', context:'Maya R. · Maths batch', badge:0, roleType:'parent', state:'active' },

  // Driver / transport scenarios
  { id:'m8', teamId:'sai', team:'Sai Travels', kind:'Transport provider', glyph:'🚌', bg:'var(--info-50)', clr:'#1E40AF',
    role:'Bus driver', context:'Route 14 · KA-05-MK-1247 · 38 students', badge:2, roleType:'driver', state:'active' },
  { id:'m9', teamId:'giis-fleet', team:'GIIS in-house fleet', kind:'School transport', glyph:'🚐', bg:'var(--info-50)', clr:'#1E40AF',
    role:'Bus driver', context:'Route 7 · MH-12-AB-3380 · 24 students', badge:0, roleType:'driver', state:'active' },
  { id:'m10', teamId:'sai', team:'Sai Travels', kind:'Transport provider', glyph:'🚌', bg:'#FFF7ED', clr:'#9A3412',
    role:'Fleet supervisor', context:'5 routes · 142 students · DPS contract', badge:1, roleType:'admin', state:'active' },

  // Archived / former
  { id:'m6', teamId:'oak', team:'Oakridge International', kind:'School · IB', glyph:'🏫', bg:'var(--n100)', clr:'var(--n500)',
    role:'Class teacher', context:'2021 – 2024 · 3 yrs', roleType:'teacher', state:'former',
    endNote:'Resigned in 2024 · records available' },
  { id:'m7', teamId:'vid', team:'Vidyaranya High', kind:'School · State board', glyph:'🏫', bg:'var(--n100)', clr:'var(--n500)',
    role:'Student', context:'2018 – 2021 · alumni', roleType:'student', state:'alumni',
    endNote:'Graduated 2021 · certificates ready' },
];

function roleChipStyle(roleType) {
  const map = {
    teacher: { bg: 'var(--p50)', clr: 'var(--p700)', label: '👩‍🏫 Teacher' },
    parent:  { bg: 'var(--c50)', clr: 'var(--c700)', label: '👨‍👩‍👧 Parent' },
    student: { bg: 'var(--success-50)', clr: '#065F46', label: '🎓 Student' },
    admin:   { bg: '#FFF7ED', clr: '#9A3412', label: '⚙️ Admin' },
    driver:  { bg: 'var(--info-50)', clr: '#1E40AF', label: '🚌 Driver' },
  };
  return map[roleType] || map.parent;
}

// ─────────────────────────────────────────────────────────────
// MEMBERSHIP SWITCHER — replaces TeamSwitcherSheet
// ─────────────────────────────────────────────────────────────
function MembershipSwitcher({ open, onClose, currentId, onPick }) {
  const [tab, setTab] = useStateT('active');
  if (!open) return null;

  const active = MEMBERSHIPS.filter(m => m.state === 'active');
  const archived = MEMBERSHIPS.filter(m => m.state !== 'active');

  // Group active by team — surfaces the same-team-multiple-roles case
  const groups = active.reduce((acc, m) => {
    (acc[m.teamId] = acc[m.teamId] || { team: m, items: [] }).items.push(m);
    return acc;
  }, {});

  const current = MEMBERSHIPS.find(m => m.id === currentId) || MEMBERSHIPS[0];

  return (
    <>
      <div className="sheet-backdrop" onClick={onClose}></div>
      <div className="sheet sheet-up" style={{ maxHeight: '88%' }}>
        <div className="sheet-handle"></div>

        {/* Header with current identity card */}
        <div style={{ padding: '10px 20px 0' }}>
          <div className="spread">
            <div>
              <div style={{ fontSize: 17, fontWeight: 800, color: 'var(--n900)', letterSpacing: '-.01em' }}>Switch identity</div>
              <div style={{ fontSize: 11, color: 'var(--n500)', marginTop: 2 }}>{active.length} active · {archived.length} archived</div>
            </div>
            <button onClick={onClose} style={{ width: 32, height: 32, borderRadius: 10, background: 'var(--n50)', display: 'grid', placeItems: 'center' }}><Icon name="x" size={16}/></button>
          </div>

          {/* Currently active strip */}
          <div className="row" style={{ marginTop: 14, padding: 12, background: 'linear-gradient(135deg,var(--p50),#fff)', borderRadius: 14, border: '1.5px solid var(--p200)', gap: 12 }}>
            <div style={{ width: 40, height: 40, borderRadius: 11, background: current.bg, color: current.clr, display: 'grid', placeItems: 'center', fontSize: 18, flexShrink: 0 }}>{current.glyph}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div className="row" style={{ gap: 6 }}>
                <span style={{ fontSize: 9, color: 'var(--success)', fontWeight: 800, letterSpacing: '.08em', fontFamily: 'var(--mono)' }}>● ACTIVE NOW</span>
              </div>
              <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)', marginTop: 2 }}>{current.team}</div>
              <div className="row" style={{ gap: 6, marginTop: 4 }}>
                <span className="pill" style={{ fontSize: 9, padding: '2px 7px', background: roleChipStyle(current.roleType).bg, color: roleChipStyle(current.roleType).clr, border: 'none' }}>{roleChipStyle(current.roleType).label}</span>
                <span style={{ fontSize: 11, color: 'var(--n600)' }}>{current.context}</span>
              </div>
            </div>
          </div>

          {/* Tabs */}
          <div style={{ marginTop: 16, padding: 4, background: 'var(--n100)', borderRadius: 11, display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 4 }}>
            {[
              { id: 'active', lab: `Active · ${active.length}` },
              { id: 'archived', lab: `Archived · ${archived.length}` },
            ].map(o => (
              <button key={o.id} onClick={() => setTab(o.id)} style={{
                padding: '8px 6px', borderRadius: 8, fontSize: 12, fontWeight: 700,
                background: tab === o.id ? '#fff' : 'transparent',
                color: tab === o.id ? 'var(--n900)' : 'var(--n600)',
                boxShadow: tab === o.id ? '0 1px 3px rgba(0,0,0,.08)' : 'none',
              }}>{o.lab}</button>
            ))}
          </div>
        </div>

        <div style={{ flex: 1, overflowY: 'auto', padding: '14px 20px 16px' }}>
          {tab === 'active' && (
            <>
              {Object.values(groups).map(g => (
                <div key={g.team.teamId} style={{ marginBottom: 16 }}>
                  {/* Team header (only when team has 2+ memberships) */}
                  {g.items.length > 1 && (
                    <div className="row" style={{ gap: 10, marginBottom: 8, padding: '0 4px' }}>
                      <div style={{ width: 28, height: 28, borderRadius: 8, background: g.team.bg, color: g.team.clr, display: 'grid', placeItems: 'center', fontSize: 14, flexShrink: 0 }}>{g.team.glyph}</div>
                      <div style={{ flex: 1, minWidth: 0 }}>
                        <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--n800)' }}>{g.team.team}</div>
                        <div style={{ fontSize: 10, color: 'var(--n500)' }}>{g.items.length} roles · same team</div>
                      </div>
                      <span className="pill" style={{ fontSize: 9, background: 'var(--p50)', color: 'var(--p700)', border: '1px solid var(--p100)' }}>DUAL ROLE</span>
                    </div>
                  )}

                  {/* Membership cards */}
                  <div className="col" style={{ gap: 8 }}>
                    {g.items.map(m => {
                      const rs = roleChipStyle(m.roleType);
                      const isCurrent = m.id === currentId;
                      return (
                        <button key={m.id} onClick={() => onPick(m)} className="row" style={{
                          width: '100%', padding: 12, gap: 12, borderRadius: 12,
                          background: isCurrent ? 'var(--p50)' : '#fff',
                          border: isCurrent ? '1.5px solid var(--p400)' : '1.5px solid var(--n100)',
                          textAlign: 'left',
                          marginLeft: g.items.length > 1 ? 8 : 0,
                          position: 'relative',
                        }}>
                          {/* Indent rail when grouped */}
                          {g.items.length > 1 && <div style={{ position: 'absolute', left: -8, top: 18, width: 14, height: 1, background: 'var(--n200)' }}></div>}

                          <div style={{ width: 38, height: 38, borderRadius: 10, background: rs.bg, color: rs.clr, display: 'grid', placeItems: 'center', flexShrink: 0, fontSize: 15 }}>{rs.label.split(' ')[0]}</div>
                          <div style={{ flex: 1, minWidth: 0 }}>
                            <div className="spread">
                              <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>{m.role}{g.items.length === 1 ? ` · ${m.team}` : ''}</div>
                              {isCurrent
                                ? <span className="pill pill-p" style={{ fontSize: 9 }}>CURRENT</span>
                                : (m.badge > 0 && <span style={{ minWidth: 18, height: 18, padding: '0 5px', borderRadius: 99, background: 'var(--c500)', color: '#fff', fontSize: 10, fontWeight: 800, display: 'grid', placeItems: 'center' }}>{m.badge}</span>)
                              }
                            </div>
                            <div style={{ fontSize: 11, color: 'var(--n500)', marginTop: 2 }}>{m.context}{g.items.length === 1 && ` · ${m.kind}`}</div>
                          </div>
                          {!isCurrent && <Icon name="chev-r" size={14} style={{ color: 'var(--n400)' }}/>}
                        </button>
                      );
                    })}
                  </div>
                </div>
              ))}

              <button className="card-flat row" style={{ width: '100%', padding: 14, gap: 12, marginTop: 4, textAlign: 'left', borderStyle: 'dashed' }}>
                <div style={{ width: 40, height: 40, borderRadius: 11, background: '#fff', color: 'var(--p600)', display: 'grid', placeItems: 'center', border: '1px dashed var(--p300)' }}><Icon name="plus" size={20}/></div>
                <div style={{ flex: 1 }}>
                  <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n900)' }}>Add another team or role</div>
                  <div style={{ fontSize: 11, color: 'var(--n500)' }}>Use invitation code or QR from your school</div>
                </div>
                <Icon name="chev-r" size={16} style={{ color: 'var(--n400)' }}/>
              </button>
            </>
          )}

          {tab === 'archived' && (
            <>
              <div style={{ fontSize: 11, color: 'var(--n500)', marginBottom: 12, padding: '0 4px', lineHeight: 1.5 }}>Past memberships kept read-only. You can download records and certificates anytime.</div>
              <div className="col" style={{ gap: 8 }}>
                {archived.map(m => (
                  <div key={m.id} className="row" style={{
                    padding: 12, gap: 12, borderRadius: 12, background: 'var(--n50)', border: '1.5px solid var(--n100)',
                  }}>
                    <div style={{ width: 38, height: 38, borderRadius: 10, background: '#fff', color: 'var(--n400)', display: 'grid', placeItems: 'center', flexShrink: 0, fontSize: 15, border: '1px dashed var(--n200)' }}>{m.glyph}</div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div className="spread">
                        <div style={{ fontSize: 13, fontWeight: 700, color: 'var(--n700)' }}>{m.role} · {m.team}</div>
                        <span className="pill" style={{ fontSize: 9, background: '#fff', color: 'var(--n500)', border: '1px solid var(--n200)' }}>{m.state.toUpperCase()}</span>
                      </div>
                      <div style={{ fontSize: 11, color: 'var(--n500)', marginTop: 2 }}>{m.context}</div>
                      <div style={{ fontSize: 10, color: 'var(--n400)', marginTop: 4, fontStyle: 'italic' }}>{m.endNote}</div>
                      <div className="row" style={{ gap: 6, marginTop: 8 }}>
                        <button className="btn-sm btn-ghost" style={{ height: 26, padding: '0 10px', fontSize: 10, background: '#fff', borderRadius: 7 }}><Icon name="down" size={11}/> Records</button>
                        <button className="btn-sm btn-ghost" style={{ height: 26, padding: '0 10px', fontSize: 10, background: '#fff', borderRadius: 7 }}><Icon name="clipboard" size={11}/> Certificates</button>
                      </div>
                    </div>
                  </div>
                ))}
              </div>
            </>
          )}
        </div>

        {/* Footer with security note */}
        <div className="row" style={{ padding: '10px 20px', borderTop: '1px solid var(--n100)', gap: 10, background: 'var(--n50)' }}>
          <Icon name="shield" size={14} style={{ color: 'var(--success)' }}/>
          <div style={{ fontSize: 10.5, color: 'var(--n600)', flex: 1, lineHeight: 1.4 }}>Each identity has its own permissions. Switching never mixes data across roles.</div>
        </div>
      </div>
    </>
  );
}

// Minimal team header that pulls from a membership object
function MembershipHeader({ membership, onSwitch, onSearch, onNotif, badge = 0 }) {
  const rs = roleChipStyle(membership.roleType);
  return (
    <div className="row" style={{ padding: '8px 16px 10px', gap: 8 }}>
      <button onClick={onSwitch} className="row" style={{
        flex: 1, gap: 10, padding: '8px 10px 8px 8px', background: '#fff', border: '1px solid var(--n100)', borderRadius: 14, minWidth: 0,
      }}>
        <div style={{ position: 'relative', flexShrink: 0 }}>
          <div style={{ width: 34, height: 34, borderRadius: 9, background: membership.bg, color: membership.clr, display: 'grid', placeItems: 'center', fontSize: 15, fontWeight: 800 }}>{membership.glyph}</div>
          {/* Role dot — sits over team glyph to show identity */}
          <div title={membership.role} style={{ position: 'absolute', bottom: -3, right: -3, width: 16, height: 16, borderRadius: 99, background: rs.clr, color: '#fff', display: 'grid', placeItems: 'center', fontSize: 8, border: '2px solid #fff' }}>{rs.label.split(' ')[0]}</div>
        </div>
        <div style={{ flex: 1, minWidth: 0, textAlign: 'left' }}>
          <div className="row" style={{ gap: 6 }}>
            <div style={{ fontSize: 12, fontWeight: 700, color: 'var(--n900)', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', flex: 1, minWidth: 0 }}>{membership.team}</div>
          </div>
          <div className="row" style={{ gap: 4, marginTop: 1 }}>
            <span style={{ fontSize: 10, fontWeight: 700, color: rs.clr, letterSpacing: '.02em' }}>{membership.role}</span>
            <span style={{ fontSize: 10, color: 'var(--n400)' }}>·</span>
            <span style={{ fontSize: 10, color: 'var(--n500)', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{membership.context}</span>
          </div>
        </div>
        <Icon name="down" size={14} style={{ color: 'var(--n500)', flexShrink: 0 }}/>
      </button>
      <button onClick={onSearch} style={{ width: 38, height: 38, borderRadius: 11, background: 'var(--n50)', display: 'grid', placeItems: 'center' }}><Icon name="search" size={18}/></button>
      <button onClick={onNotif} style={{ width: 38, height: 38, borderRadius: 11, background: 'var(--n50)', display: 'grid', placeItems: 'center', position: 'relative' }}>
        <Icon name="bell" size={18}/>
        {badge > 0 && <span style={{ position: 'absolute', top: 4, right: 4, minWidth: 14, height: 14, padding: '0 3px', borderRadius: 99, background: 'var(--c500)', color: '#fff', fontSize: 9, fontWeight: 800, display: 'grid', placeItems: 'center' }}>{badge}</span>}
      </button>
    </div>
  );
}

window.MEMBERSHIPS = MEMBERSHIPS;
window.MembershipSwitcher = MembershipSwitcher;
window.MembershipHeader = MembershipHeader;
window.roleChipStyle = roleChipStyle;

// ─────────────────────────────────────────────────────────────
// MembershipChip — compact identity pill for hero/profile entry points
// variant: 'dark' (over gradient hero) | 'light' (on white surfaces)
// ─────────────────────────────────────────────────────────────
function MembershipChip({ membership, onTap, variant = 'dark', compact = false }) {
  if (!membership) return null;
  const dark = variant === 'dark';
  const rs = roleChipStyle(membership.roleType);
  return (
    <button onClick={onTap} className="row" style={{
      padding: compact ? '6px 10px 6px 6px' : '8px 12px 8px 8px',
      background: dark ? 'rgba(255,255,255,.16)' : '#fff',
      border: dark ? '1px solid rgba(255,255,255,.22)' : '1px solid var(--n100)',
      backdropFilter: dark ? 'blur(10px)' : 'none',
      borderRadius: 99, gap: 8, color: dark ? '#fff' : 'var(--n900)',
      maxWidth: '100%', minWidth: 0,
      boxShadow: dark ? 'none' : '0 1px 2px rgba(0,0,0,.04)',
    }}>
      <div style={{ position: 'relative', flexShrink: 0 }}>
        <div style={{
          width: compact ? 22 : 26, height: compact ? 22 : 26, borderRadius: 99,
          background: dark ? 'rgba(255,255,255,.22)' : membership.bg,
          color: dark ? '#fff' : membership.clr,
          display: 'grid', placeItems: 'center', fontSize: compact ? 11 : 13,
        }}>{membership.glyph}</div>
        <div style={{
          position: 'absolute', bottom: -2, right: -2,
          width: compact ? 11 : 12, height: compact ? 11 : 12, borderRadius: 99,
          background: rs.clr, border: `2px solid ${dark ? '#4F46E5' : '#fff'}`,
        }}></div>
      </div>
      <div style={{ minWidth: 0, textAlign: 'left' }}>
        <div style={{
          fontSize: compact ? 11 : 12, fontWeight: 700, lineHeight: 1.1,
          whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: 130,
        }}>{membership.role}</div>
        <div style={{
          fontSize: 9.5, opacity: dark ? .8 : .6, lineHeight: 1.2, marginTop: 1,
          whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: 130,
          color: dark ? '#fff' : 'var(--n500)',
        }}>{membership.team}</div>
      </div>
      <Icon name="down" size={12} style={{ opacity: .8, flexShrink: 0 }}/>
    </button>
  );
}

window.MembershipChip = MembershipChip;
