// tilgang-screens.jsx — Tilganger & innstillinger (hi-fi, interaktiv)
// Faner: Brukere · Roller & matrise · Overstyringer · Forespørsler · Aktivitet · Innstillinger

// ── Liten gjenbrukt rettighetscelle ─────────────────────────────────────────
const KodeCelle = ({ kode, size = 26, onClick, title }) => {
  const c = AKS_KODER[kode];
  return (
    <div
      onClick={onClick}
      title={title}
      style={{
        width: size, height: size, display: 'flex', alignItems: 'center', justifyContent: 'center',
        background: c.bg, color: c.fg, fontSize: size > 24 ? 11.5 : 10, fontWeight: 700,
        borderRadius: 6, boxShadow: kode === '·' ? `inset 0 0 0 1px ${c.ring}` : `inset 0 0 0 1.5px ${c.ring}`,
        cursor: onClick ? 'pointer' : 'default', transition: 'transform .08s, box-shadow .12s', userSelect: 'none',
        fontVariantNumeric: 'tabular-nums',
      }}
      onMouseDown={onClick ? e => { e.currentTarget.style.transform = 'scale(.9)'; } : undefined}
      onMouseUp={onClick ? e => { e.currentTarget.style.transform = 'scale(1)'; } : undefined}
      onMouseLeave={onClick ? e => { e.currentTarget.style.transform = 'scale(1)'; } : undefined}
    >{c.kort}</div>
  );
};

const StatusPill = ({ status }) => {
  const map = {
    aktiv:    { bg: '#dbeed8', fg: '#2f5a28', dot: '#08654f', label: 'Aktiv' },
    sperret:  { bg: '#fcddde', fg: '#a01a25', dot: '#f2545c', label: 'Sperret' },
    invitert: { bg: '#fdeac8', fg: '#8e5a05', dot: '#f2b950', label: 'Invitert' },
  };
  const m = map[status] || map.aktiv;
  return (
    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '3px 10px', borderRadius: 999,
      background: m.bg, color: m.fg, fontSize: 10.5, fontWeight: 600 }}>
      <span style={{ width: 6, height: 6, borderRadius: '50%', background: m.dot }} />{m.label}
    </span>
  );
};

const Forklaring = () => (
  <div style={{ display: 'flex', gap: 14, flexWrap: 'wrap', alignItems: 'center' }}>
    {AKS_KODE_REKKE.map(k => (
      <div key={k} style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
        <KodeCelle kode={k} size={22} />
        <span style={{ fontSize: 11.5, color: SK.soft }}>{AKS_KODER[k].label}</span>
      </div>
    ))}
  </div>
);

// ═════════════════════════════════════════════════════════════════
// FANE · BRUKERE
// ═════════════════════════════════════════════════════════════════
function FaneBrukereMock({ brukere, setBrukere, go }) {
  const [sok, setSok] = React.useState('');
  const [filt, setFilt] = React.useState('alle');
  const [valgt, setValgt] = React.useState(null);

  const filtrert = brukere.filter(b => {
    if (filt !== 'alle' && b.status !== filt) return false;
    if (!sok) return true;
    const q = sok.toLowerCase();
    return aksNavn(b.id).toLowerCase().includes(q) || b.epost.toLowerCase().includes(q) || b.avd.toLowerCase().includes(q);
  });

  const settStatus = (id, status) => {
    setBrukere(prev => prev.map(b => b.id === id ? { ...b, status } : b));
    setValgt(v => v && v.id === id ? { ...v, status } : v);
  };

  const valgtBruker = valgt ? brukere.find(b => b.id === valgt.id) : null;

  return (
    <div style={{ display: 'grid', gridTemplateColumns: valgtBruker ? '1fr 360px' : '1fr', gap: 16, alignItems: 'start' }}>
      <div>
        <div style={{ display: 'flex', gap: 8, marginBottom: 14, alignItems: 'center' }}>
          <input className="ok-input ok-input--search" placeholder="Søk navn, e-post, avdeling…" value={sok}
            onChange={e => setSok(e.target.value)} style={{ maxWidth: 300, padding: '7px 12px 7px 32px' }} />
          <select className="ok-input" value={filt} onChange={e => setFilt(e.target.value)} style={{ maxWidth: 150, padding: '7px 10px' }}>
            <option value="alle">Alle ({brukere.length})</option>
            <option value="aktiv">Aktive</option>
            <option value="sperret">Sperret</option>
            <option value="invitert">Inviterte</option>
          </select>
          <div style={{ marginLeft: 'auto' }}><Button variant="primary" icon={I.plus}>Inviter bruker</Button></div>
        </div>
        <Card padded={false}>
          <table className="ok-table">
            <thead>
              <tr>
                <th>Navn</th><th>Rolle</th><th>Avdeling</th><th>Status</th><th>2FA</th><th>Sist aktiv</th>
              </tr>
            </thead>
            <tbody>
              {filtrert.map(b => {
                const r = aksRolle(b.rolle);
                return (
                  <tr key={b.id} onClick={() => setValgt({ id: b.id })} style={{ background: valgt?.id === b.id ? SK.iceBlueLight : undefined }}>
                    <td>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                        <Avatar initials={b.id} color={aksFarge(b.id)} />
                        <div style={{ minWidth: 0 }}>
                          <div style={{ fontWeight: 600, fontSize: 12.5 }}>{aksNavn(b.id)}</div>
                          <div style={{ fontSize: 11, color: SK.soft }}>{b.epost}</div>
                        </div>
                      </div>
                    </td>
                    <td>
                      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 12 }}>
                        <span style={{ width: 8, height: 8, borderRadius: '50%', background: r?.farge }} />{r?.label}
                      </span>
                    </td>
                    <td style={{ fontSize: 12, color: SK.soft }}>{b.avd}</td>
                    <td><StatusPill status={b.status} /></td>
                    <td>{b.mfa
                      ? <span style={{ fontSize: 11, color: SK.success, fontWeight: 600 }}>På</span>
                      : <span style={{ fontSize: 11, color: SK.coral, fontWeight: 600 }}>Av</span>}</td>
                    <td style={{ fontSize: 11.5, color: SK.soft, whiteSpace: 'nowrap' }}>{b.sist}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </Card>
      </div>

      {valgtBruker && <BrukerPanel b={valgtBruker} onLukk={() => setValgt(null)} settStatus={settStatus} go={go} />}
    </div>
  );
}

function BrukerPanel({ b, onLukk, settStatus, go }) {
  const r = aksRolle(b.rolle);
  const overstyr = AKS_OVERSTYRINGER.filter(o => o.bruker === b.id);
  const rad = AKS_MATRISE_DEFAULT[b.rolle] || [];
  return (
    <Card padded={false} style={{ position: 'sticky', top: 0 }}>
      <div style={{ padding: '16px 18px', borderBottom: '1px solid rgba(17,24,61,.08)', display: 'flex', gap: 12, alignItems: 'center' }}>
        <Avatar initials={b.id} color={aksFarge(b.id)} size={42} />
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontWeight: 600, fontSize: 15 }}>{aksNavn(b.id)}</div>
          <div style={{ fontSize: 11.5, color: SK.soft }}>{b.epost}</div>
        </div>
        <Button variant="ghost" size="icon" onClick={onLukk}>✕</Button>
      </div>
      <div style={{ padding: 18, display: 'flex', flexDirection: 'column', gap: 16 }}>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <Felt label="Rolle" value={<span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><span style={{ width: 8, height: 8, borderRadius: '50%', background: r?.farge }} />{r?.label}</span>} />
          <Felt label="Avdeling" value={b.avd} />
          <Felt label="Status" value={<StatusPill status={b.status} />} />
          <Felt label="2-faktor" value={b.mfa ? <span style={{ color: SK.success, fontWeight: 600 }}>Påslått</span> : <span style={{ color: SK.coral, fontWeight: 600 }}>Av</span>} />
        </div>

        <div>
          <div style={{ fontSize: 10.5, fontWeight: 600, color: SK.soft, letterSpacing: 0.06, textTransform: 'uppercase', marginBottom: 8 }}>Effektiv tilgang (fra rolle)</div>
          <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
            {AKS_MODULER.filter(m => !m.sub).map((m) => {
              const idx = AKS_MODULER.indexOf(m);
              const kode = rad[idx] || '·';
              if (kode === '·') return null;
              return (
                <span key={m.k} style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11, padding: '3px 8px', borderRadius: 7, background: SK.iceBlueLight }}>
                  <KodeCelle kode={kode} size={16} />{m.n}
                </span>
              );
            })}
          </div>
        </div>

        {overstyr.length > 0 && (
          <div>
            <div style={{ fontSize: 10.5, fontWeight: 600, color: SK.soft, letterSpacing: 0.06, textTransform: 'uppercase', marginBottom: 8 }}>Overstyringer ({overstyr.length})</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {overstyr.map((o, i) => {
                const m = AKS_MODULER.find(x => x.k === o.modul);
                return (
                  <div key={i} style={{ border: '1px solid rgba(17,24,61,.1)', borderRadius: 8, padding: '8px 10px' }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12 }}>
                      <span style={{ fontWeight: 600 }}>{m?.n}</span>
                      <span style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 4 }}>
                        <KodeCelle kode={o.fra} size={18} /><span style={{ color: SK.soft }}>→</span><KodeCelle kode={o.til} size={18} />
                      </span>
                    </div>
                    <div style={{ fontSize: 11, color: SK.soft, marginTop: 4, lineHeight: 1.4 }}>{o.begrunnelse}</div>
                  </div>
                );
              })}
            </div>
          </div>
        )}

        <div style={{ display: 'flex', gap: 8, borderTop: '1px solid rgba(17,24,61,.08)', paddingTop: 14, flexWrap: 'wrap' }}>
          {b.status === 'sperret'
            ? <Button variant="primary" onClick={() => settStatus(b.id, 'aktiv')}>Gjenåpne konto</Button>
            : <Button variant="accent" onClick={() => settStatus(b.id, 'sperret')}>Sperr konto</Button>}
          <Button size="sm">Endre rolle</Button>
          {b.rolle === 'styre' && <Button size="sm" onClick={() => go({ screen: 'styre' })}>Åpne styreportal</Button>}
        </div>
      </div>
    </Card>
  );
}

const Felt = ({ label, value }) => (
  <div>
    <div style={{ fontSize: 10, fontWeight: 600, color: SK.soft, letterSpacing: 0.05, textTransform: 'uppercase' }}>{label}</div>
    <div style={{ fontSize: 12.5, marginTop: 3 }}>{value}</div>
  </div>
);

// ═════════════════════════════════════════════════════════════════
// FANE · ROLLER & MATRISE  (interaktiv — klikk celle for å sykle kode)
// ═════════════════════════════════════════════════════════════════
function FaneMatriseMock({ matrise, setMatrise, dirty, lagre, tilbakestill }) {
  const sykle = (rolleK, modulIdx) => {
    setMatrise(prev => {
      const rad = [...prev[rolleK]];
      const naa = rad[modulIdx];
      const ni = (AKS_KODE_REKKE.indexOf(naa) + 1) % AKS_KODE_REKKE.length;
      rad[modulIdx] = AKS_KODE_REKKE[ni];
      return { ...prev, [rolleK]: rad };
    });
  };

  let forrigeGruppe = null;
  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 14, flexWrap: 'wrap' }}>
        <Forklaring />
        <div style={{ marginLeft: 'auto', display: 'flex', gap: 8, alignItems: 'center' }}>
          {dirty && <span style={{ fontSize: 11.5, color: SK.coral, fontWeight: 600 }}>● Ulagrede endringer</span>}
          <Button size="sm" onClick={tilbakestill} disabled={!dirty}>Tilbakestill</Button>
          <Button variant="primary" size="sm" onClick={lagre} disabled={!dirty}>Lagre endringer</Button>
        </div>
      </div>
      <div style={{ fontSize: 12, color: SK.soft, marginBottom: 10 }}>Klikk en celle for å sykle gjennom rettighetsnivå. Avdeling kombineres på toppen i per-bruker-overstyringer.</div>
      <Card padded={false} style={{ overflow: 'hidden' }}>
        <div style={{ overflowX: 'auto' }}>
          <table style={{ borderCollapse: 'collapse', width: '100%', minWidth: 760 }}>
            <thead>
              <tr>
                <th style={{ position: 'sticky', left: 0, zIndex: 2, background: SK.iceBlueLight, textAlign: 'left', padding: '12px 14px', minWidth: 210,
                  fontSize: 11, fontWeight: 600, letterSpacing: 0.04, textTransform: 'uppercase', color: SK.soft, borderBottom: '1px solid rgba(17,24,61,.1)' }}>Modul</th>
                {AKS_ROLLER.map(r => (
                  <th key={r.k} style={{ padding: '10px 4px', borderBottom: '1px solid rgba(17,24,61,.1)', borderLeft: '1px solid rgba(17,24,61,.05)', verticalAlign: 'bottom', minWidth: 58 }}>
                    <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 6 }}>
                      <span style={{ width: 9, height: 9, borderRadius: '50%', background: r.farge }} />
                      <span style={{ writingMode: 'vertical-rl', transform: 'rotate(180deg)', fontSize: 11, fontWeight: 600, color: SK.ink, whiteSpace: 'nowrap', maxHeight: 96 }}>{r.label}</span>
                    </div>
                  </th>
                ))}
              </tr>
            </thead>
            <tbody>
              {AKS_MODULER.map((m, mi) => {
                const nyGruppe = m.gruppe !== forrigeGruppe;
                forrigeGruppe = m.gruppe;
                return (
                  <React.Fragment key={m.k}>
                    {nyGruppe && (
                      <tr>
                        <td colSpan={AKS_ROLLER.length + 1} style={{ background: '#fff', padding: '12px 14px 4px', fontSize: 10, fontWeight: 700, letterSpacing: 0.1, textTransform: 'uppercase', color: SK.soft, position: 'sticky', left: 0 }}>{m.gruppe}</td>
                      </tr>
                    )}
                    <tr style={{ borderTop: '1px solid rgba(17,24,61,.05)' }}>
                      <td style={{ position: 'sticky', left: 0, zIndex: 1, background: '#fff', padding: '7px 14px', fontSize: 12.5 }}>
                        <span style={{ paddingLeft: m.sub ? 16 : 0, color: m.sub ? SK.soft : SK.ink, fontWeight: m.sub ? 400 : 500 }}>
                          {m.sub && <span style={{ color: 'rgba(17,24,61,.3)', marginRight: 4 }}>↳</span>}{m.n}
                          {m.sensitiv && <span title="Sensitiv modul" style={{ marginLeft: 6, fontSize: 9, color: SK.coral, fontWeight: 700, verticalAlign: 'middle' }}>●</span>}
                        </span>
                      </td>
                      {AKS_ROLLER.map(r => (
                        <td key={r.k} style={{ textAlign: 'center', padding: '5px 4px', borderLeft: '1px solid rgba(17,24,61,.04)' }}>
                          <div style={{ display: 'flex', justifyContent: 'center' }}>
                            <KodeCelle kode={matrise[r.k][mi]} onClick={() => sykle(r.k, mi)} title={`${r.label} · ${m.n}`} />
                          </div>
                        </td>
                      ))}
                    </tr>
                  </React.Fragment>
                );
              })}
            </tbody>
          </table>
        </div>
      </Card>
      <div style={{ marginTop: 8, fontSize: 11, color: SK.soft }}><span style={{ color: SK.coral }}>●</span> Sensitiv modul — krever eksplisitt admin-godkjenning.</div>
    </div>
  );
}

Object.assign(window, { KodeCelle, StatusPill, Forklaring, FaneBrukereMock, BrukerPanel, FaneMatriseMock, Felt });
