/* Admin → Settings → Roles & Access (full RBAC view) */
const JL_ROLES = [
  { id:'super',   name:'Super Admin', scope:'District-wide', initials:'DR', color:'gold',  count:3 },
  { id:'admin',   name:'School Admin', scope:'Single school', initials:'SA', color:'navy',  count:12 },
  { id:'teacher', name:'Teacher',      scope:'Own classes',   initials:'MJ', color:'blue',  count:86 },
  { id:'driver',  name:'Driver',       scope:'Assigned route', initials:'MT', color:'green', count:25 },
  { id:'parent',  name:'Parent',       scope:'Own children',  initials:'JH', color:'cyan',  count:1248 },
  { id:'student', name:'Student',      scope:'Own profile',   initials:'EJ', color:'red',   count:1248 },
];

/* access level per capability per role: 'full' | 'own' | 'none' */
const JL_CAPS = [
  { cap:'View student records', icon:'users',          a:{ super:'full', admin:'full', teacher:'own',  driver:'own',  parent:'own',  student:'own'  } },
  { cap:'Live bus tracking',     icon:'bus',            a:{ super:'full', admin:'full', teacher:'none', driver:'own',  parent:'own',  student:'own'  } },
  { cap:'Message families',      icon:'message-circle', a:{ super:'full', admin:'full', teacher:'full', driver:'none', parent:'full', student:'none' } },
  { cap:'Pickup & dismissal',    icon:'car-front',      a:{ super:'full', admin:'full', teacher:'own',  driver:'own',  parent:'own',  student:'own'  } },
  { cap:'Process payments',      icon:'credit-card',    a:{ super:'full', admin:'full', teacher:'none', driver:'none', parent:'own',  student:'none' } },
  { cap:'Reports & analytics',   icon:'bar-chart-3',    a:{ super:'full', admin:'own',  teacher:'own',  driver:'none', parent:'none', student:'none' } },
  { cap:'Manage roles & settings', icon:'settings',     a:{ super:'full', admin:'own',  teacher:'none', driver:'none', parent:'none', student:'none' } },
];

function AccessCell({ level }) {
  const map = {
    full: { icon:'check', bg:'var(--success-100)', fg:'var(--success-600)', label:'Full' },
    own:  { icon:'user',  bg:'var(--warning-100)', fg:'var(--warning-600)', label:'Own data' },
    none: { icon:'minus', bg:'var(--gray-100)',    fg:'var(--gray-400)',    label:'None' },
  };
  const m = map[level];
  return (
    <span title={m.label} style={{ display:'inline-flex', alignItems:'center', justifyContent:'center', width:26, height:26, borderRadius:8, background:m.bg }}>
      <Icon name={m.icon} size={14} color={m.fg} stroke={2.6} />
    </span>
  );
}

function RolesAccess() {
  const [active, setActive] = React.useState('admin');
  const [caps, setCaps] = React.useState(JL_CAPS);
  const [dirty, setDirty] = React.useState(false);
  const cycle = (capIndex, roleId) => {
    const nextLevel = { full:'own', own:'none', none:'full' };
    setCaps(cs => cs.map((row,i)=> i===capIndex ? { ...row, a:{ ...row.a, [roleId]: nextLevel[row.a[roleId]] } } : row));
    setDirty(true);
  };
  const fmt = n => n >= 1000 ? (n/1000).toFixed(n%1000?1:0)+'k' : ''+n;
  return (
    <div style={{ display:'flex', flexDirection:'column', gap:16 }}>
      {/* role cards */}
      <Panel title="Roles" action={<button onClick={()=>jlToast('New custom role', { icon:'plus' })} style={{ display:'flex', alignItems:'center', gap:6, background:'var(--navy-600)', color:'#fff', border:0, borderRadius:9, padding:'8px 13px', fontWeight:700, fontSize:12.5, cursor:'pointer', fontFamily:'var(--font-sans)' }}><Icon name="plus" size={14} color="#fff" />Add Role</button>}>
        <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:12, padding:'4px 0 2px' }}>
          {JL_ROLES.map(r => {
            const on = active===r.id;
            return (
              <button key={r.id} onClick={()=>setActive(r.id)} style={{ textAlign:'left', display:'flex', alignItems:'center', gap:11, padding:'13px 14px', borderRadius:12, cursor:'pointer', fontFamily:'var(--font-sans)', background: on?'var(--blue-100)':'#fff', border: on?'1.5px solid var(--blue-500)':'1px solid var(--gray-200)' }}>
                <Avatar initials={r.initials} color={r.color} size={38} />
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ fontSize:14, fontWeight:700, color:'var(--ink)' }}>{r.name}</div>
                  <div style={{ fontSize:12, color:'var(--gray-500)' }}>{r.scope}</div>
                </div>
                <div style={{ textAlign:'right' }}>
                  <div style={{ fontSize:15, fontWeight:800, color:'var(--ink)', letterSpacing:'-.01em' }}>{fmt(r.count)}</div>
                  <div style={{ fontSize:10.5, color:'var(--gray-400)', fontWeight:600 }}>members</div>
                </div>
              </button>
            );
          })}
        </div>
      </Panel>

      {/* permissions matrix */}
      <Panel title="Permission Matrix" action={<span style={{ display:'inline-flex', gap:14, alignItems:'center' }}>
        {dirty && <button onClick={()=>{ setDirty(false); jlToast('Permissions saved · applied to all members', { icon:'shield-check' }); }} style={{ display:'flex', alignItems:'center', gap:6, background:'var(--gold-400)', color:'var(--on-gold)', border:0, borderRadius:9, padding:'8px 13px', fontWeight:700, fontSize:12.5, cursor:'pointer', fontFamily:'var(--font-sans)', boxShadow:'var(--shadow-gold)' }}><Icon name="save" size={14} color="var(--on-gold)" />Save Changes</button>}
        <Legend level="full" label="Full" /><Legend level="own" label="Own data" /><Legend level="none" label="No access" />
      </span>} pad={false}>
        <div style={{ overflowX:'auto' }}>
          <div style={{ minWidth:680 }}>
            {/* header */}
            <div style={{ display:'grid', gridTemplateColumns:'1.6fr repeat(6, 1fr)', alignItems:'center', padding:'11px 18px', background:'var(--gray-50)', borderBottom:'1px solid var(--gray-200)' }}>
              <span style={{ fontSize:11, fontWeight:800, letterSpacing:'.05em', textTransform:'uppercase', color:'var(--gray-500)' }}>Capability</span>
              {JL_ROLES.map(r => (
                <span key={r.id} style={{ justifySelf:'center', textAlign:'center', fontSize:11, fontWeight:700, color: active===r.id?'var(--blue-600)':'var(--gray-600)' }}>{r.name.replace(' Admin',' Adm.')}</span>
              ))}
            </div>
            {/* rows */}
            {caps.map((row, i) => (
              <div key={row.cap} style={{ display:'grid', gridTemplateColumns:'1.6fr repeat(6, 1fr)', alignItems:'center', padding:'11px 18px', borderTop: i>0?'1px solid var(--gray-100)':'0' }}>
                <span style={{ display:'flex', alignItems:'center', gap:9 }}>
                  <Icon name={row.icon} size={16} color="var(--gray-500)" />
                  <span style={{ fontSize:13, fontWeight:600, color:'var(--ink)' }}>{row.cap}</span>
                </span>
                {JL_ROLES.map(r => (
                  <button key={r.id} onClick={()=>cycle(i, r.id)} title="Click to change access" style={{ justifySelf:'center', padding:'2px 4px', borderRadius:8, border:0, cursor:'pointer', background: active===r.id?'rgba(42,105,188,.06)':'transparent' }}><AccessCell level={row.a[r.id]} /></button>
                ))}
              </div>
            ))}
          </div>
        </div>
      </Panel>

      {/* data-scope note */}
      <div style={{ display:'flex', alignItems:'flex-start', gap:11, background:'var(--blue-100)', borderRadius:12, padding:'14px 16px' }}>
        <Icon name="shield-check" size={18} color="var(--blue-600)" />
        <div style={{ fontSize:12.5, color:'var(--blue-700)', lineHeight:1.5 }}>
          <strong>Row-level security is enforced everywhere.</strong> “Own data” means a teacher sees only their class, a parent only their children, a driver only their route, and a student only their own profile — never another family's information. Tap any cell above to adjust a role's access.
        </div>
      </div>
    </div>
  );
}

function Legend({ level, label }) {
  return (
    <span style={{ display:'inline-flex', alignItems:'center', gap:5, fontSize:11.5, fontWeight:600, color:'var(--gray-600)' }}>
      <AccessCell level={level} />{label}
    </span>
  );
}

Object.assign(window, { RolesAccess, JL_ROLES, JL_CAPS });
