// Roles & permissions
const ROLES = [
  { name: 'Operator', desc: 'Floor-level machine operation and form submission', count: 412, color: '#16a34a' },
  { name: 'Shift supervisor', desc: 'Shift coordination, escalation handling', count: 38, color: '#2563eb' },
  { name: 'Maintenance', desc: 'Maintenance work orders and machine intervention', count: 42, color: '#d97706' },
  { name: 'QA inspector', desc: 'Quality forms, dispositions, CAPA', count: 24, color: '#7c3aed' },
  { name: 'Plant manager', desc: 'Plant-wide operational oversight', count: 6, color: '#dc2626' },
  { name: 'Plant head', desc: 'Plant performance, P&L responsibility', count: 6, color: '#dc2626' },
  { name: 'Corporate admin', desc: 'Cross-plant configuration & reporting', count: 8, color: '#1a1a17' },
  { name: 'Auditor (read-only)', desc: 'Audit trail access, no write access', count: 4, color: '#595955' },
];

const MODULE_NAMES = ['Operations', 'Machines', 'Events', 'Workflows', 'Forms', 'Quality', 'Maintenance', 'Planning', 'Inventory', 'Analytics', 'Modules', 'Plants', 'Roles'];
const PERMS = ['view', 'edit', 'approve', 'configure'];

const PERM_MATRIX = {
  'Operator':           [['view'], ['view'], ['view'], [], ['view','edit'], ['view','edit'], [], [], [], [], [], [], []],
  'Shift supervisor':   [['view','edit'], ['view','edit'], ['view','edit','approve'], [], ['view','edit','approve'], ['view','edit','approve'], ['view','edit'], ['view'], ['view'], ['view'], [], [], []],
  'Maintenance':        [['view'], ['view','edit'], ['view','edit','approve'], [], ['view','edit'], ['view'], ['view','edit','approve','configure'], [], ['view','edit'], ['view'], [], [], []],
  'QA inspector':       [['view'], ['view'], ['view','edit'], [], ['view','edit'], ['view','edit','approve','configure'], ['view'], [], ['view','edit'], ['view'], [], [], []],
  'Plant manager':      [['view','edit'], ['view','edit','configure'], ['view','edit','approve','configure'], ['view','edit','configure'], ['view','edit','configure'], ['view','edit','approve','configure'], ['view','edit','approve','configure'], ['view','edit','approve','configure'], ['view','edit'], ['view','edit'], ['view'], ['view'], ['view']],
  'Plant head':         [['view'], ['view'], ['view','approve'], ['view','approve'], ['view','approve'], ['view','approve'], ['view','approve'], ['view','approve'], ['view'], ['view','edit','configure'], ['view'], ['view'], ['view']],
  'Corporate admin':    [['view'], ['view'], ['view'], ['view','edit','configure'], ['view','edit','configure'], ['view','edit','configure'], ['view','edit','configure'], ['view','edit','configure'], ['view','edit','configure'], ['view','edit','configure'], ['view','edit','configure'], ['view','edit','configure'], ['view','edit','configure']],
  'Auditor (read-only)':[['view'], ['view'], ['view'], ['view'], ['view'], ['view'], ['view'], ['view'], ['view'], ['view'], ['view'], ['view'], ['view']],
};

const RolesPage = () => {
  const [tab, setTab] = useState('roles');
  const [selectedRole, setSelectedRole] = useState('Maintenance');
  return (
    <>
      <div className="page-header">
        <div>
          <h1 className="page-title">Roles & Access</h1>
          <div className="page-sub">8 roles · 540 users · 13 modules under access control · Azure AD synced</div>
        </div>
        <div className="page-actions">
          <button className="btn"><Icon name="download" size={12}/>Audit log</button>
          <button className="btn"><Icon name="upload" size={12}/>Sync users</button>
          <button className="btn primary"><Icon name="plus" size={12}/>New role</button>
        </div>
      </div>

      <div className="tabs">
        <div className={`tab ${tab==='roles'?'active':''}`} onClick={()=>setTab('roles')}>Roles <span className="count">8</span></div>
        <div className={`tab ${tab==='matrix'?'active':''}`} onClick={()=>setTab('matrix')}>Permissions matrix</div>
        <div className={`tab ${tab==='users'?'active':''}`} onClick={()=>setTab('users')}>Users <span className="count">540</span></div>
        <div className={`tab ${tab==='approvals'?'active':''}`} onClick={()=>setTab('approvals')}>Approval chains</div>
      </div>

      <div className="page-body">
        {tab === 'roles' && (
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 380px', gap: 12 }}>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10 }}>
              {ROLES.map(r => (
                <div key={r.name} className="card" style={{ cursor: 'pointer', borderColor: selectedRole === r.name ? 'var(--accent)' : 'var(--line)' }} onClick={()=>setSelectedRole(r.name)}>
                  <div style={{ padding: 14 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 8 }}>
                      <div className="avatar" style={{ width: 28, height: 28, fontSize: 11, background: r.color }}>{r.name.split(' ').map(s=>s[0]).join('').slice(0,2)}</div>
                      <div style={{ flex: 1 }}>
                        <div style={{ fontSize: 13, fontWeight: 500 }}>{r.name}</div>
                        <div className="mono" style={{ fontSize: 10.5, color: 'var(--text-3)' }}>{r.count} users</div>
                      </div>
                      <button className="btn ghost icon sm"><Icon name="moreVert" size={11}/></button>
                    </div>
                    <div style={{ fontSize: 11.5, color: 'var(--text-2)', lineHeight: 1.4 }}>{r.desc}</div>
                  </div>
                </div>
              ))}
            </div>

            <div className="card" style={{ height: 'fit-content', position: 'sticky', top: 12 }}>
              <div className="card-header">
                <div className="card-title">{selectedRole} — permissions</div>
              </div>
              <div style={{ padding: 14 }}>
                <div className="sec-heading">Module access</div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
                  {MODULE_NAMES.slice(0, 9).map((m, i) => {
                    const perms = PERM_MATRIX[selectedRole][i] || [];
                    return (
                      <div key={m} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '5px 8px', background: 'var(--panel-2)', borderRadius: 3, fontSize: 12 }}>
                        <span>{m}</span>
                        <div style={{ display: 'flex', gap: 3 }}>
                          {PERMS.map(p => <span key={p} style={{ width: 6, height: 6, borderRadius: '50%', background: perms.includes(p) ? 'var(--green)' : 'var(--line-2)' }}/>)}
                        </div>
                      </div>
                    );
                  })}
                </div>

                <div className="sec-heading" style={{ marginTop: 16 }}>Operational scope</div>
                <div style={{ fontSize: 11.5, color: 'var(--text-2)' }}>
                  <div className="mono" style={{ padding: '6px 8px', background: 'var(--panel-2)', borderRadius: 3, marginBottom: 4 }}>plants: PUN-N, PUN-S</div>
                  <div className="mono" style={{ padding: '6px 8px', background: 'var(--panel-2)', borderRadius: 3, marginBottom: 4 }}>lines: A, B, C, D</div>
                  <div className="mono" style={{ padding: '6px 8px', background: 'var(--panel-2)', borderRadius: 3 }}>shifts: all</div>
                </div>

                <div className="sec-heading" style={{ marginTop: 16 }}>Approval authority</div>
                <div style={{ fontSize: 11.5 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 0', borderBottom: '1px solid var(--line)' }}><span>Maintenance ticket</span><span className="mono" style={{ color: 'var(--green)' }}>up to ₹2L</span></div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 0', borderBottom: '1px solid var(--line)' }}><span>Quality disposition</span><span className="mono" style={{ color: 'var(--text-3)' }}>—</span></div>
                  <div style={{ display: 'flex', justifyContent: 'space-between', padding: '4px 0' }}><span>Production schedule</span><span className="mono" style={{ color: 'var(--text-3)' }}>—</span></div>
                </div>
              </div>
            </div>
          </div>
        )}

        {tab === 'matrix' && (
          <div className="card" style={{ overflow: 'auto' }}>
            <table className="tbl">
              <thead><tr><th style={{ position: 'sticky', left: 0, background: 'var(--panel-2)', zIndex: 2 }}>Role</th>{MODULE_NAMES.map(m => <th key={m}>{m}</th>)}</tr></thead>
              <tbody>
                {ROLES.map((r, ri) => (
                  <tr key={r.name}>
                    <td style={{ position: 'sticky', left: 0, background: 'var(--panel)', fontWeight: 500 }}>{r.name}</td>
                    {MODULE_NAMES.map((m, mi) => {
                      const perms = PERM_MATRIX[r.name][mi] || [];
                      return (
                        <td key={mi} style={{ textAlign: 'center' }}>
                          <div style={{ display: 'flex', gap: 2, justifyContent: 'center' }}>
                            {PERMS.map(p => <span key={p} title={p} style={{ width: 5, height: 14, borderRadius: 1, background: perms.includes(p) ? 'var(--green)' : 'var(--line-2)' }}/>)}
                          </div>
                        </td>
                      );
                    })}
                  </tr>
                ))}
              </tbody>
            </table>
            <div style={{ padding: 10, fontSize: 11, color: 'var(--text-3)', display: 'flex', gap: 14, borderTop: '1px solid var(--line)' }}>
              <span>4 bars per cell:</span>
              {PERMS.map(p => <span key={p} style={{ display: 'flex', alignItems: 'center', gap: 4 }}><span style={{ width: 5, height: 12, borderRadius: 1, background: 'var(--green)' }}/>{p}</span>)}
            </div>
          </div>
        )}

        {tab === 'users' && (
          <div className="card">
            <table className="tbl">
              <thead><tr><th>User</th><th>Role</th><th>Plants</th><th>Status</th><th>Last active</th><th></th></tr></thead>
              <tbody>
                {[
                  ['Priya Sharma','Plant manager','PUN-N','active','2m ago'],
                  ['Rahul Mehta','Shift supervisor','PUN-N','active','just now'],
                  ['Aarav Desai','Maintenance','PUN-N, PUN-S','active','5m ago'],
                  ['Sneha Joshi','QA inspector','PUN-N','active','12m ago'],
                  ['Pranav Kulkarni','Maintenance','PUN-N','on shift','1m ago'],
                  ['Vikram Singh','Plant head','PUN-N, PUN-S','active','1h ago'],
                  ['Meera Iyer','Corporate admin','All plants','active','22m ago'],
                  ['Imran Ali','Operator','PUN-N','on shift','just now'],
                ].map((u,i)=>(
                  <tr key={i}>
                    <td><div style={{ display: 'flex', alignItems: 'center', gap: 8 }}><div className="avatar" style={{width:22,height:22,fontSize:10}}>{u[0].split(' ').map(s=>s[0]).join('')}</div>{u[0]}</div></td>
                    <td>{u[1]}</td>
                    <td className="mono" style={{ fontSize: 11.5 }}>{u[2]}</td>
                    <td><span className={`pill ${u[3]==='on shift'?'running':''}`}><span className="dot"/>{u[3]}</span></td>
                    <td className="mono" style={{ fontSize: 11.5, color: 'var(--text-3)' }}>{u[4]}</td>
                    <td><button className="btn ghost icon sm"><Icon name="more" size={12}/></button></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        )}

        {tab === 'approvals' && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            {[
              {name:'Maintenance ticket > ₹2L', chain:['Maintenance lead','Plant manager','Plant head']},
              {name:'Quality disposition: scrap > 50 units', chain:['QA inspector','QA manager','Plant manager']},
              {name:'Production schedule change', chain:['Shift supervisor','Plant manager']},
              {name:'New SOP approval', chain:['Process engineer','QA manager','Plant head','Corporate admin']},
            ].map(c => (
              <div key={c.name} className="card">
                <div className="card-header"><div className="card-title">{c.name}</div></div>
                <div style={{ padding: 14, display: 'flex', alignItems: 'center', gap: 4 }}>
                  {c.chain.map((step, i) => (
                    <div key={step} style={{ display: 'contents' }}>
                      <div style={{ flex: 1, padding: 10, border: '1px solid var(--line)', borderRadius: 4, background: 'var(--panel-2)', textAlign: 'center' }}>
                        <div style={{ fontSize: 12, fontWeight: 500 }}>{step}</div>
                        <div className="mono" style={{ fontSize: 10.5, color: 'var(--text-3)' }}>step {i+1}</div>
                      </div>
                      {i < c.chain.length - 1 && <Icon name="arrowRight" size={14} style={{ color: 'var(--text-3)' }}/>}
                    </div>
                  ))}
                </div>
              </div>
            ))}
          </div>
        )}
      </div>
    </>
  );
};

window.RolesPage = RolesPage;
