// personal-screens.jsx — Personal-modul i Organisasjon: beriket ansattliste,
// personalendringer (på tvers av avdelinger og selskaper), og utgående
// kontrakter / kortere vikariater som krever oppfølging.

// ── Hjelpere ───────────────────────────────────────────────────────────────
const I_DAG_PE = new Date('2026-05-28');
const dagerTilPE = (iso) => {
  if (!iso) return null;
  return Math.round((new Date(iso) - I_DAG_PE) / 86400000);
};
const fmtDatoNo = (iso) => {
  if (!iso) return '—';
  const d = new Date(iso);
  const mnd = ['jan', 'feb', 'mar', 'apr', 'mai', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'des'];
  return `${d.getDate()}. ${mnd[d.getMonth()]} ${d.getFullYear()}`;
};
const fmtKrPE = (v) => v == null ? '—' : new Intl.NumberFormat('nb-NO').format(Math.round(v));

const findSelskapPE = (id) => OK_SELSKAPER.find(s => s.id === id);
const findEnhetPE = (id) => ORG_UNITS.find(u => u.id === id);

// ═══════════════════════════════════════════════════════════════════════════
// ANSATTE — beriket liste m/kontrakt + handlinger
// ═══════════════════════════════════════════════════════════════════════════
function EmployeesListMock({ onNyEndring }) {
  const [search, setSearch] = React.useState('');
  const [filtKontr, setFiltKontr] = React.useState('alle');
  const [filtSelsk, setFiltSelsk] = React.useState('alle');
  const [filtEnhet, setFiltEnhet] = React.useState('alle');

  const filtered = ALL_EMPLOYEES.filter(e => {
    if (search && !e.n.toLowerCase().includes(search.toLowerCase()) && !e.r.toLowerCase().includes(search.toLowerCase())) return false;
    if (filtKontr !== 'alle' && e.kontrakt !== filtKontr) return false;
    if (filtSelsk !== 'alle' && e.selskap !== filtSelsk) return false;
    if (filtEnhet !== 'alle' && e.enhet !== filtEnhet) return false;
    return true;
  });

  const utgaende = ALL_EMPLOYEES.filter(e => e.sluttDato && dagerTilPE(e.sluttDato) >= 0 && dagerTilPE(e.sluttDato) <= 120).length;

  return (
    <div>
      <div style={{
        display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap',
        padding: '12px 14px', background: SK.pureWhite, border: '1px solid rgba(17,24,61,.08)',
        borderRadius: 10, marginBottom: 14,
      }}>
        <input
          className="ok-input ok-input--search"
          placeholder="Søk ansatt eller rolle…"
          value={search}
          onChange={e => setSearch(e.target.value)}
          style={{ maxWidth: 240 }}
        />
        <select className="ok-input" value={filtSelsk} onChange={e => setFiltSelsk(e.target.value)} style={{ maxWidth: 180, padding: '6px 10px' }}>
          <option value="alle">Alle selskaper</option>
          {OK_SELSKAPER.map(s => <option key={s.id} value={s.id}>{s.navn}</option>)}
        </select>
        <select className="ok-input" value={filtEnhet} onChange={e => setFiltEnhet(e.target.value)} style={{ maxWidth: 220, padding: '6px 10px' }}>
          <option value="alle">Alle enheter</option>
          {ORG_UNITS.filter(u => u.id !== 'styret' && u.id !== 'dgl').map(u => <option key={u.id} value={u.id}>{u.name}</option>)}
        </select>
        <div style={{ display: 'flex', gap: 4 }}>
          {[['alle','Alle'],['fast','Fast'],['vikariat','Vikariat'],['midlertidig','Midlertidig'],['lærling','Lærling']].map(([k,l]) => (
            <button key={k} onClick={() => setFiltKontr(k)} className="ok-btn ok-btn--sm" style={{
              background: filtKontr === k ? SK.ink : 'transparent',
              color: filtKontr === k ? '#fff' : SK.ink,
              borderColor: filtKontr === k ? SK.ink : 'rgba(17,24,61,.15)',
            }}>{l}</button>
          ))}
        </div>
        <span style={{ marginLeft: 'auto', fontSize: 11.5, color: SK.soft }}>
          {filtered.length} av {ALL_EMPLOYEES.length} ansatte
          {utgaende > 0 && <> · <span style={{ color: SK.coral, fontWeight: 600 }}>{utgaende} med utgående kontrakt</span></>}
        </span>
      </div>

      <Card padded={false}>
        <table className="ok-table">
          <thead>
            <tr>
              <th style={{ paddingLeft: 18 }}>Ansatt</th>
              <th>Rolle</th>
              <th>Selskap</th>
              <th>Enhet</th>
              <th>Kontrakt</th>
              <th style={{ textAlign: 'right' }}>Stilling</th>
              <th>Utløper</th>
              <th style={{ width: 70 }}></th>
            </tr>
          </thead>
          <tbody>
            {filtered.map(e => {
              const dager = e.sluttDato ? dagerTilPE(e.sluttDato) : null;
              const farlig = dager != null && dager <= 90;
              const obs = dager != null && dager > 90 && dager <= 180;
              const kt = KONTRAKT_TYPER[e.kontrakt] || KONTRAKT_TYPER.fast;
              const selsk = findSelskapPE(e.selskap);
              const enhet = findEnhetPE(e.enhet);
              const leder = e.leder ? TEAM[e.leder] : null;
              return (
                <tr key={e.i}>
                  <td style={{ paddingLeft: 18 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                      <Avatar initials={e.i} color={e.c} />
                      <div>
                        <div style={{ fontWeight: 600, fontSize: 13 }}>{e.n}</div>
                        <div style={{ fontSize: 11, color: SK.soft }}>
                          Leder: {leder ? leder.n : '—'}
                        </div>
                      </div>
                    </div>
                  </td>
                  <td style={{ fontSize: 12.5 }}>{e.r}</td>
                  <td style={{ fontSize: 12 }}>
                    <span style={{
                      display: 'inline-block', padding: '2px 8px', borderRadius: 4,
                      background: (selsk?.brand || SK.lightBlue) + '33',
                      color: SK.ink, fontSize: 11, fontWeight: 600,
                    }}>{selsk?.kort || '—'}</span>
                  </td>
                  <td style={{ fontSize: 12, color: SK.ink }}>{enhet?.name || '—'}</td>
                  <td>
                    <span style={{
                      display: 'inline-block', padding: '2px 8px', borderRadius: 99,
                      background: kt.farge + '22', color: kt.farge,
                      fontSize: 11, fontWeight: 600,
                    }}>{kt.label}</span>
                  </td>
                  <td style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums', fontWeight: 600 }}>{e.stilling} %</td>
                  <td style={{ fontSize: 11.5 }}>
                    {e.sluttDato ? (
                      <div>
                        <div style={{ fontWeight: 500 }}>{fmtDatoNo(e.sluttDato)}</div>
                        <div style={{
                          fontSize: 10.5, marginTop: 1,
                          color: farlig ? SK.coral : obs ? '#8e5a05' : SK.soft,
                          fontWeight: farlig || obs ? 600 : 500,
                        }}>
                          {dager < 0 ? `${Math.abs(dager)} dgr utløpt` : dager === 0 ? 'utløper i dag' : `${dager} dgr igjen`}
                        </div>
                      </div>
                    ) : <span style={{ color: SK.soft }}>—</span>}
                  </td>
                  <td onClick={(ev) => ev.stopPropagation()}>
                    <Button variant="ghost" size="sm" onClick={() => onNyEndring(e.i)}>Endre →</Button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// PERSONALENDRINGER — saksliste med detalj-panel
// ═══════════════════════════════════════════════════════════════════════════
function PersonalEndringerTabMock({ onNyEndring }) {
  const [filter, setFilter] = React.useState('apne');
  const [openId, setOpenId] = React.useState(null);

  const sakerApne = PERSONAL_ENDRINGER.filter(p => p.status.startsWith('venter-'));
  const sakerUtkast = PERSONAL_ENDRINGER.filter(p => p.status === 'utkast');
  const sakerFerdig = PERSONAL_ENDRINGER.filter(p => p.status === 'godkjent' || p.status === 'effektuert');
  const sakerAvvist = PERSONAL_ENDRINGER.filter(p => p.status === 'avvist');

  const filtered = (
    filter === 'apne' ? sakerApne :
    filter === 'utkast' ? sakerUtkast :
    filter === 'ferdig' ? sakerFerdig :
    filter === 'avvist' ? sakerAvvist :
    PERSONAL_ENDRINGER
  );

  const valgt = openId ? PERSONAL_ENDRINGER.find(p => p.id === openId) : null;

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 14 }}>
        <Card padded><KPI label="Åpne saker" value={sakerApne.length} sub="Venter på godkjenning" accent={sakerApne.length > 0} /></Card>
        <Card padded><KPI label="Utkast" value={sakerUtkast.length} sub="Ikke sendt enda" /></Card>
        <Card padded><KPI label="Effektuert · 14d" value={sakerFerdig.length} sub="Postert i Finago/HR" /></Card>
        <Card padded><KPI label="Avvist · 14d" value={sakerAvvist.length} sub="Trukket eller stoppet" /></Card>
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14 }}>
        <div style={{ display: 'flex', gap: 4, background: SK.pureWhite, border: '1px solid rgba(17,24,61,.1)', borderRadius: 99, padding: 3 }}>
          {[
            { id: 'apne',  label: `Åpne (${sakerApne.length})` },
            { id: 'utkast', label: `Utkast (${sakerUtkast.length})` },
            { id: 'ferdig', label: 'Godkjent/effektuert' },
            { id: 'avvist', label: 'Avvist' },
            { id: 'alle',  label: 'Alle' },
          ].map(t => (
            <button
              key={t.id}
              onClick={() => setFilter(t.id)}
              style={{
                padding: '5px 12px', borderRadius: 99, border: 0, cursor: 'pointer', fontFamily: 'inherit',
                background: filter === t.id ? SK.ink : 'transparent',
                color: filter === t.id ? SK.pureWhite : SK.ink,
                fontWeight: filter === t.id ? 600 : 500, fontSize: 11.5,
              }}
            >{t.label}</button>
          ))}
        </div>
        <div style={{ marginLeft: 'auto', display: 'flex', gap: 8 }}>
          <Button variant="ghost">Regler & godkjenningsstier</Button>
          <Button variant="primary" icon={I.plus} onClick={() => onNyEndring()}>Ny personalendring</Button>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: valgt ? '1.45fr 1fr' : '1fr', gap: 14, alignItems: 'flex-start' }}>
        <Card padded={false}>
          <table className="ok-table">
            <thead>
              <tr>
                <th style={{ width: 110 }}>Sak</th>
                <th>Ansatt</th>
                <th>Type</th>
                <th>Fra → Til</th>
                <th>Gjelder fra</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(p => {
                const emp = findEmp(p.person);
                const fraSel = findSelskapPE(p.fraSelskap);
                const tilSel = findSelskapPE(p.tilSelskap);
                const fraEnh = findEnhetPE(p.fraEnhet);
                const tilEnh = findEnhetPE(p.tilEnhet);
                const typeInfo = ENDRING_TYPER[p.type];
                const krysser = p.fraSelskap !== p.tilSelskap;
                return (
                  <tr key={p.id} onClick={() => setOpenId(p.id)} style={{ background: openId === p.id ? SK.iceBlueLight : 'inherit' }}>
                    <td style={{ fontVariantNumeric: 'tabular-nums', color: SK.soft, fontWeight: 600, fontSize: 11.5 }}>{p.nr}</td>
                    <td>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <Avatar initials={p.person} color={emp?.c || SK.lightBlue} size={24} />
                        <div>
                          <div style={{ fontWeight: 600, fontSize: 12.5 }}>{p.personNavn}</div>
                          <div style={{ fontSize: 10.5, color: SK.soft }}>{emp?.r}</div>
                        </div>
                      </div>
                    </td>
                    <td>
                      <span style={{
                        display: 'inline-flex', alignItems: 'center', gap: 4,
                        padding: '2px 8px', borderRadius: 4,
                        background: typeInfo.farge + '22', color: typeInfo.farge,
                        fontSize: 11, fontWeight: 600,
                      }}>
                        <span style={{ fontWeight: 700 }}>{typeInfo.ikon}</span>
                        {typeInfo.label}
                      </span>
                    </td>
                    <td style={{ fontSize: 11.5 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                        <span>{fraEnh?.name}</span>
                        {krysser && <span style={{ fontSize: 9.5, color: SK.coral, fontWeight: 700, letterSpacing: 0.04, background: SK.lightCoral, padding: '1px 5px', borderRadius: 3 }}>{fraSel?.kort}</span>}
                      </div>
                      <div style={{ color: SK.soft, marginTop: 1, display: 'flex', alignItems: 'center', gap: 6 }}>
                        → {tilEnh?.name}
                        {krysser && <span style={{ fontSize: 9.5, color: SK.coral, fontWeight: 700, letterSpacing: 0.04, background: SK.lightCoral, padding: '1px 5px', borderRadius: 3 }}>{tilSel?.kort}</span>}
                      </div>
                    </td>
                    <td style={{ fontSize: 11.5 }}>{fmtDatoNo(p.gjelderFra)}</td>
                    <td><Pill status={ENDRING_STATUS[p.status].pill}>{ENDRING_STATUS[p.status].label}</Pill></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </Card>

        {valgt && <EndringDetalj sak={valgt} onClose={() => setOpenId(null)} />}
      </div>

      <Card title="Regler · godkjenningsstier" style={{ marginTop: 14 }} padded={false}>
        <table className="ok-table">
          <thead>
            <tr><th style={{ width: '40%', paddingLeft: 18 }}>Regel</th><th>Krav</th></tr>
          </thead>
          <tbody>
            {PERSONAL_REGLER.map(r => (
              <tr key={r.id} style={{ cursor: 'default' }}>
                <td style={{ fontWeight: 600, paddingLeft: 18 }}>{r.regel}</td>
                <td style={{ color: SK.soft }}>{r.krav}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

// ── Sak-detalj-panel ──
function EndringDetalj({ sak, onClose }) {
  const typeInfo = ENDRING_TYPER[sak.type];
  const emp = findEmp(sak.person);
  const fraSel = findSelskapPE(sak.fraSelskap);
  const tilSel = findSelskapPE(sak.tilSelskap);
  const fraEnh = findEnhetPE(sak.fraEnhet);
  const tilEnh = findEnhetPE(sak.tilEnhet);
  const krysser = sak.fraSelskap !== sak.tilSelskap;

  // Bygg godkjenningssti-komponent (kopiert mønster fra Økonomi)
  return (
    <Card title={sak.nr} action={
      <Button variant="ghost" size="sm" onClick={onClose}>Lukk ×</Button>
    }>
      <div style={{ fontSize: 12.5, lineHeight: 1.5 }}>
        {/* Person + type */}
        <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px', background: SK.iceBlueLight, borderRadius: 8, marginBottom: 14 }}>
          <Avatar initials={sak.person} color={emp?.c || SK.lightBlue} size={36} />
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 14, fontWeight: 600 }}>{sak.personNavn}</div>
            <div style={{ fontSize: 11, color: SK.soft }}>{emp?.r}</div>
          </div>
          <span style={{
            padding: '4px 10px', borderRadius: 99,
            background: typeInfo.farge + '22', color: typeInfo.farge,
            fontSize: 11, fontWeight: 600,
          }}>{typeInfo.ikon} {typeInfo.label}</span>
        </div>

        {/* Fra → Til */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 24px 1fr', gap: 8, marginBottom: 14, alignItems: 'center' }}>
          <div style={{ padding: 10, border: '1px solid rgba(17,24,61,.1)', borderRadius: 8 }}>
            <div style={{ fontSize: 10, color: SK.soft, fontWeight: 600, letterSpacing: 0.05, textTransform: 'uppercase' }}>Fra</div>
            <div style={{ fontWeight: 600, marginTop: 4 }}>{fraEnh?.name}</div>
            <div style={{ fontSize: 11, color: SK.soft }}>{fraSel?.navn}</div>
          </div>
          <div style={{ textAlign: 'center', color: krysser ? SK.coral : SK.soft, fontSize: 18, fontWeight: 700 }}>→</div>
          <div style={{ padding: 10, border: `1px solid ${krysser ? SK.coral : 'rgba(17,24,61,.1)'}`, borderRadius: 8, background: krysser ? SK.lightCoral + '50' : 'transparent' }}>
            <div style={{ fontSize: 10, color: SK.soft, fontWeight: 600, letterSpacing: 0.05, textTransform: 'uppercase' }}>Til</div>
            <div style={{ fontWeight: 600, marginTop: 4 }}>{tilEnh?.name}</div>
            <div style={{ fontSize: 11, color: SK.soft }}>{tilSel?.navn}{krysser && <span style={{ marginLeft: 6, fontWeight: 700, color: SK.coral }}>· KRYSSER SELSKAP</span>}</div>
          </div>
        </div>

        {/* Detalj-grid */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8, marginBottom: 14 }}>
          {sak.nyTittel && <DetalCell label="Ny tittel" value={sak.nyTittel} />}
          {sak.gammelStilling !== sak.nyStilling
            ? <DetalCell label="Stilling" value={`${sak.gammelStilling}% → ${sak.nyStilling}%`} accent />
            : <DetalCell label="Stilling" value={`${sak.nyStilling}%`} />}
          {sak.gammelLonn && sak.nyLonn && sak.gammelLonn !== sak.nyLonn
            ? <DetalCell label="Månedslønn" value={`${fmtKrPE(sak.gammelLonn)} → ${fmtKrPE(sak.nyLonn)}`} accent />
            : sak.nyLonn ? <DetalCell label="Månedslønn" value={`${fmtKrPE(sak.nyLonn)} kr`} /> : null}
          <DetalCell label="Gjelder fra" value={fmtDatoNo(sak.gjelderFra)} />
          {sak.forlengeTil && <DetalCell label="Ny sluttdato" value={`${fmtDatoNo(sak.gammelSlutt)} → ${fmtDatoNo(sak.forlengeTil)}`} accent />}
          {sak.nyKontrakt && <DetalCell label="Ny kontrakttype" value={KONTRAKT_TYPER[sak.nyKontrakt]?.label} accent />}
          {sak.splittAllok && (
            <DetalCell label="Allokering" value={
              Object.entries(sak.splittAllok).map(([id, pct]) => `${findEnhetPE(id)?.name}: ${pct}%`).join(' · ')
            } accent />
          )}
        </div>

        <div style={{ background: SK.iceBlueLight, padding: 12, borderRadius: 8, marginBottom: 14 }}>
          <div style={{ fontSize: 10.5, color: SK.soft, fontWeight: 600, letterSpacing: 0.05, textTransform: 'uppercase' }}>Begrunnelse</div>
          <div style={{ marginTop: 4, fontSize: 12.5, lineHeight: 1.45 }}>{sak.begrunnelse}</div>
        </div>

        {sak.konsekvenser?.length > 0 && (
          <div style={{ marginBottom: 14 }}>
            <div style={{ fontSize: 10.5, color: SK.soft, fontWeight: 600, letterSpacing: 0.05, textTransform: 'uppercase', marginBottom: 6 }}>Konsekvenser</div>
            <ul style={{ margin: 0, paddingLeft: 18, fontSize: 12, lineHeight: 1.5, color: SK.ink }}>
              {sak.konsekvenser.map((k, i) => <li key={i}>{k}</li>)}
            </ul>
          </div>
        )}

        <div style={{ fontSize: 10.5, color: SK.soft, fontWeight: 600, letterSpacing: 0.05, textTransform: 'uppercase', marginBottom: 10 }}>Godkjenningssti</div>
        <Godkjenningstrapp steg={sak.godkjenningssti} />

        {sak.avvisGrunn && (
          <div style={{ marginTop: 14, padding: 12, background: SK.lightCoral, borderRadius: 8, fontSize: 12, color: '#a01a25' }}>
            <b>Avvist:</b> {sak.avvisGrunn}
          </div>
        )}
        {sak.hrKvittering && (
          <div style={{ marginTop: 14, padding: 10, background: '#dbeed8', borderRadius: 8, fontSize: 12, color: SK.success, fontWeight: 600 }}>
            ✓ {sak.hrKvittering}
          </div>
        )}

        {sak.status.startsWith('venter-') && (
          <div style={{ display: 'flex', gap: 8, marginTop: 14, paddingTop: 14, borderTop: '1px solid rgba(17,24,61,.08)' }}>
            <Button variant="primary">Godkjenn</Button>
            <Button>Be om endring</Button>
            <Button variant="accent" style={{ marginLeft: 'auto' }}>Avvis</Button>
          </div>
        )}
      </div>
    </Card>
  );
}

const DetalCell = ({ label, value, accent }) => (
  <div style={{ padding: '8px 10px', borderRadius: 6, background: accent ? '#fdeac850' : SK.iceBlueLight, border: accent ? '1px solid #fdeac8' : 'none' }}>
    <div style={{ fontSize: 10, fontWeight: 600, color: SK.soft, letterSpacing: 0.04, textTransform: 'uppercase' }}>{label}</div>
    <div style={{ fontSize: 12.5, fontWeight: 600, marginTop: 3, color: SK.ink }}>{value}</div>
  </div>
);

// Godkjenningstrapp (egen variant for personal)
function Godkjenningstrapp({ steg }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      {steg.map((s, i) => {
        const done = s.state === 'godkjent';
        const reject = s.state === 'avvist';
        const wait = s.state === 'venter';
        const queue = s.state === 'kø';
        return (
          <div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 10 }}>
            <div style={{
              width: 22, height: 22, borderRadius: '50%', flexShrink: 0,
              background: done ? SK.success : reject ? SK.coral : wait ? SK.warn : SK.lightBlue,
              color: queue ? SK.soft : '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 11, fontWeight: 700,
            }}>{done ? '✓' : reject ? '×' : wait ? '…' : i + 1}</div>
            <div style={{ flex: 1, fontSize: 12, lineHeight: 1.4 }}>
              <div style={{ fontWeight: 600, color: SK.ink }}>{s.rolle}</div>
              <div style={{ color: SK.soft, marginTop: 1 }}>
                {done && s.av === 'sys' ? `Automatisk · ${s.tid}`
                  : done ? `${TEAM[s.av]?.n || s.av} · ${s.tid}`
                  : reject ? `Avvist av ${TEAM[s.av]?.n || s.av} · ${s.tid}`
                  : wait ? `Venter på handling${s.grunn ? ` · ${s.grunn}` : ''}`
                  : 'I kø'}
              </div>
            </div>
          </div>
        );
      })}
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// UTGÅENDE KONTRAKTER — tidslinje + tabell
// ═══════════════════════════════════════════════════════════════════════════
function UtgaaendeKontrakterTabMock({ onNyEndring }) {
  const utgaaende = ALL_EMPLOYEES
    .filter(e => e.sluttDato && dagerTilPE(e.sluttDato) >= 0 && dagerTilPE(e.sluttDato) <= 365)
    .sort((a, b) => new Date(a.sluttDato) - new Date(b.sluttDato));

  const innen30 = utgaaende.filter(e => dagerTilPE(e.sluttDato) <= 30);
  const innen90 = utgaaende.filter(e => dagerTilPE(e.sluttDato) > 30 && dagerTilPE(e.sluttDato) <= 90);
  const innen180 = utgaaende.filter(e => dagerTilPE(e.sluttDato) > 90 && dagerTilPE(e.sluttDato) <= 180);
  const vikariater = utgaaende.filter(e => e.kontrakt === 'vikariat');
  const korteVikar = ALL_EMPLOYEES.filter(e => e.kontrakt === 'vikariat' && e.startet && e.sluttDato
    && (new Date(e.sluttDato) - new Date(e.startet)) / 86400000 < 365).length;

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 14 }}>
        <Card padded><KPI label="Kritisk · < 30 dgr" value={innen30.length} sub="Krever handling nå" accent={innen30.length > 0} /></Card>
        <Card padded><KPI label="Oppfølging · 30–90 dgr" value={innen90.length} sub="Begynn samtaler" accent={innen90.length > 0} /></Card>
        <Card padded><KPI label="Planlegging · 90–180 dgr" value={innen180.length} sub="Vurder forlengelse" /></Card>
        <Card padded><KPI label="Korte vikariater" value={korteVikar} sub="< 12 mnd varighet" /></Card>
      </div>

      {/* Tidslinje */}
      <Card title="Tidslinje · neste 12 måneder">
        <div style={{ marginTop: 14, position: 'relative', height: 64, padding: '0 8px' }}>
          {/* Akse */}
          <div style={{ position: 'absolute', left: 8, right: 8, top: 30, height: 2, background: SK.iceBlue, borderRadius: 99 }} />
          {/* I dag */}
          <div style={{ position: 'absolute', left: 8, top: 18, bottom: 8, width: 2, background: SK.ink }} />
          <div style={{ position: 'absolute', left: 12, top: 6, fontSize: 10, fontWeight: 600, color: SK.ink }}>I dag</div>
          {/* Markører */}
          {[1, 3, 6, 9, 12].map(m => {
            const pct = (m / 12) * 100;
            return (
              <React.Fragment key={m}>
                <div style={{ position: 'absolute', left: `${pct}%`, top: 28, width: 1, height: 6, background: SK.soft }} />
                <div style={{ position: 'absolute', left: `${pct}%`, top: 40, fontSize: 9.5, color: SK.soft, transform: 'translateX(-50%)' }}>
                  +{m} mnd
                </div>
              </React.Fragment>
            );
          })}
          {/* Personer */}
          {utgaaende.map((e, i) => {
            const dager = dagerTilPE(e.sluttDato);
            const pct = (dager / 365) * 100;
            const farge = dager <= 30 ? SK.coral : dager <= 90 ? SK.warn : SK.success;
            return (
              <div key={e.i} title={`${e.n} — ${fmtDatoNo(e.sluttDato)}`} style={{
                position: 'absolute', left: `calc(${pct}% - 11px)`, top: 14,
                width: 22, height: 22, borderRadius: '50%',
                background: e.c, color: SK.ink, fontSize: 10, fontWeight: 700,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                border: `2px solid ${farge}`, cursor: 'pointer',
                boxShadow: '0 1px 3px rgba(17,24,61,.2)',
              }}>{e.i}</div>
            );
          })}
        </div>
      </Card>

      {/* Tabell */}
      <Card title="Ansatte med utløpende kontrakter" action={
        <div style={{ display: 'flex', gap: 6, fontSize: 11, color: SK.soft, alignItems: 'center' }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
            <span style={{ width: 8, height: 8, borderRadius: '50%', background: SK.coral }} /> ≤ 30 dgr
          </span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, marginLeft: 8 }}>
            <span style={{ width: 8, height: 8, borderRadius: '50%', background: SK.warn }} /> 30–90 dgr
          </span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, marginLeft: 8 }}>
            <span style={{ width: 8, height: 8, borderRadius: '50%', background: SK.success }} /> &gt; 90 dgr
          </span>
        </div>
      } padded={false} style={{ marginTop: 14 }}>
        <table className="ok-table">
          <thead>
            <tr>
              <th style={{ paddingLeft: 18 }}>Ansatt</th>
              <th>Kontrakt</th>
              <th>Enhet · selskap</th>
              <th>Startet</th>
              <th>Utløper</th>
              <th>Bakgrunn</th>
              <th style={{ width: 140 }}></th>
            </tr>
          </thead>
          <tbody>
            {utgaaende.map(e => {
              const dager = dagerTilPE(e.sluttDato);
              const kt = KONTRAKT_TYPER[e.kontrakt];
              const sel = findSelskapPE(e.selskap);
              const enh = findEnhetPE(e.enhet);
              const farlig = dager <= 30;
              const obs = dager > 30 && dager <= 90;
              const varighetMnd = Math.round((new Date(e.sluttDato) - new Date(e.startet)) / 86400000 / 30);
              return (
                <tr key={e.i} style={{ cursor: 'default' }}>
                  <td style={{ paddingLeft: 18 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                      <Avatar initials={e.i} color={e.c} size={28} />
                      <div>
                        <div style={{ fontWeight: 600, fontSize: 13 }}>{e.n}</div>
                        <div style={{ fontSize: 11, color: SK.soft }}>{e.r}</div>
                      </div>
                    </div>
                  </td>
                  <td>
                    <span style={{
                      display: 'inline-block', padding: '2px 8px', borderRadius: 99,
                      background: kt.farge + '22', color: kt.farge,
                      fontSize: 11, fontWeight: 600,
                    }}>{kt.label}</span>
                    {varighetMnd < 12 && (
                      <div style={{ fontSize: 10, color: SK.coral, fontWeight: 600, marginTop: 3 }}>
                        Kort: {varighetMnd} mnd
                      </div>
                    )}
                  </td>
                  <td style={{ fontSize: 12 }}>
                    <div>{enh?.name}</div>
                    <div style={{ fontSize: 11, color: SK.soft }}>{sel?.kort}</div>
                  </td>
                  <td style={{ fontSize: 11.5, color: SK.soft }}>{fmtDatoNo(e.startet)}</td>
                  <td>
                    <div style={{ fontWeight: 600, fontSize: 12.5 }}>{fmtDatoNo(e.sluttDato)}</div>
                    <div style={{
                      fontSize: 11, marginTop: 1, fontWeight: 600,
                      color: farlig ? SK.coral : obs ? '#8e5a05' : SK.success,
                    }}>
                      {dager === 0 ? 'I dag' : `${dager} dgr igjen`}
                    </div>
                  </td>
                  <td style={{ fontSize: 11.5, color: SK.soft, lineHeight: 1.4, maxWidth: 280 }}>
                    {e.vikarFor ? <>Vikar for <b style={{ color: SK.ink }}>{e.vikarFor}</b></> : e.begrunn || '—'}
                  </td>
                  <td onClick={(ev) => ev.stopPropagation()}>
                    <Button variant={farlig ? 'primary' : 'ghost'} size="sm" onClick={() => onNyEndring(e.i)}>Følg opp →</Button>
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// NY PERSONALENDRING — 3-stegs modal
// ═══════════════════════════════════════════════════════════════════════════
function NyPersonalendringModalMock({ open, onClose, prefyllInitials }) {
  const [step, setStep] = React.useState(1);
  const [empI, setEmpI] = React.useState(prefyllInitials || ALL_EMPLOYEES[0]?.i);
  const [type, setType] = React.useState('overflytting');
  const [tilEnhet, setTilEnhet] = React.useState('avd-holm');
  const [tilSelskap, setTilSelskap] = React.useState('okm');
  const [nyStilling, setNyStilling] = React.useState(100);
  const [nyLonn, setNyLonn] = React.useState(0);
  const [gjelderFra, setGjelderFra] = React.useState('2026-08-01');
  const [forlengeTil, setForlengeTil] = React.useState('2027-06-30');
  const [begrunnelse, setBegrunnelse] = React.useState('');

  React.useEffect(() => {
    if (open) {
      if (prefyllInitials) setEmpI(prefyllInitials);
      const emp = findEmp(prefyllInitials || empI);
      if (emp) {
        setNyStilling(emp.stilling);
        setNyLonn(emp.manedslonn);
        setTilEnhet(emp.enhet);
        setTilSelskap(emp.selskap);
      }
    } else {
      setStep(1);
    }
  }, [open, prefyllInitials]);

  const emp = findEmp(empI);
  if (!open || !emp) return null;

  // Bygg godkjenningssti basert på type + krysser-flagg
  const krysser = tilSelskap !== emp.selskap;
  const flyttetEnhet = tilEnhet !== emp.enhet;
  const tilEnh = findEnhetPE(tilEnhet);
  const fraEnh = findEnhetPE(emp.enhet);
  const fraSel = findSelskapPE(emp.selskap);
  const tilSel = findSelskapPE(tilSelskap);
  const lonnEndring = nyLonn !== emp.manedslonn ? Math.abs(nyLonn - emp.manedslonn) / emp.manedslonn : 0;
  const stillingEndring = nyStilling !== emp.stilling;

  const godkjStegFunc = () => {
    const sti = [];
    sti.push({ rolle: `Nærmeste leder (fra) · ${fraEnh?.name}`, who: emp.leder });
    if (flyttetEnhet) sti.push({ rolle: `Nærmeste leder (til) · ${tilEnh?.name}`, who: tilEnh?.leader });
    if (krysser || lonnEndring > 0.05 || stillingEndring || type === 'fast-tilsetting' || type === 'omdisponering') {
      sti.push({ rolle: `Daglig leder · ${fraSel?.navn}`, who: 'KS' });
    }
    if (krysser) sti.push({ rolle: `Daglig leder · ${tilSel?.navn}`, who: 'KS' });
    sti.push({ rolle: 'HR · Hanne Myhre', who: 'HM' });
    return sti;
  };

  return (
    <div style={{
      position: 'fixed', inset: 0, background: 'rgba(17,24,61,.55)', zIndex: 200,
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 24,
    }} onClick={onClose}>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: SK.pureWhite, borderRadius: 14, width: '100%', maxWidth: 720,
        boxShadow: '0 20px 60px rgba(17,24,61,.4)', overflow: 'hidden',
        maxHeight: '90vh', display: 'flex', flexDirection: 'column',
      }}>
        <div style={{ padding: '18px 22px', borderBottom: '1px solid rgba(17,24,61,.08)', display: 'flex', alignItems: 'center' }}>
          <div>
            <div style={{ fontSize: 10.5, color: SK.soft, fontWeight: 600, letterSpacing: 0.05, textTransform: 'uppercase' }}>Ny personalendring</div>
            <h2 style={{ margin: '4px 0 0', fontSize: 18, fontWeight: 600 }}>
              Steg {step} av 3 · {step === 1 ? 'Ansatt & type' : step === 2 ? 'Detaljer & begrunnelse' : 'Forhåndsvis & send'}
            </h2>
          </div>
          <Button variant="ghost" size="icon" onClick={onClose} style={{ marginLeft: 'auto' }}>×</Button>
        </div>

        <div style={{ padding: 22, overflowY: 'auto', flex: 1 }}>
          {step === 1 && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <div>
                <label style={{ fontSize: 11, color: SK.soft, fontWeight: 600, letterSpacing: 0.05, textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>
                  Ansatt {prefyllInitials && '(prefylt fra ansattliste)'}
                </label>
                <select className="ok-input" value={empI} onChange={e => {
                  setEmpI(e.target.value);
                  const ny = findEmp(e.target.value);
                  if (ny) { setNyStilling(ny.stilling); setNyLonn(ny.manedslonn); setTilEnhet(ny.enhet); setTilSelskap(ny.selskap); }
                }}>
                  {ALL_EMPLOYEES.map(p => <option key={p.i} value={p.i}>{p.n} · {p.r}</option>)}
                </select>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 10, padding: 10, background: SK.iceBlueLight, borderRadius: 8 }}>
                  <Avatar initials={emp.i} color={emp.c} size={32} />
                  <div style={{ flex: 1, fontSize: 12 }}>
                    <div style={{ fontWeight: 600 }}>{emp.n} · {KONTRAKT_TYPER[emp.kontrakt].label} {emp.stilling}%</div>
                    <div style={{ color: SK.soft, marginTop: 2 }}>
                      {findEnhetPE(emp.enhet)?.name} · {findSelskapPE(emp.selskap)?.navn}
                      · {fmtKrPE(emp.manedslonn)} kr/mnd
                      {emp.sluttDato && <> · slutt {fmtDatoNo(emp.sluttDato)}</>}
                    </div>
                  </div>
                </div>
              </div>

              <div>
                <label style={{ fontSize: 11, color: SK.soft, fontWeight: 600, letterSpacing: 0.05, textTransform: 'uppercase', display: 'block', marginBottom: 8 }}>Endringstype</label>
                <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 8 }}>
                  {Object.entries(ENDRING_TYPER).map(([k, info]) => (
                    <button
                      key={k}
                      onClick={() => setType(k)}
                      style={{
                        padding: '10px 12px', borderRadius: 8, cursor: 'pointer', fontFamily: 'inherit',
                        background: type === k ? info.farge + '15' : SK.pureWhite,
                        border: `1.5px solid ${type === k ? info.farge : 'rgba(17,24,61,.1)'}`,
                        display: 'flex', alignItems: 'center', gap: 10, textAlign: 'left',
                      }}
                    >
                      <span style={{
                        width: 30, height: 30, borderRadius: 8,
                        background: info.farge + '22', color: info.farge,
                        display: 'flex', alignItems: 'center', justifyContent: 'center',
                        fontSize: 16, fontWeight: 700, flexShrink: 0,
                      }}>{info.ikon}</span>
                      <span style={{ fontSize: 12.5, fontWeight: type === k ? 600 : 500, color: SK.ink }}>{info.label}</span>
                    </button>
                  ))}
                </div>
              </div>
            </div>
          )}
          {step === 2 && (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              {(type === 'overflytting' || type === 'selskapsbytte' || type === 'omdisponering') && (
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
                  <div>
                    <label style={{ fontSize: 11, color: SK.soft, fontWeight: 600, letterSpacing: 0.05, textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>Til selskap</label>
                    <select className="ok-input" value={tilSelskap} onChange={e => setTilSelskap(e.target.value)}>
                      {OK_SELSKAPER.map(s => <option key={s.id} value={s.id}>{s.navn}</option>)}
                    </select>
                  </div>
                  <div>
                    <label style={{ fontSize: 11, color: SK.soft, fontWeight: 600, letterSpacing: 0.05, textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>Til enhet</label>
                    <select className="ok-input" value={tilEnhet} onChange={e => setTilEnhet(e.target.value)}>
                      {ORG_UNITS.filter(u => u.id !== 'styret').map(u => <option key={u.id} value={u.id}>{u.name}</option>)}
                    </select>
                  </div>
                </div>
              )}
              {(type === 'stillingsendring' || type === 'omdisponering') && (
                <div>
                  <label style={{ fontSize: 11, color: SK.soft, fontWeight: 600, letterSpacing: 0.05, textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>
                    Ny stilling — fra {emp.stilling}%
                  </label>
                  <input type="range" min={20} max={100} step={5} value={nyStilling} onChange={e => setNyStilling(+e.target.value)} style={{ width: '100%' }} />
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 4, fontSize: 11.5, color: SK.soft }}>
                    <span>20 %</span>
                    <b style={{ color: SK.ink, fontSize: 16 }}>{nyStilling} %</b>
                    <span>100 %</span>
                  </div>
                </div>
              )}
              {(type === 'stillingsendring' || type === 'fast-tilsetting' || type === 'overflytting') && (
                <div>
                  <label style={{ fontSize: 11, color: SK.soft, fontWeight: 600, letterSpacing: 0.05, textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>
                    Ny månedslønn — fra {fmtKrPE(emp.manedslonn)} kr
                  </label>
                  <input type="number" className="ok-input" value={nyLonn} onChange={e => setNyLonn(+e.target.value)} style={{ fontVariantNumeric: 'tabular-nums', fontSize: 15 }} />
                </div>
              )}
              {type === 'forlengelse' && (
                <div>
                  <label style={{ fontSize: 11, color: SK.soft, fontWeight: 600, letterSpacing: 0.05, textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>
                    Forlenge kontrakt til — gammel slutt {emp.sluttDato ? fmtDatoNo(emp.sluttDato) : 'ingen'}
                  </label>
                  <input type="date" className="ok-input" value={forlengeTil} onChange={e => setForlengeTil(e.target.value)} />
                </div>
              )}
              <div>
                <label style={{ fontSize: 11, color: SK.soft, fontWeight: 600, letterSpacing: 0.05, textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>Gjelder fra</label>
                <input type="date" className="ok-input" value={gjelderFra} onChange={e => setGjelderFra(e.target.value)} />
              </div>
              <div>
                <label style={{ fontSize: 11, color: SK.soft, fontWeight: 600, letterSpacing: 0.05, textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>Begrunnelse</label>
                <textarea
                  className="ok-input"
                  rows={4}
                  value={begrunnelse}
                  onChange={e => setBegrunnelse(e.target.value)}
                  placeholder="Hvorfor er denne endringen ønsket? Vis til behov, samtaler med den ansatte, evt. midler/budsjett."
                  style={{ resize: 'vertical', fontFamily: 'inherit' }}
                />
              </div>
              <div style={{ padding: 12, background: SK.iceBlueLight, borderRadius: 8, fontSize: 11.5, lineHeight: 1.5 }}>
                <b style={{ color: SK.ink }}>Forhåndsvisning:</b>{' '}
                {ENDRING_TYPER[type].label} for {emp.n}
                {flyttetEnhet && <> · {fraEnh?.name} → {tilEnh?.name}</>}
                {krysser && <> <span style={{ color: SK.coral, fontWeight: 700 }}>· KRYSSER SELSKAP ({fraSel?.kort} → {tilSel?.kort})</span></>}
                {stillingEndring && <> · stilling {emp.stilling}% → {nyStilling}%</>}
                {lonnEndring > 0.001 && <> · lønn {fmtKrPE(emp.manedslonn)} → {fmtKrPE(nyLonn)} kr</>}
              </div>
            </div>
          )}
          {step === 3 && (
            <div>
              <div style={{ padding: 14, background: SK.iceBlueLight, borderRadius: 10, marginBottom: 14 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 10 }}>
                  <Avatar initials={emp.i} color={emp.c} size={40} />
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 16, fontWeight: 600 }}>{emp.n}</div>
                    <div style={{ fontSize: 11.5, color: SK.soft }}>{emp.r}</div>
                  </div>
                  <span style={{
                    padding: '4px 12px', borderRadius: 99,
                    background: ENDRING_TYPER[type].farge + '22', color: ENDRING_TYPER[type].farge,
                    fontSize: 12, fontWeight: 600,
                  }}>{ENDRING_TYPER[type].ikon} {ENDRING_TYPER[type].label}</span>
                </div>
                <div style={{ fontSize: 12, lineHeight: 1.6, color: SK.ink }}>
                  {flyttetEnhet && <>Flyttes fra <b>{fraEnh?.name}</b> til <b>{tilEnh?.name}</b>{krysser && <> ({fraSel?.kort} → {tilSel?.kort})</>}. </>}
                  {stillingEndring && <>Stilling justeres fra <b>{emp.stilling}%</b> til <b>{nyStilling}%</b>. </>}
                  {nyLonn !== emp.manedslonn && <>Månedslønn endres til <b>{fmtKrPE(nyLonn)} kr</b>. </>}
                  Gjelder fra <b>{fmtDatoNo(gjelderFra)}</b>.
                </div>
              </div>

              <div style={{ fontSize: 11, color: SK.soft, fontWeight: 600, letterSpacing: 0.05, textTransform: 'uppercase', marginBottom: 8 }}>
                Sendes for godkjenning til
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 14 }}>
                {godkjStegFunc().map((s, i) => (
                  <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '8px 12px', background: SK.pureWhite, border: '1px solid rgba(17,24,61,.08)', borderRadius: 8 }}>
                    <div style={{ width: 22, height: 22, borderRadius: '50%', background: SK.lightBlue, color: SK.soft, display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 11, fontWeight: 700 }}>{i + 1}</div>
                    <div style={{ flex: 1, fontSize: 12.5 }}>
                      <div style={{ fontWeight: 600 }}>{s.rolle}</div>
                      <div style={{ fontSize: 11, color: SK.soft }}>{s.who ? TEAM[s.who]?.n : '—'}</div>
                    </div>
                  </div>
                ))}
              </div>
              <div style={{ fontSize: 11.5, color: SK.soft, lineHeight: 1.5 }}>
                Når alle godkjenninger er gitt, varsles HR. Endringen postes deretter
                til Finago (lønnssystemet) ved neste lønnskjøring (3. juni).
                {krysser && <> Siden saken krysser selskaper, genereres et konsernintern­fakturerings­bilag automatisk.</>}
              </div>
            </div>
          )}
        </div>

        <div style={{ padding: '14px 22px', borderTop: '1px solid rgba(17,24,61,.08)', display: 'flex', gap: 8 }}>
          {step > 1 && <Button onClick={() => setStep(step - 1)}>← Tilbake</Button>}
          <div style={{ marginLeft: 'auto', display: 'flex', gap: 8 }}>
            <Button variant="ghost" onClick={onClose}>Avbryt</Button>
            {step < 3 && <Button variant="primary" onClick={() => setStep(step + 1)}>Neste →</Button>}
            {step === 3 && <Button variant="primary" onClick={onClose}>Send til godkjenning</Button>}
          </div>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { EmployeesListMock, PersonalEndringerTabMock, UtgaaendeKontrakterTabMock, NyPersonalendringModalMock });
