// handbok.jsx — Håndbøker med Supabase, tilgangsstyring og krysslenker

// ── Supabase-kall ─────────────────────────────────────────────

async function HB_hentKapitler(type) {
  const { data, error } = await window._sb
    .from('handbok_kapitler')
    .select('*, artikler:handbok_artikler(id,tittel,intro,versjon,revidert_dato,status,rekkefølge)')
    .eq('handbok_type', type)
    .order('rekkefølge');
  if (error) throw error;
  return (data || []).map(k => ({
    ...k,
    artikler: (k.artikler || []).sort((a, b) => a.rekkefølge - b.rekkefølge)
  }));
}

async function HB_hentArtikkel(id) {
  const { data, error } = await window._sb
    .from('handbok_artikler')
    .select('*, eier:profiles!eier_id(id,navn,epost)')
    .eq('id', id)
    .single();
  if (error) throw error;
  return data;
}

async function HB_lagreArtikkel(id, felter) {
  const { eier, ...rene } = felter;
  rene.oppdatert_at = new Date().toISOString();
  const { data, error } = await window._sb.from('handbok_artikler').update(rene).eq('id', id).select().single();
  if (error) throw error;
  return data;
}

async function HB_opprettArtikkel(felter) {
  const { eier, ...rene } = felter;
  const { data, error } = await window._sb.from('handbok_artikler').insert([rene]).select().single();
  if (error) throw error;
  return data;
}

async function HB_slettArtikkel(id) {
  const { error } = await window._sb.from('handbok_artikler').delete().eq('id', id);
  if (error) throw error;
}

async function HB_hentProfiler() {
  const { data } = await window._sb.from('profiles').select('id,navn,epost').order('navn');
  return data || [];
}

async function HB_sjekkLederTilgang() {
  const { data: { user } } = await window._sb.auth.getUser();
  if (!user) return false;
  const { data } = await window._sb
    .from('profiles')
    .select('rolle:roller!rolle_id(navn)')
    .eq('id', user.id)
    .single();
  const rolleNavn = data?.rolle?.navn?.toLowerCase() || '';
  return rolleNavn.includes('leder') || rolleNavn.includes('daglig') || rolleNavn.includes('hr') || rolleNavn.includes('admin');
}

// ── Hjelpere ──────────────────────────────────────────────────

function hbFmtDato(d) {
  if (!d) return '—';
  return new Date(d).toLocaleDateString('nb-NO', { day: 'numeric', month: 'long', year: 'numeric' });
}

// Intern-lenker: [[modulnavn|Lenketekst]] i innhold
function HbInnhold({ tekst, go }) {
  if (!tekst) return null;
  const deler = tekst.split(/(\[\[[^\]]+\]\])/g);
  return (
    <div style={{ fontSize: 13.5, lineHeight: 1.8, color: SK.ink, whiteSpace: 'pre-wrap' }}>
      {deler.map((del, i) => {
        const match = del.match(/^\[\[([^\|]+)\|?([^\]]*)\]\]$/);
        if (match) {
          const modul = match[1].trim();
          const tekst = match[2].trim() || modul;
          return (
            <button key={i} onClick={() => go && go(modul)} style={{
              background: SK.iceBlueLight, border: 'none', borderRadius: 4, padding: '1px 8px',
              fontSize: 13, color: SK.ink, cursor: 'pointer', fontFamily: 'inherit',
              textDecoration: 'underline', textDecorationStyle: 'dotted',
            }}>
              → {tekst}
            </button>
          );
        }
        return <span key={i}>{del}</span>;
      })}
    </div>
  );
}

// ── Artikkel-editor ───────────────────────────────────────────

function ArtikkelEditor({ artikkel, kapittelId, profiler, onLagret, onAvbryt }) {
  const [tittel,  setTittel]  = React.useState(artikkel?.tittel || '');
  const [intro,   setIntro]   = React.useState(artikkel?.intro || '');
  const [innhold, setInnhold] = React.useState(artikkel?.innhold || '');
  const [nokkel,  setNokkel]  = React.useState((artikkel?.nokkel_punkter || []).join('\n'));
  const [eierId,  setEierId]  = React.useState(artikkel?.eier_id || '');
  const [versjon, setVersjon] = React.useState(artikkel?.versjon || '1.0');
  const [revidert,setRevidert]= React.useState(artikkel?.revidert_dato || new Date().toISOString().split('T')[0]);
  const [laster,  setLaster]  = React.useState(false);
  const [feil,    setFeil]    = React.useState(null);

  const lagre = async () => {
    if (!tittel.trim()) { setFeil('Tittel er påkrevd.'); return; }
    setLaster(true); setFeil(null);
    const felter = {
      tittel, intro: intro || null, innhold: innhold || null,
      nokkel_punkter: nokkel.split('\n').map(s => s.trim()).filter(Boolean),
      eier_id: eierId || null, versjon, revidert_dato: revidert,
      kapittel_id: kapittelId,
    };
    try {
      const res = artikkel ? await HB_lagreArtikkel(artikkel.id, felter) : await HB_opprettArtikkel(felter);
      onLagret(res);
    } catch(e) { setFeil(e.message); } finally { setLaster(false); }
  };

  const lbl = { fontSize: 11, fontWeight: 600, color: SK.soft, letterSpacing: 0.04, textTransform: 'uppercase' };
  const inp = { padding: '10px 12px', fontSize: 13 };

  return (
    <div style={{ padding: '20px 24px' }}>
      <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 18 }}>{artikkel ? 'Rediger artikkel' : 'Ny artikkel'}</div>
      {feil && <div style={{ background: '#fcddde', border: '1px solid #f2545c', borderRadius: 8, padding: '10px 14px', fontSize: 13, color: '#8a1620', marginBottom: 16 }}>{feil}</div>}
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16, marginBottom: 20 }}>
        <div style={{ gridColumn: '1/-1', display: 'flex', flexDirection: 'column', gap: 6 }}>
          <label style={lbl}>Tittel *</label>
          <input className="ok-input" value={tittel} onChange={e => setTittel(e.target.value)} autoFocus style={inp} />
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
          <label style={lbl}>Eier / ansvarlig</label>
          <select className="ok-input" value={eierId} onChange={e => setEierId(e.target.value)} style={inp}>
            <option value="">— Ikke satt —</option>
            {profiler.map(p => <option key={p.id} value={p.id}>{p.navn || p.epost}</option>)}
          </select>
        </div>
        <div style={{ display: 'flex', gap: 12 }}>
          <div style={{ flex: 1, display: 'flex', flexDirection: 'column', gap: 6 }}>
            <label style={lbl}>Versjon</label>
            <input className="ok-input" value={versjon} onChange={e => setVersjon(e.target.value)} style={inp} placeholder="1.0" />
          </div>
          <div style={{ flex: 2, display: 'flex', flexDirection: 'column', gap: 6 }}>
            <label style={lbl}>Revidert dato</label>
            <input className="ok-input" type="date" value={revidert} onChange={e => setRevidert(e.target.value)} style={inp} />
          </div>
        </div>
        <div style={{ gridColumn: '1/-1', display: 'flex', flexDirection: 'column', gap: 6 }}>
          <label style={lbl}>Ingress</label>
          <textarea className="ok-input" value={intro} onChange={e => setIntro(e.target.value)} rows={2}
            style={{ ...inp, resize: 'vertical', fontFamily: 'inherit', lineHeight: 1.6 }} placeholder="Kort beskrivelse av artikkelen…" />
        </div>
        <div style={{ gridColumn: '1/-1', display: 'flex', flexDirection: 'column', gap: 6 }}>
          <label style={lbl}>Innhold</label>
          <textarea className="ok-input" value={innhold} onChange={e => setInnhold(e.target.value)} rows={12}
            style={{ ...inp, resize: 'vertical', fontFamily: 'inherit', lineHeight: 1.7 }}
            placeholder={'Skriv artikkelteksten her.\n\nBruk [[modulnavn|Lenketekst]] for å lenke til andre moduler.\nEksempel: Se [[protocols|Møter & protokoller]] for mer informasjon.'} />
          <div style={{ fontSize: 11, color: SK.soft }}>Tips: Bruk <code>[[modulnavn|Lenketekst]]</code> for å lenke til andre moduler i systemet.</div>
        </div>
        <div style={{ gridColumn: '1/-1', display: 'flex', flexDirection: 'column', gap: 6 }}>
          <label style={lbl}>Nøkkelpunkter (én per linje)</label>
          <textarea className="ok-input" value={nokkel} onChange={e => setNokkel(e.target.value)} rows={4}
            style={{ ...inp, resize: 'vertical', fontFamily: 'inherit' }} />
        </div>
      </div>
      <div style={{ display: 'flex', gap: 10 }}>
        <Button variant="primary" onClick={lagre} disabled={laster}>{laster ? 'Lagrer…' : (artikkel ? 'Lagre endringer' : 'Opprett artikkel')}</Button>
        <Button onClick={onAvbryt}>Avbryt</Button>
      </div>
    </div>
  );
}

// ── Håndbok-visning ───────────────────────────────────────────

function HandbokVisning({ type, tittel, kanRedigere, go }) {
  const [kapitler,      setKapitler]      = React.useState([]);
  const [profiler,      setProfiler]      = React.useState([]);
  const [laster,        setLaster]        = React.useState(true);
  const [feil,          setFeil]          = React.useState(null);
  const [åpentKapittel, setÅpentKapittel] = React.useState(null);
  const [valgtArtikkel, setValgtArtikkel] = React.useState(null);
  const [artikkelData,  setArtikkelData]  = React.useState(null);
  const [lastArtikkel,  setLastArtikkel]  = React.useState(false);
  const [visEditor,     setVisEditor]     = React.useState(false);
  const [redigerArt,    setRedigerArt]    = React.useState(null);
  const [nyKapId,       setNyKapId]       = React.useState(null);
  const [sok,           setSok]           = React.useState('');

  React.useEffect(() => {
    HB_hentProfiler().then(setProfiler).catch(() => {});
    lastInn();
  }, [type]);

  async function lastInn() {
    setLaster(true); setFeil(null);
    try {
      const k = await HB_hentKapitler(type);
      setKapitler(k);
      if (k.length > 0 && !åpentKapittel) setÅpentKapittel(k[0].id);
    } catch(err) { setFeil(err.message); } finally { setLaster(false); }
  }

  const åpneArtikkel = async (id) => {
    setValgtArtikkel(id); setLastArtikkel(true); setArtikkelData(null); setVisEditor(false);
    try { const a = await HB_hentArtikkel(id); setArtikkelData(a); }
    catch(e) { setFeil(e.message); } finally { setLastArtikkel(false); }
  };

  const sokResultater = sok.length > 1
    ? kapitler.flatMap(k => (k.artikler || []).filter(a => a.tittel.toLowerCase().includes(sok.toLowerCase())))
    : [];

  const totArtikler = kapitler.reduce((s, k) => s + (k.artikler?.length || 0), 0);

  return (
    <div>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20 }}>
        <div>
          <h2 style={{ margin: 0, fontSize: 24, fontWeight: 600 }}>{tittel}</h2>
          <div style={{ fontSize: 13, color: SK.soft, marginTop: 4 }}>{kapitler.length} kapitler · {totArtikler} artikler</div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <input className="ok-input" value={sok} onChange={e => setSok(e.target.value)}
            placeholder="Søk i håndboken…" style={{ padding: '8px 12px', fontSize: 13, width: 200 }} />
          {kanRedigere && (
            <Button variant="primary" size="sm" icon={I.plus} onClick={() => { setNyKapId(åpentKapittel); setRedigerArt(null); setVisEditor(true); setArtikkelData(null); setValgtArtikkel(null); }}>
              Ny artikkel
            </Button>
          )}
        </div>
      </div>

      {feil && <div style={{ background: '#fcddde', border: '1px solid #f2545c', borderRadius: 8, padding: '10px 14px', fontSize: 13, color: '#8a1620', marginBottom: 14 }}>{feil}</div>}

      {/* Søkeresultater */}
      {sok.length > 1 && (
        <Card padded={false} style={{ marginBottom: 16 }}>
          <div style={{ padding: '12px 18px', borderBottom: '1px solid rgba(17,24,61,.07)', fontSize: 12, fontWeight: 600, color: SK.soft, textTransform: 'uppercase', letterSpacing: .04 }}>
            Søkeresultater ({sokResultater.length})
          </div>
          {sokResultater.length === 0 ? (
            <div style={{ padding: '16px 18px', fontSize: 13, color: SK.soft }}>Ingen treff på «{sok}»</div>
          ) : sokResultater.map((a, i) => (
            <div key={a.id} onClick={() => { setSok(''); åpneArtikkel(a.id); }} style={{
              padding: '11px 18px', cursor: 'pointer', borderTop: i > 0 ? '1px solid rgba(17,24,61,.05)' : 'none',
              display: 'flex', alignItems: 'center', gap: 10,
            }}>
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={SK.soft} strokeWidth="2" strokeLinecap="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/></svg>
              <span style={{ fontSize: 13, fontWeight: 500 }}>{a.tittel}</span>
              {a.intro && <span style={{ fontSize: 12, color: SK.soft, flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{a.intro}</span>}
            </div>
          ))}
        </Card>
      )}

      {visEditor && kanRedigere && (
        <Card padded={false} style={{ marginBottom: 20 }}>
          <ArtikkelEditor
            artikkel={redigerArt}
            kapittelId={nyKapId || åpentKapittel}
            profiler={profiler}
            onLagret={async () => { await lastInn(); setVisEditor(false); setRedigerArt(null); if (redigerArt) åpneArtikkel(redigerArt.id); }}
            onAvbryt={() => { setVisEditor(false); setRedigerArt(null); }} />
        </Card>
      )}

      {laster ? (
        <Card padded><div style={{ padding: 32, textAlign: 'center', color: SK.soft, fontSize: 13 }}>Laster…</div></Card>
      ) : (
        <div style={{ display: 'grid', gridTemplateColumns: '260px 1fr', gap: 20, alignItems: 'flex-start' }}>
          {/* Innholdsfortegnelse */}
          <div style={{ position: 'sticky', top: 0 }}>
            <div style={{ fontSize: 11, fontWeight: 600, color: SK.soft, letterSpacing: 0.08, textTransform: 'uppercase', marginBottom: 10 }}>Innhold</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 3 }}>
              {kapitler.map(k => (
                <div key={k.id}>
                  <div onClick={() => setÅpentKapittel(åpentKapittel === k.id ? null : k.id)} style={{
                    cursor: 'pointer', padding: '8px 12px', borderRadius: 8, fontSize: 13,
                    fontWeight: åpentKapittel === k.id ? 600 : 400,
                    background: åpentKapittel === k.id ? SK.iceBlueLight : 'transparent',
                    color: åpentKapittel === k.id ? SK.ink : SK.ink,
                    display: 'flex', justifyContent: 'space-between', alignItems: 'center',
                    transition: 'all .1s',
                  }}>
                    <span>{k.nr}. {k.tittel}</span>
                    <span style={{ fontSize: 11, color: SK.soft }}>{k.artikler?.length || 0}</span>
                  </div>
                  {åpentKapittel === k.id && (
                    <div style={{ paddingLeft: 8, marginTop: 2 }}>
                      {(k.artikler || []).map(a => (
                        <div key={a.id} onClick={() => åpneArtikkel(a.id)} style={{
                          cursor: 'pointer', padding: '6px 12px', borderRadius: 6, fontSize: 12.5,
                          background: valgtArtikkel === a.id ? SK.ink : 'transparent',
                          color: valgtArtikkel === a.id ? '#fff' : SK.ink,
                          marginBottom: 1, transition: 'all .1s',
                          display: 'flex', alignItems: 'center', gap: 6,
                        }}>
                          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" style={{ opacity: .5, flexShrink: 0 }}><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/></svg>
                          {a.tittel}
                        </div>
                      ))}
                      {kanRedigere && (
                        <div onClick={() => { setNyKapId(k.id); setRedigerArt(null); setVisEditor(true); }} style={{
                          cursor: 'pointer', padding: '5px 12px', borderRadius: 6, fontSize: 12, color: SK.soft,
                          display: 'flex', alignItems: 'center', gap: 6, marginTop: 2,
                        }}>
                          <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><line x1="12" y1="5" x2="12" y2="19"/><line x1="5" y1="12" x2="19" y2="12"/></svg>
                          Ny artikkel i dette kapitlet
                        </div>
                      )}
                    </div>
                  )}
                </div>
              ))}
            </div>
          </div>

          {/* Artikkelvisning */}
          <div>
            {!valgtArtikkel && !visEditor && (
              <Card padded>
                <div style={{ padding: '32px 0', textAlign: 'center', color: SK.soft, fontSize: 13 }}>
                  Velg en artikkel i innholdsfortegnelsen til venstre.
                </div>
              </Card>
            )}
            {lastArtikkel && (
              <Card padded><div style={{ padding: 32, textAlign: 'center', color: SK.soft, fontSize: 13 }}>Laster artikkel…</div></Card>
            )}
            {artikkelData && !lastArtikkel && !visEditor && (
              <Card padded={false}>
                <div style={{ padding: '22px 28px', borderBottom: '1px solid rgba(17,24,61,.08)',
                  display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 14 }}>
                  <div>
                    <h2 style={{ margin: 0, fontSize: 22, fontWeight: 600, letterSpacing: -0.01 }}>{artikkelData.tittel}</h2>
                    <div style={{ display: 'flex', gap: 16, marginTop: 10, fontSize: 12.5, color: SK.soft, flexWrap: 'wrap' }}>
                      {artikkelData.eier?.navn && (
                        <span style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
                          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><circle cx="12" cy="8" r="4"/><path d="M5.5 22a8 8 0 0 1 13 0"/></svg>
                          {artikkelData.eier.navn}
                        </span>
                      )}
                      <span>v{artikkelData.versjon}</span>
                      <span>Revidert {hbFmtDato(artikkelData.revidert_dato)}</span>
                    </div>
                  </div>
                  {kanRedigere && (
                    <Button size="sm" onClick={() => { setRedigerArt(artikkelData); setNyKapId(artikkelData.kapittel_id); setVisEditor(true); }}>Rediger</Button>
                  )}
                </div>
                <div style={{ padding: '24px 28px' }}>
                  {artikkelData.intro && (
                    <div style={{ fontSize: 14.5, color: SK.soft, lineHeight: 1.7, marginBottom: 22, padding: '14px 18px',
                      background: SK.iceBlueLight, borderRadius: 8, borderLeft: `3px solid ${SK.ink}` }}>
                      {artikkelData.intro}
                    </div>
                  )}
                  {artikkelData.innhold && (
                    <HbInnhold tekst={artikkelData.innhold} go={go} />
                  )}
                  {artikkelData.nokkel_punkter?.length > 0 && (
                    <div style={{ marginTop: 24, padding: '16px 20px', background: SK.iceBlueLight, borderRadius: 10 }}>
                      <div style={{ fontSize: 11, fontWeight: 600, color: SK.soft, textTransform: 'uppercase', letterSpacing: 0.04, marginBottom: 12 }}>Nøkkelpunkter</div>
                      {artikkelData.nokkel_punkter.map((p, i) => (
                        <div key={i} style={{ display: 'flex', gap: 10, padding: '5px 0', fontSize: 13.5, lineHeight: 1.5 }}>
                          <span style={{ color: SK.coral, fontWeight: 700, flexShrink: 0 }}>·</span>
                          <span>{p}</span>
                        </div>
                      ))}
                    </div>
                  )}
                  {kanRedigere && (
                    <div style={{ marginTop: 24, paddingTop: 18, borderTop: '1px solid rgba(17,24,61,.07)', display: 'flex', gap: 10 }}>
                      <Button size="sm" onClick={() => { setRedigerArt(artikkelData); setNyKapId(artikkelData.kapittel_id); setVisEditor(true); }}>Rediger artikkel</Button>
                      <Button size="sm" onClick={async () => { if (confirm('Slette denne artikkelen?')) { await HB_slettArtikkel(artikkelData.id); await lastInn(); setArtikkelData(null); setValgtArtikkel(null); }}}>Slett</Button>
                    </div>
                  )}
                </div>
              </Card>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

// ── HandbookWorkspace (hoved) ─────────────────────────────────

function HandbookWorkspace({ go, startFane = 'personal' }) {
  const [fane,          setFane]          = React.useState(startFane);
  const [harLederTilgang,setHarLederTilgang] = React.useState(false);
  const [sjekkFerdig,   setSjekkFerdig]   = React.useState(false);
  const [kanRedigere,   setKanRedigere]   = React.useState(false);

  React.useEffect(() => {
    HB_sjekkLederTilgang().then(harTilgang => {
      setHarLederTilgang(harTilgang);
      setKanRedigere(harTilgang);
      // Hvis vi ble bedt om å starte på leder-fanen men mangler tilgang, fall tilbake
      if (startFane === 'leder' && !harTilgang) setFane('personal');
      setSjekkFerdig(true);
    }).catch(() => setSjekkFerdig(true));
  }, []);

  if (!sjekkFerdig) return (
    <div className="ok-content__inner">
      <div style={{ padding: 48, textAlign: 'center', color: SK.soft, fontSize: 13 }}>Sjekker tilgang…</div>
    </div>
  );

  return (
    <div className="ok-content__inner" style={{ maxWidth: 1320 }}>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 24 }}>
        <div>
          <div style={{ fontSize: 11, fontWeight: 600, color: SK.soft, letterSpacing: 0.08, textTransform: 'uppercase' }}>Ressurser</div>
          <h1 style={{ margin: '6px 0 0', fontSize: 28, fontWeight: 600, letterSpacing: -0.02 }}>Håndbøker</h1>
          <div style={{ marginTop: 4, color: SK.soft, fontSize: 13 }}>
            Personalhåndbok og lederhåndbok med versjonering og søk
          </div>
        </div>
        {!kanRedigere && (
          <div style={{ fontSize: 12, color: SK.soft, background: SK.iceBlueLight, padding: '8px 14px', borderRadius: 8 }}>
            Kun lesing — kontakt HR for å be om redigeringstilgang
          </div>
        )}
      </div>

      <div style={{ display: 'flex', borderBottom: '1px solid rgba(17,24,61,.08)', marginBottom: 28 }}>
        <button onClick={() => setFane('personal')} style={{
          background: 'none', border: 'none', cursor: 'pointer', padding: '10px 22px',
          fontSize: 14, fontWeight: fane === 'personal' ? 600 : 400,
          color: fane === 'personal' ? SK.ink : SK.soft,
          borderBottom: fane === 'personal' ? `2px solid ${SK.coral}` : '2px solid transparent',
          fontFamily: 'inherit',
        }}>Personalhåndbok</button>
        {harLederTilgang && (
          <button onClick={() => setFane('leder')} style={{
            background: 'none', border: 'none', cursor: 'pointer', padding: '10px 22px',
            fontSize: 14, fontWeight: fane === 'leder' ? 600 : 400,
            color: fane === 'leder' ? SK.ink : SK.soft,
            borderBottom: fane === 'leder' ? `2px solid ${SK.coral}` : '2px solid transparent',
            fontFamily: 'inherit',
            display: 'flex', alignItems: 'center', gap: 6,
          }}>
            Lederhåndbok
            <span style={{ fontSize: 10, background: '#fdeac8', color: '#8e5a05', padding: '1px 6px', borderRadius: 99, fontWeight: 700 }}>Leder</span>
          </button>
        )}
        {!harLederTilgang && (
          <button disabled style={{
            background: 'none', border: 'none', padding: '10px 22px', fontSize: 14,
            color: 'rgba(17,24,61,.25)', display: 'flex', alignItems: 'center', gap: 6, cursor: 'not-allowed',
          }}>
            Lederhåndbok
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" style={{ opacity: .4 }}>
              <rect width="18" height="11" x="3" y="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/>
            </svg>
          </button>
        )}
      </div>

      {fane === 'personal' && <HandbokVisning type="personal" tittel="Personalhåndbok" kanRedigere={kanRedigere} go={go} />}
      {fane === 'leder' && harLederTilgang && <HandbokVisning type="leder" tittel="Lederhåndbok" kanRedigere={kanRedigere} go={go} />}
    </div>
  );
}

function Personalhandbok({ go }) { return <HandbookWorkspace go={go} startFane="personal" />; }
function Lederhandbok({ go })    { return <HandbookWorkspace go={go} startFane="leder" />; }

Object.assign(window, { HandbookWorkspace, Personalhandbok, Lederhandbok });

