// kvalitet-screens-2.jsx — Kvalitet (ISO) workspace, del 2.
// Interaktive faner: Risiko (matrise + register), Avvik (arbeidsflyt + meld nytt),
// Revisjoner (revisjonsprogram + ledelsens gjennomgang), Oppgaver (tiltaksspor).

// ── Gjenbrukbar modal-overlay ────────────────────────────────────────────────
function KvalModal({ onClose, width = 560, children }) {
  React.useEffect(() => {
    const h = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', h);
    return () => window.removeEventListener('keydown', h);
  }, [onClose]);
  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, zIndex: 1000, background: 'rgba(17,24,61,.42)', backdropFilter: 'blur(2px)',
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24,
    }}>
      <div onClick={e => e.stopPropagation()} style={{
        width: `min(${width}px, 100%)`, maxHeight: '90vh', overflowY: 'auto',
        background: SK.pureWhite, borderRadius: 16, boxShadow: '0 24px 70px rgba(17,24,61,.32)',
      }}>{children}</div>
    </div>
  );
}
const KvalModalClose = ({ onClose }) => (
  <button onClick={onClose} style={{
    background: SK.pureWhite, border: '1px solid rgba(17,24,61,.12)', borderRadius: 99,
    width: 30, height: 30, cursor: 'pointer', color: SK.soft, flexShrink: 0,
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
  }}>
    <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M18 6 6 18M6 6l12 12"/></svg>
  </button>
);

// ═══════════════════════════════════════════════════════════════════════════
// RISIKO — matrise + register (ISO 9001 §6.1 / 14001 §6.1.2)
// ═══════════════════════════════════════════════════════════════════════════
function KvalRisiko({ go, risiko, setRisiko }) {
  const [bruk, setBruk] = React.useState('iboende'); // iboende | rest
  const [filterStd, setFilterStd] = React.useState('alle');
  const [filterType, setFilterType] = React.useState('alle');
  const [sel, setSel] = React.useState(null);

  const visible = risiko.filter(r =>
    (filterStd === 'alle' || r.std.includes(filterStd)) &&
    (filterType === 'alle' || r.type === filterType));

  const sOf = (r) => bruk === 'rest' ? r.restSann : r.sann;
  const kOf = (r) => bruk === 'rest' ? r.restKons : r.kons;

  const selRisk = sel ? risiko.find(r => r.id === sel) : null;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      {/* Filterrad */}
      <Card padded>
        <div style={{ display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
          <div style={{ display: 'flex', gap: 4 }}>
            {[['iboende', 'Iboende risiko'], ['rest', 'Restrisiko']].map(([k, l]) => (
              <button key={k} onClick={() => setBruk(k)} className="ok-btn ok-btn--sm" style={{
                background: bruk === k ? SK.ink : 'transparent', color: bruk === k ? '#fff' : SK.ink,
                borderColor: bruk === k ? SK.ink : 'rgba(17,24,61,.15)',
              }}>{l}</button>
            ))}
          </div>
          <div style={{ width: 1, height: 22, background: 'rgba(17,24,61,.1)' }} />
          <select className="ok-input" value={filterStd} onChange={e => setFilterStd(e.target.value)} style={{ maxWidth: 170, padding: '6px 10px' }}>
            <option value="alle">Begge standarder</option>
            <option value="9001">ISO 9001</option>
            <option value="14001">ISO 14001</option>
          </select>
          <select className="ok-input" value={filterType} onChange={e => setFilterType(e.target.value)} style={{ maxWidth: 150, padding: '6px 10px' }}>
            <option value="alle">Alle typer</option>
            {Object.entries(KVAL_RISIKO_TYPER).map(([k, v]) => <option key={k} value={k}>{v.label}</option>)}
          </select>
          <span style={{ marginLeft: 'auto', fontSize: 11.5, color: SK.soft }}>{visible.length} risikoer · viser {bruk === 'rest' ? 'restrisiko etter tiltak' : 'iboende risiko'}</span>
        </div>
      </Card>

      <div style={{ display: 'grid', gridTemplateColumns: '420px 1fr', gap: 14, alignItems: 'flex-start' }}>
        {/* Matrise */}
        <Card padded>
          <KvalSectionLabel sub="Sannsynlighet × konsekvens. Klikk en risiko for detaljer.">Risikomatrise (5×5)</KvalSectionLabel>
          <div style={{ display: 'flex', gap: 8 }}>
            {/* Y-akse */}
            <div style={{ display: 'flex', flexDirection: 'column', justifyContent: 'space-between', alignItems: 'center', paddingBottom: 22 }}>
              <span style={{ writingMode: 'vertical-rl', transform: 'rotate(180deg)', fontSize: 10, fontWeight: 600, color: SK.soft, letterSpacing: 0.06, textTransform: 'uppercase' }}>Sannsynlighet →</span>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 4 }}>
                {[5, 4, 3, 2, 1].map(s => (
                  [1, 2, 3, 4, 5].map(k => {
                    const n = kvalRisikoNivaa(s, k);
                    const here = visible.filter(r => sOf(r) === s && kOf(r) === k);
                    return (
                      <div key={`${s}-${k}`} style={{
                        aspectRatio: '1', background: n.bg, borderRadius: 6, padding: 3,
                        display: 'flex', flexWrap: 'wrap', gap: 2, alignContent: 'flex-start',
                        border: '1px solid rgba(255,255,255,.6)',
                      }}>
                        {here.map(r => (
                          <button key={r.id} onClick={() => setSel(r.id)} title={r.navn} style={{
                            border: sel === r.id ? `2px solid ${SK.ink}` : '1px solid rgba(17,24,61,.2)',
                            background: SK.pureWhite, color: n.farge, borderRadius: 5, cursor: 'pointer',
                            fontSize: 9, fontWeight: 700, padding: '2px 4px', fontFamily: 'inherit', lineHeight: 1,
                          }}>{r.nr.replace('RIS-', '')}</button>
                        ))}
                      </div>
                    );
                  })
                ))}
              </div>
              <div style={{ textAlign: 'center', fontSize: 10, fontWeight: 600, color: SK.soft, letterSpacing: 0.06, textTransform: 'uppercase', marginTop: 6 }}>Konsekvens →</div>
            </div>
          </div>
          {/* Forklaring */}
          <div style={{ display: 'flex', gap: 12, marginTop: 12, flexWrap: 'wrap' }}>
            {[[1, 1], [2, 2], [3, 3], [4, 4]].map(([s, k], i) => {
              const labels = ['Lav', 'Middels', 'Høy', 'Kritisk'];
              const n = kvalRisikoNivaa(s, k);
              return (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 5 }}>
                  <span style={{ width: 11, height: 11, borderRadius: 3, background: n.bg, border: `1px solid ${n.farge}` }} />
                  <span style={{ fontSize: 10.5, color: SK.soft }}>{labels[i]}</span>
                </div>
              );
            })}
          </div>
        </Card>

        {/* Register */}
        <Card padded={false}>
          <table className="ok-table">
            <thead>
              <tr>
                <th style={{ paddingLeft: 18 }}>Risiko</th>
                <th>Type</th>
                <th>Eier</th>
                <th>{bruk === 'rest' ? 'Restrisiko' : 'Iboende'}</th>
              </tr>
            </thead>
            <tbody>
              {visible.map(r => {
                const eier = TEAM[r.eier];
                return (
                  <TR key={r.id} onClick={() => setSel(r.id)}>
                    <td style={{ paddingLeft: 18 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 2 }}>
                        <span style={{ fontSize: 10.5, fontWeight: 700, color: SK.soft }}>{r.nr}</span>
                        <ISOTags std={r.std} klausul={r.klausul} mini />
                      </div>
                      <div style={{ fontWeight: 600, fontSize: 12.5 }}>{r.navn}</div>
                    </td>
                    <td><span style={{ fontSize: 11, fontWeight: 600, color: KVAL_RISIKO_TYPER[r.type].farge }}>{KVAL_RISIKO_TYPER[r.type].label}</span></td>
                    <td>{eier ? <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}><Avatar initials={eier.i} color={eier.c} size={20} /><span style={{ fontSize: 11.5 }}>{eier.n.split(' ')[0]}</span></div> : '—'}</td>
                    <td><RisikoBadge s={sOf(r)} k={kOf(r)} /></td>
                  </TR>
                );
              })}
            </tbody>
          </table>
        </Card>
      </div>

      {selRisk && <RisikoDetailModal r={selRisk} go={go} onClose={() => setSel(null)} setRisiko={setRisiko} />}
    </div>
  );
}

function RisikoDetailModal({ r, go, onClose, setRisiko }) {
  const eier = TEAM[r.eier];
  const toggleTiltak = (i) => setRisiko(list => list.map(x => x.id !== r.id ? x : {
    ...x, tiltak: x.tiltak.map((t, j) => j === i ? { ...t, status: t.status === 'done' ? 'open' : 'done' } : t),
  }));
  return (
    <KvalModal onClose={onClose} width={600}>
      <div style={{ padding: 22, background: SK.iceBlueLight, display: 'flex', justifyContent: 'space-between', gap: 12 }}>
        <div style={{ minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6, flexWrap: 'wrap' }}>
            <span style={{ fontSize: 11, fontWeight: 700, color: SK.soft }}>{r.nr}</span>
            <ISOTags std={r.std} klausul={r.klausul} />
            <span style={{ fontSize: 11, fontWeight: 600, color: KVAL_RISIKO_TYPER[r.type].farge }}>{KVAL_RISIKO_TYPER[r.type].label}</span>
          </div>
          <h2 style={{ margin: 0, fontSize: 19, fontWeight: 600, letterSpacing: -0.01 }}>{r.navn}</h2>
        </div>
        <KvalModalClose onClose={onClose} />
      </div>
      <div style={{ padding: 22 }}>
        <div style={{ fontSize: 13, color: SK.ink, lineHeight: 1.55, marginBottom: 16 }}>{r.beskrivelse}</div>

        {/* Iboende → restrisiko */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 16 }}>
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontSize: 10, fontWeight: 600, color: SK.soft, letterSpacing: 0.04, textTransform: 'uppercase', marginBottom: 4 }}>Iboende</div>
            <RisikoBadge s={r.sann} k={r.kons} />
          </div>
          <span style={{ color: SK.soft }}>→ etter tiltak →</span>
          <div style={{ textAlign: 'center' }}>
            <div style={{ fontSize: 10, fontWeight: 600, color: SK.soft, letterSpacing: 0.04, textTransform: 'uppercase', marginBottom: 4 }}>Restrisiko</div>
            <RisikoBadge s={r.restSann} k={r.restKons} />
          </div>
          <div style={{ marginLeft: 'auto', textAlign: 'right' }}>
            <div style={{ fontSize: 10, fontWeight: 600, color: SK.soft, letterSpacing: 0.04, textTransform: 'uppercase' }}>Eier</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 4 }}>
              {eier && <Avatar initials={eier.i} color={eier.c} size={22} />}<span style={{ fontSize: 12.5, fontWeight: 600 }}>{eier?.n}</span>
            </div>
          </div>
        </div>

        {/* Tiltak */}
        <div style={{ fontSize: 11, fontWeight: 600, color: SK.soft, letterSpacing: 0.04, textTransform: 'uppercase', marginBottom: 8 }}>Risikoreduserende tiltak</div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 16 }}>
          {r.tiltak.map((t, i) => (
            <label key={i} style={{ display: 'flex', gap: 10, alignItems: 'center', padding: '8px 10px', background: SK.iceBlueLight, borderRadius: 8, cursor: 'pointer' }}>
              <input type="checkbox" checked={t.status === 'done'} onChange={() => toggleTiltak(i)} style={{ accentColor: SK.success, width: 16, height: 16 }} />
              <span style={{ fontSize: 12.5, textDecoration: t.status === 'done' ? 'line-through' : 'none', color: t.status === 'done' ? SK.soft : SK.ink }}>{t.t}</span>
            </label>
          ))}
        </div>

        <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
          <span style={{ fontSize: 11, color: SK.soft }}>Kilde:</span>
          <KildeChip kilde={r.kilde} go={go} />
        </div>
      </div>
    </KvalModal>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// AVVIK — register, arbeidsflyt, meld nytt (ISO 9001/14001 §10.2)
// ═══════════════════════════════════════════════════════════════════════════
const AVVIK_FLYT = ['registrert', 'under-behandling', 'tiltak', 'verifisering', 'lukket'];

function KvalAvvik({ go, avvik, setAvvik, oppg }) {
  const [search, setSearch] = React.useState('');
  const [fStatus, setFStatus] = React.useState('alle');
  const [fKat, setFKat] = React.useState('alle');
  const [sel, setSel] = React.useState(null);
  const [nyOpen, setNyOpen] = React.useState(false);

  const visible = avvik.filter(a =>
    (fStatus === 'alle' || (fStatus === 'apne' ? a.status !== 'lukket' : a.status === fStatus)) &&
    (fKat === 'alle' || a.kategori === fKat) &&
    (!search || a.tittel.toLowerCase().includes(search.toLowerCase()) || a.nr.toLowerCase().includes(search.toLowerCase())));

  const selA = sel ? avvik.find(a => a.id === sel) : null;

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      <Card padded={false}>
        <div style={{ padding: '12px 16px', display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap', borderBottom: '1px solid rgba(17,24,61,.08)' }}>
          <input className="ok-input ok-input--search" placeholder="Søk avvik eller nr…" value={search} onChange={e => setSearch(e.target.value)} style={{ maxWidth: 240 }} />
          <div style={{ display: 'flex', gap: 4 }}>
            {[['alle', 'Alle'], ['apne', 'Åpne'], ['registrert', 'Nye'], ['tiltak', 'Tiltak'], ['lukket', 'Lukket']].map(([k, l]) => (
              <button key={k} onClick={() => setFStatus(k)} className="ok-btn ok-btn--sm" style={{
                background: fStatus === k ? SK.ink : 'transparent', color: fStatus === k ? '#fff' : SK.ink,
                borderColor: fStatus === k ? SK.ink : 'rgba(17,24,61,.15)',
              }}>{l}</button>
            ))}
          </div>
          <select className="ok-input" value={fKat} onChange={e => setFKat(e.target.value)} style={{ maxWidth: 140, padding: '6px 10px' }}>
            <option value="alle">Alle kategorier</option>
            <option value="kvalitet">Kvalitet</option>
            <option value="miljø">Miljø</option>
            <option value="hms">HMS</option>
          </select>
          <Button size="sm" variant="accent" icon={I.plus} onClick={() => setNyOpen(true)} style={{ marginLeft: 'auto' }}>Meld avvik</Button>
        </div>

        <table className="ok-table">
          <thead>
            <tr>
              <th style={{ paddingLeft: 18 }}>Avvik</th>
              <th>Standard</th>
              <th>Alvor</th>
              <th style={{ width: 220 }}>Status / arbeidsflyt</th>
              <th>Ansvarlig</th>
              <th>Frist</th>
            </tr>
          </thead>
          <tbody>
            {visible.map(a => {
              const st = KVAL_AVVIK_STATUS[a.status];
              const al = KVAL_ALVOR[a.alvor];
              const ansv = TEAM[a.ansvarlig];
              const dager = kvalDagerTil(a.frist);
              return (
                <TR key={a.id} onClick={() => setSel(a.id)}>
                  <td style={{ paddingLeft: 18 }}>
                    <div style={{ fontSize: 10.5, fontWeight: 700, color: SK.soft, fontVariantNumeric: 'tabular-nums' }}>{a.nr}</div>
                    <div style={{ fontWeight: 600, fontSize: 12.5, marginTop: 2 }}>{a.tittel}</div>
                  </td>
                  <td><ISOTags std={a.std} klausul={a.klausul} mini /></td>
                  <td><span style={{ display: 'inline-block', padding: '2px 8px', borderRadius: 99, fontSize: 10, fontWeight: 600, background: al.farge + '22', color: al.farge }}>{al.label}</span></td>
                  <td><StatusStepper status={a.status} /></td>
                  <td>{ansv ? <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}><Avatar initials={ansv.i} color={ansv.c} size={20} /><span style={{ fontSize: 11.5 }}>{ansv.n.split(' ')[0]}</span></div> : '—'}</td>
                  <td style={{ fontSize: 11.5 }}>
                    {a.status === 'lukket' ? <span style={{ color: SK.soft }}>—</span> : (
                      <span style={{ fontWeight: 600, color: dager < 0 ? SK.coral : dager < 7 ? '#8e5a05' : SK.soft }}>
                        {dager < 0 ? `${Math.abs(dager)} d forfalt` : `${dager} d`}
                      </span>
                    )}
                  </td>
                </TR>
              );
            })}
          </tbody>
        </table>
      </Card>

      {selA && <AvvikDetailModal a={selA} go={go} onClose={() => setSel(null)} setAvvik={setAvvik} oppg={oppg} />}
      {nyOpen && <NyAvvikModal onClose={() => setNyOpen(false)} setAvvik={setAvvik} onSaved={(id) => { setNyOpen(false); setSel(id); }} />}
    </div>
  );
}

// Kompakt arbeidsflyt-stepper (5 prikker)
function StatusStepper({ status }) {
  const idx = AVVIK_FLYT.indexOf(status);
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 0 }}>
      {AVVIK_FLYT.map((s, i) => {
        const done = i <= idx;
        const cur = i === idx;
        const c = KVAL_AVVIK_STATUS[s].farge;
        return (
          <React.Fragment key={s}>
            <span title={KVAL_AVVIK_STATUS[s].label} style={{
              width: cur ? 11 : 8, height: cur ? 11 : 8, borderRadius: '50%', flexShrink: 0,
              background: done ? c : '#e2e4ee', border: cur ? `2px solid ${c}` : 'none',
              boxShadow: cur ? `0 0 0 2px ${c}33` : 'none',
            }} />
            {i < AVVIK_FLYT.length - 1 && <span style={{ width: 14, height: 2, background: i < idx ? KVAL_AVVIK_STATUS[AVVIK_FLYT[i + 1]].farge : '#e2e4ee' }} />}
          </React.Fragment>
        );
      })}
      <span style={{ marginLeft: 8, fontSize: 11, fontWeight: 600, color: KVAL_AVVIK_STATUS[status].farge, whiteSpace: 'nowrap' }}>{KVAL_AVVIK_STATUS[status].label}</span>
    </div>
  );
}

function AvvikDetailModal({ a, go, onClose, setAvvik, oppg }) {
  const al = KVAL_ALVOR[a.alvor];
  const ansv = TEAM[a.ansvarlig];
  const melder = TEAM[a.melder];
  const idx = AVVIK_FLYT.indexOf(a.status);
  const enhet = typeof ORG_UNITS !== 'undefined' ? ORG_UNITS.find(u => u.id === a.enhet) : null;
  const koblet = oppg.filter(o => o.kilde && o.kilde.type === 'avvik' && o.kilde.id === a.id);

  const setStatus = (ns) => setAvvik(list => list.map(x => x.id === a.id ? { ...x, status: ns } : x));
  const toggleTiltak = (i) => setAvvik(list => list.map(x => x.id !== a.id ? x : {
    ...x, tiltak: x.tiltak.map((t, j) => j === i ? { ...t, status: t.status === 'done' ? 'open' : 'done' } : t),
  }));

  return (
    <KvalModal onClose={onClose} width={620}>
      <div style={{ padding: 22, background: SK.iceBlueLight, display: 'flex', justifyContent: 'space-between', gap: 12 }}>
        <div style={{ minWidth: 0 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 6, flexWrap: 'wrap' }}>
            <span style={{ fontSize: 11, fontWeight: 700, color: SK.soft }}>{a.nr}</span>
            <ISOTags std={a.std} klausul={a.klausul} />
            <span style={{ padding: '2px 8px', borderRadius: 99, fontSize: 10, fontWeight: 600, background: al.farge + '22', color: al.farge }}>{al.label}</span>
          </div>
          <h2 style={{ margin: 0, fontSize: 19, fontWeight: 600, letterSpacing: -0.01 }}>{a.tittel}</h2>
        </div>
        <KvalModalClose onClose={onClose} />
      </div>

      <div style={{ padding: 22 }}>
        {/* Arbeidsflyt + handling */}
        <div style={{ padding: '12px 14px', border: '1px solid rgba(17,24,61,.1)', borderRadius: 10, marginBottom: 16 }}>
          <div style={{ fontSize: 10.5, fontWeight: 600, color: SK.soft, letterSpacing: 0.04, textTransform: 'uppercase', marginBottom: 10 }}>Arbeidsflyt</div>
          <StatusStepper status={a.status} />
          <div style={{ display: 'flex', gap: 8, marginTop: 14 }}>
            {idx > 0 && a.status !== 'lukket' && (
              <Button size="sm" variant="ghost" onClick={() => setStatus(AVVIK_FLYT[idx - 1])}>← Tilbake</Button>
            )}
            {a.status !== 'lukket' ? (
              <Button size="sm" variant="primary" onClick={() => setStatus(AVVIK_FLYT[idx + 1])}>
                Flytt til «{KVAL_AVVIK_STATUS[AVVIK_FLYT[idx + 1]].label}» →
              </Button>
            ) : (
              <Button size="sm" onClick={() => setStatus('verifisering')}>Gjenåpne</Button>
            )}
          </div>
        </div>

        {/* Detaljer */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 16 }}>
          <Cell label="Melder" value={melder ? <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><Avatar initials={melder.i} color={melder.c} size={18} />{melder.n.split(' ')[0]}</span> : a.melder} />
          <Cell label="Ansvarlig" value={ansv ? <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><Avatar initials={ansv.i} color={ansv.c} size={18} />{ansv.n.split(' ')[0]}</span> : a.ansvarlig} />
          <Cell label="Enhet" value={enhet ? enhet.name : a.enhet} />
          <Cell label="Frist" value={kvalFmtDato(a.frist)} />
        </div>

        <SubLabel>Beskrivelse</SubLabel>
        <div style={{ fontSize: 12.5, color: SK.ink, lineHeight: 1.55, marginBottom: 14 }}>{a.beskrivelse}</div>

        <SubLabel>Rotårsak <span style={{ fontWeight: 500, textTransform: 'none', color: SK.soft }}>· §10.2 a)</span></SubLabel>
        <div style={{ fontSize: 12.5, color: a.rotarsak ? SK.ink : SK.soft, lineHeight: 1.55, marginBottom: 14, fontStyle: a.rotarsak ? 'normal' : 'italic' }}>
          {a.rotarsak || 'Ikke fastsatt ennå — settes i «Under behandling».'}
        </div>

        <SubLabel>Korrigerende tiltak <span style={{ fontWeight: 500, textTransform: 'none', color: SK.soft }}>· §10.2 b)</span></SubLabel>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 14 }}>
          {a.tiltak.length === 0 ? (
            <div style={{ fontSize: 12, color: SK.soft, fontStyle: 'italic' }}>Ingen tiltak registrert ennå.</div>
          ) : a.tiltak.map((t, i) => (
            <label key={i} style={{ display: 'flex', gap: 10, alignItems: 'center', padding: '8px 10px', background: SK.iceBlueLight, borderRadius: 8, cursor: 'pointer' }}>
              <input type="checkbox" checked={t.status === 'done'} onChange={() => toggleTiltak(i)} style={{ accentColor: SK.success, width: 16, height: 16 }} />
              <span style={{ fontSize: 12.5, textDecoration: t.status === 'done' ? 'line-through' : 'none', color: t.status === 'done' ? SK.soft : SK.ink }}>{t.t}</span>
            </label>
          ))}
        </div>

        {koblet.length > 0 && (
          <>
            <SubLabel>Koblede oppgaver</SubLabel>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 4, marginBottom: 14 }}>
              {koblet.map(o => (
                <div key={o.id} style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 12 }}>
                  <span style={{ width: 6, height: 6, borderRadius: '50%', background: o.status === 'done' ? SK.success : SK.coral }} />
                  <span style={{ textDecoration: o.status === 'done' ? 'line-through' : 'none', color: o.status === 'done' ? SK.soft : SK.ink }}>{o.tittel}</span>
                </div>
              ))}
            </div>
          </>
        )}

        <div style={{ display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' }}>
          <span style={{ fontSize: 11, color: SK.soft }}>Kilde:</span>
          <KildeChip kilde={a.kilde} go={go} />
        </div>
      </div>
    </KvalModal>
  );
}

const Cell = ({ label, value }) => (
  <div style={{ padding: '8px 10px', borderRadius: 8, background: SK.iceBlueLight }}>
    <div style={{ fontSize: 10, fontWeight: 600, color: SK.soft, letterSpacing: 0.04, textTransform: 'uppercase' }}>{label}</div>
    <div style={{ fontSize: 12.5, fontWeight: 500, marginTop: 3, color: SK.ink }}>{value}</div>
  </div>
);
const SubLabel = ({ children }) => (
  <div style={{ fontSize: 11, fontWeight: 600, color: SK.soft, letterSpacing: 0.04, textTransform: 'uppercase', marginBottom: 7 }}>{children}</div>
);

// Meld nytt avvik
function NyAvvikModal({ onClose, setAvvik, onSaved }) {
  const [tittel, setTittel] = React.useState('');
  const [beskr, setBeskr] = React.useState('');
  const [std, setStd] = React.useState('9001');
  const [kat, setKat] = React.useState('kvalitet');
  const [alvor, setAlvor] = React.useState('mindre');
  const [ansv, setAnsv] = React.useState('KK');
  const [klausul, setKlausul] = React.useState('10.2');
  const [enhet, setEnhet] = React.useState('avd-lamb');
  const [frist, setFrist] = React.useState('2026-06-15');

  const lagre = () => {
    if (!tittel.trim()) return;
    const nr = `AVV-2026-${String(32 + Math.floor(Math.random() * 60)).padStart(3, '0')}`;
    const id = 'a-' + Date.now();
    const ny = {
      id, nr, tittel: tittel.trim(), kategori: kat, std: [std], klausul,
      alvor, status: 'registrert', melder: 'KS', ansvarlig: ansv, enhet,
      opprettet: '2026-05-21', frist, beskrivelse: beskr.trim() || '—',
      rotarsak: '', tiltak: [], kilde: { modul: 'kvalitet', label: 'Manuelt meldt' },
    };
    setAvvik(list => [ny, ...list]);
    onSaved(id);
  };

  const enheter = typeof ORG_UNITS !== 'undefined' ? ORG_UNITS.filter(u => u.id !== 'styret') : [];
  const fieldLbl = { fontSize: 11, fontWeight: 600, color: SK.soft, letterSpacing: 0.04, textTransform: 'uppercase', display: 'block', marginBottom: 5 };

  return (
    <KvalModal onClose={onClose} width={560}>
      <div style={{ padding: 22, display: 'flex', justifyContent: 'space-between', gap: 12, borderBottom: '1px solid rgba(17,24,61,.08)' }}>
        <div>
          <div style={{ fontSize: 11, fontWeight: 600, color: SK.soft, letterSpacing: 0.06, textTransform: 'uppercase' }}>Forbedring · §10.2</div>
          <h2 style={{ margin: '4px 0 0', fontSize: 19, fontWeight: 600 }}>Meld nytt avvik</h2>
        </div>
        <KvalModalClose onClose={onClose} />
      </div>
      <div style={{ padding: 22, display: 'flex', flexDirection: 'column', gap: 14 }}>
        <div>
          <label style={fieldLbl}>Tittel</label>
          <input className="ok-input" value={tittel} onChange={e => setTittel(e.target.value)} placeholder="Kort beskrivelse av avviket" autoFocus />
        </div>
        <div>
          <label style={fieldLbl}>Beskrivelse</label>
          <textarea className="ok-input" value={beskr} onChange={e => setBeskr(e.target.value)} rows={3} placeholder="Hva skjedde, hvor og når?" style={{ resize: 'vertical', fontFamily: 'inherit' }} />
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
          <div>
            <label style={fieldLbl}>Standard</label>
            <select className="ok-input" value={std} onChange={e => setStd(e.target.value)} style={{ padding: '8px 10px' }}>
              <option value="9001">ISO 9001 — Kvalitet</option>
              <option value="14001">ISO 14001 — Miljø</option>
            </select>
          </div>
          <div>
            <label style={fieldLbl}>Klausul</label>
            <input className="ok-input" value={klausul} onChange={e => setKlausul(e.target.value)} placeholder="f.eks. 8.5" />
          </div>
          <div>
            <label style={fieldLbl}>Kategori</label>
            <select className="ok-input" value={kat} onChange={e => setKat(e.target.value)} style={{ padding: '8px 10px' }}>
              <option value="kvalitet">Kvalitet</option>
              <option value="miljø">Miljø</option>
              <option value="hms">HMS</option>
            </select>
          </div>
          <div>
            <label style={fieldLbl}>Alvorlighet</label>
            <select className="ok-input" value={alvor} onChange={e => setAlvor(e.target.value)} style={{ padding: '8px 10px' }}>
              <option value="mindre">Mindre</option>
              <option value="vesentlig">Vesentlig</option>
              <option value="kritisk">Kritisk</option>
            </select>
          </div>
          <div>
            <label style={fieldLbl}>Ansvarlig</label>
            <select className="ok-input" value={ansv} onChange={e => setAnsv(e.target.value)} style={{ padding: '8px 10px' }}>
              {Object.values(TEAM).map(p => <option key={p.i} value={p.i}>{p.n}</option>)}
            </select>
          </div>
          <div>
            <label style={fieldLbl}>Frist</label>
            <input className="ok-input" type="date" value={frist} onChange={e => setFrist(e.target.value)} style={{ padding: '7px 10px' }} />
          </div>
          <div style={{ gridColumn: '1 / -1' }}>
            <label style={fieldLbl}>Enhet</label>
            <select className="ok-input" value={enhet} onChange={e => setEnhet(e.target.value)} style={{ padding: '8px 10px' }}>
              {enheter.map(u => <option key={u.id} value={u.id}>{u.name}</option>)}
            </select>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8, justifyContent: 'flex-end', marginTop: 4 }}>
          <Button variant="ghost" onClick={onClose}>Avbryt</Button>
          <Button variant="primary" onClick={lagre} disabled={!tittel.trim()}>Registrer avvik</Button>
        </div>
      </div>
    </KvalModal>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// REVISJONER — revisjonsprogram + ledelsens gjennomgang (§9.2 / §9.3)
// ═══════════════════════════════════════════════════════════════════════════
function KvalRevisjoner({ go }) {
  const statusTone = {
    planlagt:   { bg: '#e3edfb', fg: '#28589f', label: 'Planlagt' },
    oppfølging: { bg: '#fdeac8', fg: '#8e5a05', label: 'Oppfølging' },
    lukket:     { bg: '#dbeed8', fg: '#1b6a2e', label: 'Lukket' },
  };
  const sortert = [...KVAL_REVISJONER].sort((a, b) => new Date(a.dato) - new Date(b.dato));
  const planlagte = sortert.filter(r => r.status === 'planlagt').length;
  const apneFunn = KVAL_REVISJONER.reduce((s, r) => s + (r.funn ? r.funn.avvik : 0), 0);

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
        <Card padded><KPI label="Revisjoner 2026" value={KVAL_REVISJONER.length} sub="i programmet" /></Card>
        <Card padded><KPI label="Planlagt" value={planlagte} sub="gjenstår" /></Card>
        <Card padded><KPI label="Avvik fra revisjon" value={apneFunn} sub="totalt funnet" accent={apneFunn > 0} /></Card>
        <Card padded><KPI label="Neste eksterne" value="18. okt" sub="DNV resertifisering" accent /></Card>
      </div>

      <Card padded>
        <KvalSectionLabel sub="Internrevisjoner (§9.2), ledelsens gjennomgang (§9.3) og ekstern sertifiseringsrevisjon. Ledelsens gjennomgang dokumenteres som protokoll.">
          Revisjonsprogram 2026
        </KvalSectionLabel>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {sortert.map(r => {
            const t = statusTone[r.status];
            const rev = TEAM[r.revisor];
            const dager = kvalDagerTil(r.dato);
            return (
              <div key={r.id} style={{ display: 'flex', gap: 14, padding: 14, border: '1px solid rgba(17,24,61,.1)', borderRadius: 10, alignItems: 'center' }}>
                <div style={{ textAlign: 'center', flexShrink: 0, width: 48 }}>
                  <div style={{ fontSize: 20, fontWeight: 700, lineHeight: 1 }}>{new Date(r.dato).getDate()}</div>
                  <div style={{ fontSize: 10, color: SK.soft, textTransform: 'uppercase' }}>{['jan','feb','mar','apr','mai','jun','jul','aug','sep','okt','nov','des'][new Date(r.dato).getMonth()]}</div>
                </div>
                <div style={{ width: 1, alignSelf: 'stretch', background: 'rgba(17,24,61,.08)' }} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', marginBottom: 4 }}>
                    <span style={{ fontSize: 10.5, fontWeight: 600, color: SK.soft, textTransform: 'uppercase', letterSpacing: 0.04 }}>{KVAL_REVISJON_TYPER[r.type].label}</span>
                    <ISOTags std={r.std} mini />
                  </div>
                  <div style={{ fontSize: 14, fontWeight: 600 }}>{r.navn}</div>
                  <div style={{ fontSize: 11.5, color: SK.soft, marginTop: 2 }}>{r.omfang}</div>
                  {r.funn && (
                    <div style={{ display: 'flex', gap: 12, marginTop: 8 }}>
                      <FunnTall n={r.funn.avvik} label="avvik" farge={SK.coral} />
                      <FunnTall n={r.funn.obs} label="observasjoner" farge="#8e5a05" />
                      <FunnTall n={r.funn.forbedring} label="forbedringer" farge={SK.success} />
                    </div>
                  )}
                </div>
                <div style={{ textAlign: 'right', flexShrink: 0 }}>
                  <span style={{ display: 'inline-block', padding: '3px 10px', borderRadius: 99, fontSize: 11, fontWeight: 600, background: t.bg, color: t.fg }}>{t.label}</span>
                  <div style={{ fontSize: 11, color: SK.soft, marginTop: 6 }}>{rev ? `Revisor: ${rev.n.split(' ')[0]}` : 'Ekstern revisor'}</div>
                  {r.status === 'planlagt' && dager >= 0 && <div style={{ fontSize: 10.5, color: SK.soft, marginTop: 2 }}>om {dager} dager</div>}
                  {r.type === 'ledelse' && (
                    <Button size="sm" variant="ghost" style={{ marginTop: 6 }} onClick={() => go({ screen: 'protocols' })}>Protokoll {I.chevron}</Button>
                  )}
                </div>
              </div>
            );
          })}
        </div>
      </Card>
    </div>
  );
}
const FunnTall = ({ n, label, farge }) => (
  <div style={{ display: 'flex', alignItems: 'baseline', gap: 4 }}>
    <span style={{ fontSize: 14, fontWeight: 700, color: n > 0 ? farge : SK.soft }}>{n}</span>
    <span style={{ fontSize: 11, color: SK.soft }}>{label}</span>
  </div>
);

// ═══════════════════════════════════════════════════════════════════════════
// OPPGAVER — tiltaksspor (kobler avvik/risiko/revisjon)
// ═══════════════════════════════════════════════════════════════════════════
function KvalOppgaver({ go, oppg, setOppg }) {
  const [fStatus, setFStatus] = React.useState('apne');
  const [fStd, setFStd] = React.useState('alle');

  const kildeIkon = { avvik: 'Avvik', risiko: 'Risiko', revisjon: 'Revisjon', rutine: 'Rutine' };
  const prioTone = { høy: SK.coral, middels: '#8e5a05', lav: SK.soft };

  const visible = oppg.filter(o =>
    (fStatus === 'alle' || (fStatus === 'apne' ? o.status !== 'done' : fStatus === 'done' ? o.status === 'done' : o.status === fStatus)) &&
    (fStd === 'alle' || o.std.includes(fStd))
  ).sort((a, b) => {
    if ((a.status === 'done') !== (b.status === 'done')) return a.status === 'done' ? 1 : -1;
    return new Date(a.frist) - new Date(b.frist);
  });

  const cycle = (o) => {
    const next = o.status === 'open' ? 'in_progress' : o.status === 'in_progress' ? 'done' : 'open';
    setOppg(list => list.map(x => x.id === o.id ? { ...x, status: next } : x));
  };

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      <Card padded={false}>
        <div style={{ padding: '12px 16px', display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap', borderBottom: '1px solid rgba(17,24,61,.08)' }}>
          <div style={{ display: 'flex', gap: 4 }}>
            {[['apne', 'Åpne'], ['in_progress', 'Pågår'], ['done', 'Fullført'], ['alle', 'Alle']].map(([k, l]) => (
              <button key={k} onClick={() => setFStatus(k)} className="ok-btn ok-btn--sm" style={{
                background: fStatus === k ? SK.ink : 'transparent', color: fStatus === k ? '#fff' : SK.ink,
                borderColor: fStatus === k ? SK.ink : 'rgba(17,24,61,.15)',
              }}>{l}</button>
            ))}
          </div>
          <select className="ok-input" value={fStd} onChange={e => setFStd(e.target.value)} style={{ maxWidth: 160, padding: '6px 10px' }}>
            <option value="alle">Begge standarder</option>
            <option value="9001">ISO 9001</option>
            <option value="14001">ISO 14001</option>
          </select>
          <span style={{ marginLeft: 'auto', fontSize: 11.5, color: SK.soft }}>Klikk avkrysningsboks for å endre status</span>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column' }}>
          {visible.map((o, i) => {
            const ansv = TEAM[o.ansvarlig];
            const dager = kvalDagerTil(o.frist);
            const forfalt = o.status !== 'done' && dager < 0;
            const m = KVAL_MODUL_MAP.kvalitet;
            return (
              <div key={o.id} style={{
                display: 'flex', gap: 12, alignItems: 'center', padding: '12px 18px',
                borderTop: i ? '1px solid rgba(17,24,61,.06)' : 'none',
                background: o.status === 'done' ? 'rgba(8,96,79,.04)' : 'transparent',
              }}>
                <button onClick={() => cycle(o)} title="Endre status" style={{
                  width: 20, height: 20, borderRadius: 6, flexShrink: 0, cursor: 'pointer',
                  border: `2px solid ${o.status === 'done' ? SK.success : o.status === 'in_progress' ? '#8e5a05' : 'rgba(17,24,61,.3)'}`,
                  background: o.status === 'done' ? SK.success : o.status === 'in_progress' ? '#fdeac8' : SK.pureWhite,
                  display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#fff', padding: 0,
                }}>
                  {o.status === 'done' && <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3.5" strokeLinecap="round"><polyline points="20 6 9 17 4 12"/></svg>}
                  {o.status === 'in_progress' && <span style={{ width: 8, height: 8, borderRadius: 2, background: '#8e5a05' }} />}
                </button>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 500, lineHeight: 1.35, textDecoration: o.status === 'done' ? 'line-through' : 'none', color: o.status === 'done' ? SK.soft : SK.ink }}>{o.tittel}</div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 5, flexWrap: 'wrap' }}>
                    <ISOTags std={o.std} klausul={o.klausul} mini />
                    <span style={{ fontSize: 10.5, color: SK.soft, display: 'inline-flex', alignItems: 'center', gap: 4 }}>
                      <span style={{ width: 5, height: 5, borderRadius: '50%', background: prioTone[o.prioritet] }} /> {o.prioritet} prioritet
                    </span>
                    {o.kilde && (
                      <span style={{ fontSize: 10.5, color: SK.soft }}>· fra {kildeIkon[o.kilde.type]} <strong style={{ color: SK.ink, fontWeight: 600 }}>{o.kilde.label}</strong></span>
                    )}
                  </div>
                </div>
                {ansv && <Avatar initials={ansv.i} color={ansv.c} size={24} />}
                <div style={{ textAlign: 'right', flexShrink: 0, minWidth: 70 }}>
                  {o.status === 'done' ? (
                    <span style={{ fontSize: 11, color: SK.success, fontWeight: 600 }}>Fullført</span>
                  ) : (
                    <span style={{ fontSize: 11.5, fontWeight: 600, color: forfalt ? SK.coral : dager < 7 ? '#8e5a05' : SK.soft }}>
                      {forfalt ? `${Math.abs(dager)} d forfalt` : `${kvalFmtDato(o.frist).replace(' 2026', '')}`}
                    </span>
                  )}
                </div>
              </div>
            );
          })}
          {visible.length === 0 && <div style={{ padding: 28, textAlign: 'center', color: SK.soft, fontSize: 13 }}>Ingen oppgaver i dette filteret.</div>}
        </div>
      </Card>
    </div>
  );
}

Object.assign(window, {
  KvalModal, KvalModalClose, KvalRisiko, RisikoDetailModal,
  KvalAvvik, StatusStepper, AvvikDetailModal, NyAvvikModal,
  KvalRevisjoner, KvalOppgaver,
});
