// okonomi-screens.jsx — Økonomi-modul: Finago-integrasjon, rapporter pr. rolle,
// konsernregnskap, kostnader pr. avdeling, kostnadsflytting (med godkjenning),
// og lønn/HR-endringer. Bruker UI-primitiver fra prototype-ui.jsx.

// ── Hjelpere ───────────────────────────────────────────────────────────────
const okFmtKr = (v, { kort } = {}) => {
  if (v == null) return '—';
  const abs = Math.abs(v);
  if (kort && abs >= 1_000_000) return `${(v / 1_000_000).toFixed(1).replace('.', ',')} M`;
  if (kort && abs >= 1_000) return `${Math.round(v / 1_000)} k`;
  return new Intl.NumberFormat('nb-NO').format(Math.round(v));
};
const fmtPct = (n, d) => d === 0 ? '—' : `${Math.round((n / d) * 100)} %`;

const PILL_FOR_LONN = {
  utkast: 'draft', klar: 'risk', 'sendt-hr': 'draft', bekreftet: 'track', feilet: 'delay',
};
const LONN_LABEL = {
  utkast: 'Utkast', klar: 'Klar — sendes neste kjøring', 'sendt-hr': 'Sendt til HR',
  bekreftet: 'Bekreftet av HR', feilet: 'Feilet — krever handling',
};

const findAvd = (id) => OK_AVDELINGER.find(a => a.id === id);
const findSelskap = (id) => OK_SELSKAPER.find(s => s.id === id);

// ── Felles delkomponenter ──────────────────────────────────────────────────

// Finago-status (sticky banner øverst i Workspace)
function FinagoBanner() {
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 14, padding: '10px 16px',
      background: SK.pureWhite, border: '1px solid rgba(17,24,61,.08)', borderRadius: 10,
      marginBottom: 16,
    }}>
      <div style={{
        width: 8, height: 8, borderRadius: '50%', background: SK.success, flexShrink: 0,
        boxShadow: `0 0 0 4px ${SK.success}22`,
      }} />
      <div style={{ fontSize: 12, lineHeight: 1.35 }}>
        <div style={{ fontWeight: 600, color: SK.ink }}>
          Finago · tilkoblet <span style={{ color: SK.soft, fontWeight: 500, marginLeft: 8 }}>
            {FINAGO_STATUS.miljo} · {FINAGO_STATUS.apiVersjon}
          </span>
        </div>
        <div style={{ color: SK.soft, marginTop: 2 }}>
          Sist synkronisert {FINAGO_STATUS.sistSynkronisert} · {FINAGO_STATUS.bilagSiste24t} bilag siste 24t · {FINAGO_STATUS.apneFlyttinger} åpne kostnadsflyttinger
        </div>
      </div>
      <div style={{ marginLeft: 'auto', display: 'flex', gap: 8 }}>
        <Button variant="ghost" size="sm" icon={I.download}>Eksport · CSV</Button>
        <Button variant="ghost" size="sm">Logg</Button>
      </div>
    </div>
  );
}

// Rolle-velger (styrer hvilke rapporter / hvilken visning som er aktiv)
function RolleVelger({ value, onChange }) {
  const opts = [
    { id: 'daglig-leder', label: 'Daglig leder' },
    { id: 'okonomi', label: 'Økonomi-stab' },
    { id: 'avd-lamb', label: 'Avd.leder · Lambertseter' },
    { id: 'leder-bistro', label: 'Leder OK:bistro' },
    { id: 'hr', label: 'HR' },
  ];
  return (
    <div style={{
      display: 'flex', alignItems: 'center', gap: 0,
      background: SK.pureWhite, border: '1px solid rgba(17,24,61,.1)', borderRadius: 99,
      padding: 3, fontSize: 11.5,
    }}>
      <span style={{ padding: '0 10px 0 12px', color: SK.soft, fontWeight: 600 }}>Du ser som</span>
      {opts.map(o => (
        <button
          key={o.id}
          onClick={() => onChange(o.id)}
          style={{
            padding: '5px 12px', borderRadius: 99, border: 0, cursor: 'pointer',
            background: value === o.id ? SK.ink : 'transparent',
            color: value === o.id ? SK.pureWhite : SK.ink,
            fontWeight: value === o.id ? 600 : 500, fontFamily: 'inherit', fontSize: 11.5,
            transition: 'all .12s',
          }}
        >{o.label}</button>
      ))}
    </div>
  );
}

// Min lille bar-graf-celle for utnyttelse
function UtnyttBar({ brukt, plan }) {
  const pct = Math.round((brukt / plan) * 100);
  // Forventet «riktig» tempo: ~37 % (mai = 5/12 mnd + litt)
  const forventet = 41;
  const status = pct > forventet + 8 ? 'risk' : pct > forventet + 18 ? 'delay' : 'track';
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
      <Progress value={pct} status={status} style={{ flex: 1, minWidth: 60, maxWidth: 140 }} />
      <span style={{
        fontSize: 11.5, fontWeight: 600, color: status === 'track' ? SK.ink : SK.coral,
        fontVariantNumeric: 'tabular-nums', minWidth: 36, textAlign: 'right',
      }}>{pct}%</span>
    </div>
  );
}

// Liten "godkjenningstrapp" for flytting
function Godkjenningssti({ 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ø';
        const color = done ? SK.success : reject ? SK.coral : wait ? SK.warn : SK.soft;
        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 ? `${TEAM[s.av]?.n || s.av} · ${s.tid}`
                  : done && s.av === 'sys' ? `Automatisk · ${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>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// TAB · OVERSIKT
// ═══════════════════════════════════════════════════════════════════════════
function TabOversikt({ rolle, goTab }) {
  const totalInntekt = OK_KONSERN_PL.filter(r => r.type === 'inntekt')
    .reduce((s, r) => s + r.okm + r.okb + r.oks + r.okd, 0);
  const totalKost = OK_KONSERN_PL.filter(r => r.type === 'kostnad')
    .reduce((s, r) => s + r.okm + r.okb + r.oks + r.okd, 0);
  const resultat = totalInntekt - totalKost;

  const apneFlytt = OK_FLYTT.filter(f => f.status === 'venter-mottaker' || f.status === 'venter-okonomi');
  const mineFlytt = apneFlytt.filter(f =>
    rolle === 'daglig-leder' || rolle === 'okonomi'
    || (rolle === 'avd-lamb' && (f.tilAvd === 'avd-lamb' || f.fraAvd === 'avd-lamb'))
  );

  return (
    <div>
      {/* KPI-rad */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 16 }}>
        <Card padded>
          <KPI
            label="Resultat hittil"
            value={`${(resultat / 1_000_000).toFixed(2).replace('.', ',')} M`}
            sub={`Budsjett: ${(OK_SELSKAPER.reduce((s, v) => s + v.budsjettResultat, 0) / 1_000_000).toFixed(2).replace('.', ',')} M`}
          />
        </Card>
        <Card padded>
          <KPI
            label="Inntekt konsern"
            value={`${(totalInntekt / 1_000_000).toFixed(1).replace('.', ',')} M`}
            sub="Hittil i år · alle selskaper"
          />
        </Card>
        <Card padded>
          <KPI
            label="Åpne kostnadsflyttinger"
            value={apneFlytt.length}
            sub={`${apneFlytt.filter(f => f.status === 'venter-okonomi').length} til økonomisjef · ${apneFlytt.filter(f => f.status === 'venter-mottaker').length} til avd.ledere`}
            accent={apneFlytt.length > 0}
          />
        </Card>
        <Card padded>
          <KPI
            label="Lønnsendringer · neste kjøring"
            value={OK_LONN_KORENINGER.apneEndringer + OK_LONN_KORENINGER.ventendeHR}
            sub={`Kjøres ${OK_LONN_KORENINGER.neste} · frist ${OK_LONN_KORENINGER.frist}`}
            accent={OK_LONN_KORENINGER.apneEndringer > 0}
          />
        </Card>
      </div>

      {/* Selskaper-grid */}
      <Card title="Konsern · hittil 2026" action={
        <Button variant="ghost" size="sm" onClick={() => goTab('konsern')}>Åpne konsernregnskap →</Button>
      }>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 12, marginTop: 4 }}>
          {OK_SELSKAPER.map(s => {
            const overBudsjett = s.resultat >= s.budsjettResultat;
            return (
              <div key={s.id} style={{
                border: '1px solid rgba(17,24,61,.08)', borderRadius: 10, padding: 14,
                background: SK.pureWhite, position: 'relative', overflow: 'hidden',
              }}>
                <div style={{
                  position: 'absolute', top: 0, left: 0, right: 0, height: 3, background: s.brand,
                }} />
                <div style={{ fontSize: 10.5, color: SK.soft, fontWeight: 600, letterSpacing: 0.05, textTransform: 'uppercase' }}>
                  {s.type === 'mor' ? 'Morselskap' : `Datter · ${s.eierandel} %`}
                </div>
                <div style={{ fontSize: 14, fontWeight: 600, color: SK.ink, marginTop: 2 }}>{s.navn}</div>
                <div style={{ fontSize: 11, color: SK.soft, marginTop: 1 }}>{s.ansatte} ansatte · {s.orgnr}</div>
                <div style={{ marginTop: 12, display: 'flex', alignItems: 'baseline', gap: 8 }}>
                  <div style={{ fontSize: 22, fontWeight: 600, color: s.resultat >= 0 ? SK.ink : SK.coral, letterSpacing: -0.01 }}>
                    {s.resultat >= 0 ? '+' : ''}{okFmtKr(s.resultat, { kort: true })}
                  </div>
                  <div style={{ fontSize: 10.5, color: SK.soft }}>resultat</div>
                </div>
                <div style={{ fontSize: 11, color: SK.soft, marginTop: 4 }}>
                  Mot bud. <span style={{ color: overBudsjett ? SK.success : SK.coral, fontWeight: 600 }}>
                    {overBudsjett ? '+' : ''}{okFmtKr(s.resultat - s.budsjettResultat, { kort: true })}
                  </span>
                </div>
              </div>
            );
          })}
        </div>
      </Card>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14, marginTop: 14 }}>
        {/* Mine åpne saker */}
        <Card title={rolle === 'okonomi' || rolle === 'daglig-leder' ? 'Åpne kostnadsflyttinger' : 'Saker som venter på deg'} action={
          <Button variant="ghost" size="sm" onClick={() => goTab('flytting')}>Se alle →</Button>
        }>
          {mineFlytt.length === 0 ? (
            <div style={{ padding: '20px 0', color: SK.soft, fontSize: 12.5 }}>Ingen åpne saker.</div>
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 2 }}>
              {mineFlytt.slice(0, 4).map(f => (
                <div key={f.id} style={{
                  display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px',
                  background: SK.iceBlueLight, borderRadius: 8,
                }}>
                  <div style={{ fontSize: 11, color: SK.soft, fontWeight: 600, minWidth: 78, fontVariantNumeric: 'tabular-nums' }}>{f.nr}</div>
                  <div style={{ flex: 1, fontSize: 12.5 }}>
                    <div style={{ fontWeight: 600, color: SK.ink }}>
                      {findAvd(f.fraAvd).navn} → {findAvd(f.tilAvd).navn}
                    </div>
                    <div style={{ fontSize: 11, color: SK.soft, marginTop: 1 }}>
                      {f.kontoNavn} · {okFmtKr(f.belop)} kr
                    </div>
                  </div>
                  <Pill status={OK_FLYTT_STATUS[f.status].pill}>{OK_FLYTT_STATUS[f.status].label}</Pill>
                </div>
              ))}
            </div>
          )}
        </Card>

        {/* Lønn-endringer som venter */}
        <Card title="Til neste lønnskjøring" action={
          <Button variant="ghost" size="sm" onClick={() => goTab('lonn')}>Se alle →</Button>
        }>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginTop: 2 }}>
            {OK_LONN_ENDRINGER.filter(e => e.status === 'klar' || e.status === 'sendt-hr' || e.status === 'feilet').slice(0, 4).map(e => (
              <div key={e.id} style={{
                display: 'flex', alignItems: 'center', gap: 12, padding: '10px 12px',
                background: SK.iceBlueLight, borderRadius: 8,
              }}>
                <Avatar initials={e.person} color={OK_LONN_TYPER[e.type].farge} size={28} />
                <div style={{ flex: 1, fontSize: 12.5 }}>
                  <div style={{ fontWeight: 600, color: SK.ink }}>
                    {e.personNavn} <span style={{ fontWeight: 500, color: SK.soft }}>· {OK_LONN_TYPER[e.type].label}</span>
                  </div>
                  <div style={{ fontSize: 11, color: SK.soft, marginTop: 1 }}>
                    Fra {e.gjelderFra}{e.belop ? ` · ${okFmtKr(e.belop)} kr ${e.periode}` : ''}
                  </div>
                </div>
                <Pill status={PILL_FOR_LONN[e.status]}>{e.status === 'feilet' ? 'Feilet' : e.status === 'klar' ? 'Klar' : e.status === 'sendt-hr' ? 'Sendt HR' : LONN_LABEL[e.status]}</Pill>
              </div>
            ))}
          </div>
        </Card>
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// TAB · MIN AVDELING
// ═══════════════════════════════════════════════════════════════════════════
function TabMinAvdeling({ goTab, setFlytt }) {
  const lamb = findAvd('avd-lamb');
  const total = OK_LAMB_KOSTNADER.reduce((s, l) => ({ plan: s.plan + l.plan, brukt: s.brukt + l.brukt }), { plan: 0, brukt: 0 });

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 14, marginBottom: 14 }}>
        <Card title={`${lamb.navn} · ${lamb.ansatte} ansatte`} action={
          <span style={{ fontSize: 11, color: SK.soft }}>Avd.leder · {TEAM[lamb.leder]?.n}</span>
        }>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16, marginTop: 4 }}>
            <KPI label="Budsjett 2026" value={`${(total.plan / 1_000_000).toFixed(1).replace('.', ',')} M`} sub="kr · hele året" />
            <KPI label="Brukt hittil" value={`${(total.brukt / 1_000_000).toFixed(1).replace('.', ',')} M`} sub={`${Math.round((total.brukt / total.plan) * 100)} % · forventet ~41 %`} />
            <KPI label="Igjen" value={`${((total.plan - total.brukt) / 1_000_000).toFixed(1).replace('.', ',')} M`} sub="til 31.12.2026" />
          </div>
        </Card>
        <Card title="Kostnadsflytting — fra denne avdelingen">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10, marginTop: 2 }}>
            <div style={{ fontSize: 12, color: SK.soft, lineHeight: 1.45 }}>
              Foreslå at en kostnad flyttes fra Lambertseter til en annen avdeling eller selskap. Mottagende avdelingsleder må godkjenne før det posteres i Finago.
            </div>
            <div style={{ display: 'flex', gap: 8 }}>
              <Button variant="primary" icon={I.plus} onClick={() => setFlytt({ open: true })}>Ny flytting</Button>
              <Button variant="ghost" onClick={() => goTab('flytting')}>Se alle flyttinger →</Button>
            </div>
          </div>
        </Card>
      </div>

      <Card title="Kostnader pr. konto · Lambertseter" action={
        <div style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 11, color: SK.soft }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: SK.success }} />
          Auto fra Finago
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: SK.coral, marginLeft: 10 }} />
          Manuell allokering
        </div>
      } padded={false}>
        <table className="ok-table">
          <thead>
            <tr>
              <th style={{ width: 70 }}>Konto</th>
              <th>Kontogruppe</th>
              <th style={{ textAlign: 'right' }}>Budsjett</th>
              <th style={{ textAlign: 'right' }}>Brukt</th>
              <th style={{ width: 240 }}>Utnyttelse</th>
              <th>Kilde</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {OK_LAMB_KOSTNADER.map(l => (
              <tr key={l.id}>
                <td style={{ color: SK.soft, fontVariantNumeric: 'tabular-nums' }}>{l.konto}</td>
                <td style={{ fontWeight: 500, color: SK.ink }}>{l.gruppe}</td>
                <td style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums', color: SK.soft }}>{okFmtKr(l.plan)}</td>
                <td style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums', fontWeight: 600 }}>{okFmtKr(l.brukt)}</td>
                <td><UtnyttBar brukt={l.brukt} plan={l.plan} /></td>
                <td style={{ fontSize: 11, color: SK.soft }}>
                  <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
                    <span style={{ width: 5, height: 5, borderRadius: '50%', background: SK.success }} />
                    {l.finagoBilag} bilag
                  </span>
                  {l.manuellAlloc > 0 && (
                    <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, marginLeft: 10 }}>
                      <span style={{ width: 5, height: 5, borderRadius: '50%', background: SK.coral }} />
                      {l.manuellAlloc}
                    </span>
                  )}
                </td>
                <td onClick={(e) => e.stopPropagation()}>
                  <Button variant="ghost" size="sm" onClick={() => setFlytt({ open: true, konto: l.konto, kontoNavn: l.gruppe })}>Flytt →</Button>
                </td>
              </tr>
            ))}
            <tr style={{ background: SK.iceBlueLight, fontWeight: 600 }}>
              <td></td>
              <td>Total</td>
              <td style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>{okFmtKr(total.plan)}</td>
              <td style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>{okFmtKr(total.brukt)}</td>
              <td><UtnyttBar brukt={total.brukt} plan={total.plan} /></td>
              <td colSpan={2}></td>
            </tr>
          </tbody>
        </table>
      </Card>

      <Card title="Ansatte allokert til Lambertseter" action={
        <span style={{ fontSize: 11, color: SK.soft }}>
          Lønnskostnader fordelt via Finago + manuelle allokeringer
        </span>
      } padded={false} style={{ marginTop: 14 }}>
        <table className="ok-table">
          <thead>
            <tr>
              <th>Ansatt</th>
              <th>Rolle</th>
              <th style={{ textAlign: 'right' }}>Stilling</th>
              <th style={{ textAlign: 'right' }}>Allokering hit</th>
              <th style={{ textAlign: 'right' }}>Månedslønn (allok.)</th>
              <th>Spesielt</th>
            </tr>
          </thead>
          <tbody>
            {OK_LAMB_ANSATTE.map((a, i) => {
              const allokLonn = Math.round(a.manedslonn * (a.alloc / 100));
              return (
                <tr key={i}>
                  <td>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
                      <Avatar initials={a.initi} color={TEAM[a.initi]?.c || SK.lightBlue} size={26} />
                      <span style={{ fontWeight: 500 }}>{a.navn}</span>
                    </div>
                  </td>
                  <td style={{ color: SK.soft }}>{a.rolle}</td>
                  <td style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>{a.stilling} %</td>
                  <td style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums', fontWeight: a.alloc < 100 ? 600 : 500, color: a.alloc < 100 ? SK.coral : SK.ink }}>
                    {a.alloc} %
                  </td>
                  <td style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>{okFmtKr(allokLonn)} kr</td>
                  <td style={{ fontSize: 11.5, color: SK.soft }}>
                    {a.fraAvd && a.fraAvd !== 'avd-lamb' ? `Hentet 20 % fra ${findAvd(a.fraAvd)?.navn}` : null}
                    {a.tilSelskap ? <>40 % belastes <b style={{ color: SK.ink }}>{findSelskap(a.tilSelskap)?.navn}</b></> : null}
                    {!a.fraAvd && !a.tilSelskap ? '—' : null}
                  </td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// TAB · KONSERNREGNSKAP
// ═══════════════════════════════════════════════════════════════════════════
function TabKonsern() {
  const inntekter = OK_KONSERN_PL.filter(r => r.type === 'inntekt');
  const kostnader = OK_KONSERN_PL.filter(r => r.type === 'kostnad');
  const sum = (rows, k) => rows.reduce((s, r) => s + r[k], 0);

  return (
    <div>
      <div style={{ display: 'flex', gap: 8, marginBottom: 14, alignItems: 'center' }}>
        <div style={{ fontSize: 13, fontWeight: 600 }}>Konsolidert resultat · hittil 2026</div>
        <span style={{ fontSize: 11, color: SK.soft }}>· 1.1 – 18.5.2026 (≈ 37 % av året)</span>
        <div style={{ marginLeft: 'auto', display: 'flex', gap: 8 }}>
          <Button variant="ghost" size="sm" icon={I.download}>Last ned PDF</Button>
          <Button variant="ghost" size="sm" icon={I.download}>Eksport CSV</Button>
        </div>
      </div>

      <Card padded={false}>
        <table className="ok-table">
          <thead>
            <tr>
              <th style={{ width: 320 }}>Kontogruppe</th>
              {OK_SELSKAPER.map(s => (
                <th key={s.id} style={{ textAlign: 'right' }}>
                  <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-end', gap: 2 }}>
                    <span>{s.kort}</span>
                    <span style={{ fontWeight: 500, color: SK.soft, textTransform: 'none', letterSpacing: 0, fontSize: 10 }}>{s.navn.replace(' AS', '')}</span>
                  </div>
                </th>
              ))}
              <th style={{ textAlign: 'right' }}>Konsolidert</th>
              <th style={{ textAlign: 'right' }}>Budsjett</th>
              <th style={{ textAlign: 'right', width: 90 }}>Avvik</th>
            </tr>
          </thead>
          <tbody>
            <tr style={{ background: SK.iceBlueLight }}>
              <td colSpan={8} style={{ fontSize: 10.5, fontWeight: 600, color: SK.soft, letterSpacing: 0.06, textTransform: 'uppercase' }}>Inntekter</td>
            </tr>
            {inntekter.map((r, i) => {
              const kons = r.okm + r.okb + r.oks + r.okd;
              const avvik = kons - r.budsjett * 0.37;
              return (
                <tr key={i} style={{ cursor: 'default' }}>
                  <td style={{ fontWeight: 500 }}>{r.gruppe}</td>
                  {OK_SELSKAPER.map(s => (
                    <td key={s.id} style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums', color: r[s.id] === 0 ? SK.soft : SK.ink }}>
                      {r[s.id] === 0 ? '—' : okFmtKr(r[s.id])}
                    </td>
                  ))}
                  <td style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums', fontWeight: 600 }}>{okFmtKr(kons)}</td>
                  <td style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums', color: SK.soft }}>{okFmtKr(r.budsjett)}</td>
                  <td style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums', color: avvik > 0 ? SK.success : SK.coral, fontWeight: 600 }}>
                    {avvik > 0 ? '+' : ''}{okFmtKr(avvik, { kort: true })}
                  </td>
                </tr>
              );
            })}
            <tr style={{ background: SK.iceBlueLight, fontWeight: 700 }}>
              <td>Sum inntekter</td>
              {OK_SELSKAPER.map(s => (
                <td key={s.id} style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>{okFmtKr(sum(inntekter, s.id))}</td>
              ))}
              <td style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>{okFmtKr(sum(inntekter, 'okm') + sum(inntekter, 'okb') + sum(inntekter, 'oks') + sum(inntekter, 'okd'))}</td>
              <td colSpan={2}></td>
            </tr>

            <tr style={{ background: SK.iceBlueLight }}>
              <td colSpan={8} style={{ fontSize: 10.5, fontWeight: 600, color: SK.soft, letterSpacing: 0.06, textTransform: 'uppercase', paddingTop: 14 }}>Kostnader</td>
            </tr>
            {kostnader.map((r, i) => {
              const kons = r.okm + r.okb + r.oks + r.okd;
              const avvik = r.budsjett * 0.37 - kons;
              return (
                <tr key={i} style={{ cursor: 'default' }}>
                  <td style={{ fontWeight: 500 }}>{r.gruppe}</td>
                  {OK_SELSKAPER.map(s => (
                    <td key={s.id} style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums', color: r[s.id] === 0 ? SK.soft : SK.ink }}>
                      {r[s.id] === 0 ? '—' : okFmtKr(r[s.id])}
                    </td>
                  ))}
                  <td style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums', fontWeight: 600 }}>{okFmtKr(kons)}</td>
                  <td style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums', color: SK.soft }}>{okFmtKr(r.budsjett)}</td>
                  <td style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums', color: avvik > 0 ? SK.success : SK.coral, fontWeight: 600 }}>
                    {avvik > 0 ? '+' : ''}{okFmtKr(avvik, { kort: true })}
                  </td>
                </tr>
              );
            })}
            <tr style={{ background: SK.iceBlueLight, fontWeight: 700 }}>
              <td>Sum kostnader</td>
              {OK_SELSKAPER.map(s => (
                <td key={s.id} style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>{okFmtKr(sum(kostnader, s.id))}</td>
              ))}
              <td style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>{okFmtKr(sum(kostnader, 'okm') + sum(kostnader, 'okb') + sum(kostnader, 'oks') + sum(kostnader, 'okd'))}</td>
              <td colSpan={2}></td>
            </tr>

            <tr style={{ background: SK.ink, color: SK.pureWhite }}>
              <td style={{ fontWeight: 700, color: SK.pureWhite }}>Resultat før skatt</td>
              {OK_SELSKAPER.map(s => {
                const r = sum(inntekter, s.id) - sum(kostnader, s.id);
                return (
                  <td key={s.id} style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums', fontWeight: 700, color: r >= 0 ? SK.pureWhite : '#ffb6bb' }}>
                    {r >= 0 ? '+' : ''}{okFmtKr(r)}
                  </td>
                );
              })}
              <td style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums', fontWeight: 700 }}>
                {(() => {
                  const tot = sum(inntekter, 'okm') + sum(inntekter, 'okb') + sum(inntekter, 'oks') + sum(inntekter, 'okd')
                            - (sum(kostnader, 'okm') + sum(kostnader, 'okb') + sum(kostnader, 'oks') + sum(kostnader, 'okd'));
                  return (tot >= 0 ? '+' : '') + okFmtKr(tot);
                })()}
              </td>
              <td colSpan={2}></td>
            </tr>
          </tbody>
        </table>
      </Card>

      <div style={{ fontSize: 11, color: SK.soft, marginTop: 10, lineHeight: 1.5 }}>
        Tall hentes automatisk fra Finago hver natt kl. 06:00 (sist {FINAGO_STATUS.sistSynkronisert}).
        Konserninterne salg/kjøp elimineres ikke i denne visningen — full konsolidering produseres ved kvartals­slutt av økonomi-stab.
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// TAB · KOSTNADSFLYTTING
// ═══════════════════════════════════════════════════════════════════════════
function TabFlytting({ setFlytt, rolle }) {
  const [filter, setFilter] = React.useState('apne');
  const [openId, setOpenId] = React.useState(null);

  const filtered = OK_FLYTT.filter(f => {
    if (filter === 'apne') return f.status === 'venter-mottaker' || f.status === 'venter-okonomi' || f.status === 'utkast';
    if (filter === 'mine') {
      return rolle === 'avd-lamb' && (f.tilAvd === 'avd-lamb' || f.fraAvd === 'avd-lamb' || f.opprettetAv === 'MR');
    }
    if (filter === 'godkjent') return f.status === 'godkjent';
    if (filter === 'avvist') return f.status === 'avvist';
    return true;
  });

  const valgt = openId ? OK_FLYTT.find(f => f.id === openId) : null;

  return (
    <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 (${OK_FLYTT.filter(f => f.status === 'venter-mottaker' || f.status === 'venter-okonomi').length})` },
            { id: 'mine', label: 'Mine saker' },
            { id: 'godkjent', label: 'Godkjent' },
            { 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 & terskler</Button>
          <Button variant="primary" icon={I.plus} onClick={() => setFlytt({ open: true })}>Ny flytting</Button>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: valgt ? '1.4fr 1fr' : '1fr', gap: 14, alignItems: 'flex-start' }}>
        <Card padded={false}>
          <table className="ok-table">
            <thead>
              <tr>
                <th style={{ width: 100 }}>Sak</th>
                <th>Fra → Til</th>
                <th>Konto</th>
                <th style={{ textAlign: 'right' }}>Beløp</th>
                <th>Status</th>
                <th style={{ width: 100 }}>Opprettet</th>
              </tr>
            </thead>
            <tbody>
              {filtered.map(f => {
                const tilSelskap = f.tilSelskap !== f.fraSelskap;
                return (
                  <tr key={f.id} onClick={() => setOpenId(f.id)} style={{ background: openId === f.id ? SK.iceBlueLight : 'inherit' }}>
                    <td style={{ fontVariantNumeric: 'tabular-nums', color: SK.soft, fontWeight: 600 }}>{f.nr}</td>
                    <td>
                      <div style={{ fontWeight: 500 }}>{findAvd(f.fraAvd)?.navn}</div>
                      <div style={{ fontSize: 11, color: SK.soft, display: 'flex', alignItems: 'center', gap: 4 }}>
                        <span>→ {findAvd(f.tilAvd)?.navn}</span>
                        {tilSelskap && <span style={{ background: SK.coral, color: '#fff', padding: '0 6px', borderRadius: 4, fontSize: 9, fontWeight: 700, letterSpacing: 0.05 }}>
                          BYTTE AV SELSKAP
                        </span>}
                      </div>
                    </td>
                    <td style={{ fontSize: 12 }}>
                      <div>{f.kontoNavn}</div>
                      <div style={{ fontSize: 10.5, color: SK.soft, fontVariantNumeric: 'tabular-nums' }}>{f.konto}</div>
                    </td>
                    <td style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums', fontWeight: 600 }}>{okFmtKr(f.belop)} kr</td>
                    <td><Pill status={OK_FLYTT_STATUS[f.status].pill}>{OK_FLYTT_STATUS[f.status].label}</Pill></td>
                    <td style={{ fontSize: 11.5, color: SK.soft }}>{f.opprettet}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </Card>

        {valgt && (
          <Card title={valgt.nr} action={
            <Button variant="ghost" size="sm" onClick={() => setOpenId(null)}>Lukk ×</Button>
          }>
            <div style={{ fontSize: 12.5, lineHeight: 1.5 }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 14 }}>
                <div>
                  <div style={{ fontSize: 10.5, color: SK.soft, fontWeight: 600, letterSpacing: 0.05, textTransform: 'uppercase' }}>Fra</div>
                  <div style={{ fontWeight: 600, marginTop: 2 }}>{findAvd(valgt.fraAvd)?.navn}</div>
                  <div style={{ fontSize: 11, color: SK.soft }}>{findSelskap(valgt.fraSelskap)?.navn}</div>
                </div>
                <div>
                  <div style={{ fontSize: 10.5, color: SK.soft, fontWeight: 600, letterSpacing: 0.05, textTransform: 'uppercase' }}>Til</div>
                  <div style={{ fontWeight: 600, marginTop: 2 }}>{findAvd(valgt.tilAvd)?.navn}</div>
                  <div style={{ fontSize: 11, color: SK.soft }}>{findSelskap(valgt.tilSelskap)?.navn}</div>
                </div>
                <div>
                  <div style={{ fontSize: 10.5, color: SK.soft, fontWeight: 600, letterSpacing: 0.05, textTransform: 'uppercase' }}>Konto</div>
                  <div style={{ fontWeight: 600, marginTop: 2 }}>{valgt.konto} · {valgt.kontoNavn}</div>
                </div>
                <div>
                  <div style={{ fontSize: 10.5, color: SK.soft, fontWeight: 600, letterSpacing: 0.05, textTransform: 'uppercase' }}>Beløp</div>
                  <div style={{ fontWeight: 700, marginTop: 2, fontSize: 18, fontVariantNumeric: 'tabular-nums' }}>{okFmtKr(valgt.belop)} kr</div>
                </div>
              </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, color: SK.ink }}>{valgt.begrunnelse}</div>
                <div style={{ fontSize: 11, color: SK.soft, marginTop: 6 }}>Ref: {valgt.referanse}</div>
              </div>

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

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

              {(valgt.status === 'venter-mottaker' || valgt.status === 'venter-okonomi') && (
                <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>
        )}
      </div>

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

// ═══════════════════════════════════════════════════════════════════════════
// TAB · LØNN / HR
// ═══════════════════════════════════════════════════════════════════════════
function TabLonnHR() {
  const klar = OK_LONN_ENDRINGER.filter(e => e.status === 'klar');
  const sendt = OK_LONN_ENDRINGER.filter(e => e.status === 'sendt-hr');
  const bekreftet = OK_LONN_ENDRINGER.filter(e => e.status === 'bekreftet');
  const feilet = OK_LONN_ENDRINGER.filter(e => e.status === 'feilet');

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 14 }}>
        <Card padded><KPI label="Klar — sendes neste kjøring" value={klar.length} sub={`Frist: ${OK_LONN_KORENINGER.frist}`} /></Card>
        <Card padded><KPI label="Sendt — venter HR" value={sendt.length} sub="Hanne Myhre · HR-leder" /></Card>
        <Card padded><KPI label="Bekreftet (siste 14d)" value={bekreftet.length} sub="Postert til lønnskjøring" /></Card>
        <Card padded><KPI label="Feilet — krever handling" value={feilet.length} sub="Sjekk feilkode" accent={feilet.length > 0} /></Card>
      </div>

      <Card title="Endringer som skal rapporteres til lønn / HR" action={
        <div style={{ display: 'flex', gap: 8 }}>
          <Button variant="ghost" size="sm" icon={I.download}>Eksport · lønnskjøring</Button>
          <Button variant="primary" size="sm" icon={I.plus}>Ny endring</Button>
        </div>
      } padded={false}>
        <table className="ok-table">
          <thead>
            <tr>
              <th>Person</th>
              <th>Type</th>
              <th style={{ width: '32%' }}>Detalj</th>
              <th style={{ textAlign: 'right' }}>Beløp</th>
              <th>Gjelder fra</th>
              <th>Status</th>
              <th>HR-kvittering</th>
            </tr>
          </thead>
          <tbody>
            {OK_LONN_ENDRINGER.map(e => (
              <tr key={e.id}>
                <td>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 9 }}>
                    <Avatar initials={e.person} color={OK_LONN_TYPER[e.type].farge} size={26} />
                    <div>
                      <div style={{ fontWeight: 500 }}>{e.personNavn}</div>
                      <div style={{ fontSize: 10.5, color: SK.soft }}>{findAvd(e.avd)?.navn}</div>
                    </div>
                  </div>
                </td>
                <td>
                  <span style={{
                    display: 'inline-block', padding: '2px 8px', borderRadius: 99,
                    background: OK_LONN_TYPER[e.type].farge + '22',
                    color: OK_LONN_TYPER[e.type].farge, fontSize: 11, fontWeight: 600,
                  }}>{OK_LONN_TYPER[e.type].label}</span>
                </td>
                <td style={{ fontSize: 12, color: SK.soft, lineHeight: 1.4 }}>
                  {e.detalj}
                  {e.feilGrunn && <div style={{ color: SK.coral, marginTop: 4, fontWeight: 500 }}>⚠ {e.feilGrunn}</div>}
                  {e.finagoOppgave && <div style={{ fontSize: 10.5, marginTop: 4 }}>Kobling: <b style={{ color: SK.ink }}>{e.finagoOppgave}</b></div>}
                </td>
                <td style={{ textAlign: 'right', fontVariantNumeric: 'tabular-nums' }}>
                  {e.belop ? `${okFmtKr(e.belop)} kr` : '—'}
                  {e.periode && <div style={{ fontSize: 10.5, color: SK.soft }}>{e.periode}</div>}
                </td>
                <td style={{ fontSize: 11.5 }}>{e.gjelderFra}</td>
                <td><Pill status={PILL_FOR_LONN[e.status]}>{LONN_LABEL[e.status]}</Pill></td>
                <td style={{ fontSize: 11, color: SK.soft }}>
                  {e.hrKvittering || (e.status === 'sendt-hr' ? '—' : (e.status === 'klar' ? 'I kø' : '—'))}
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>

      <div style={{ fontSize: 11, color: SK.soft, marginTop: 10, lineHeight: 1.5 }}>
        Endringer rapportert her overføres til HR-systemet ved neste lønnskjøring ({OK_LONN_KORENINGER.neste}).
        Allokeringsendringer som påvirker avdelingsregnskapet posteres parallelt i Finago.
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// TAB · RAPPORTER (tilgangsfiltrert)
// ═══════════════════════════════════════════════════════════════════════════
function TabRapporter({ rolle }) {
  const synlige = OK_RAPPORTER.filter(r => r.tilgang.includes(rolle));
  const skjulte = OK_RAPPORTER.filter(r => !r.tilgang.includes(rolle));

  return (
    <div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14, fontSize: 12.5 }}>
        <span style={{ color: SK.soft }}>Tilgang basert på rolle <b style={{ color: SK.ink }}>{OK_ROLLER[rolle]?.label}</b>:</span>
        <span style={{ background: '#dbeed8', color: SK.success, padding: '2px 10px', borderRadius: 99, fontSize: 11, fontWeight: 600 }}>
          {synlige.length} rapporter tilgjengelig
        </span>
        <span style={{ background: SK.lightCoral, color: '#a01a25', padding: '2px 10px', borderRadius: 99, fontSize: 11, fontWeight: 600 }}>
          {skjulte.length} skjult — krever annen rolle
        </span>
      </div>

      <Card title="Tilgjengelige rapporter" padded={false}>
        <table className="ok-table">
          <thead>
            <tr>
              <th>Rapport</th>
              <th>Periode</th>
              <th>Oppdatert</th>
              <th>Kilde</th>
              <th>Tilgang</th>
              <th style={{ width: 110 }}></th>
            </tr>
          </thead>
          <tbody>
            {synlige.map(r => (
              <tr key={r.id}>
                <td style={{ fontWeight: 500 }}>{r.navn}</td>
                <td style={{ fontSize: 12, color: SK.soft }}>{r.periode}</td>
                <td style={{ fontSize: 11.5, color: SK.soft }}>{r.oppdatert}</td>
                <td>
                  <span style={{
                    display: 'inline-block', padding: '2px 8px', borderRadius: 4, background: SK.iceBlue,
                    color: SK.ink, fontSize: 11, fontWeight: 600,
                  }}>{r.kilde}</span>
                </td>
                <td>
                  <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
                    {r.tilgang.slice(0, 3).map(t => (
                      <span key={t} style={{
                        fontSize: 10, padding: '1px 7px', borderRadius: 99,
                        background: OK_ROLLER[t]?.farge + '22',
                        color: OK_ROLLER[t]?.farge.startsWith('#bbe8') || OK_ROLLER[t]?.farge.startsWith('#fcdd') || OK_ROLLER[t]?.farge.startsWith('#cedf') ? SK.ink : OK_ROLLER[t]?.farge,
                        fontWeight: 600,
                      }}>{OK_ROLLER[t]?.label.replace('Avd.leder · ', '').replace('Leder ', '')}</span>
                    ))}
                    {r.tilgang.length > 3 && <span style={{ fontSize: 10, color: SK.soft }}>+{r.tilgang.length - 3}</span>}
                  </div>
                </td>
                <td onClick={(e) => e.stopPropagation()}>
                  <Button variant="ghost" size="sm" icon={I.download}>PDF</Button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>

      {skjulte.length > 0 && (
        <Card title="Skjulte rapporter — krever annen rolle" style={{ marginTop: 14 }} padded={false}>
          <table className="ok-table" style={{ opacity: 0.6 }}>
            <thead>
              <tr>
                <th>Rapport</th>
                <th>Tilgjengelig for</th>
                <th>Kilde</th>
                <th style={{ width: 140 }}></th>
              </tr>
            </thead>
            <tbody>
              {skjulte.map(r => (
                <tr key={r.id} style={{ cursor: 'default' }}>
                  <td style={{ fontWeight: 500, color: SK.soft, display: 'flex', alignItems: 'center', gap: 6 }}>
                    <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><rect width="18" height="11" x="3" y="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>
                    {r.navn}
                  </td>
                  <td>
                    <div style={{ display: 'flex', gap: 4, flexWrap: 'wrap' }}>
                      {r.tilgang.map(t => (
                        <span key={t} style={{ fontSize: 10, padding: '1px 7px', borderRadius: 99, background: SK.lightBlue, color: SK.soft, fontWeight: 600 }}>
                          {OK_ROLLER[t]?.label}
                        </span>
                      ))}
                    </div>
                  </td>
                  <td style={{ fontSize: 11, color: SK.soft }}>{r.kilde}</td>
                  <td><Button variant="ghost" size="sm">Be om tilgang</Button></td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      )}
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// NY FLYTTING · modal
// ═══════════════════════════════════════════════════════════════════════════
function NyFlyttingModal({ open, onClose, prefyll }) {
  const [step, setStep] = React.useState(1);
  const [fraAvd, setFraAvd] = React.useState('avd-lamb');
  const [tilAvd, setTilAvd] = React.useState('avd-holm');
  const [konto, setKonto] = React.useState(prefyll?.konto || 5000);
  const [belop, setBelop] = React.useState(15_000);
  const [begrunnelse, setBegrunnelse] = React.useState('');

  React.useEffect(() => {
    if (open && prefyll?.konto) setKonto(prefyll.konto);
    if (!open) setStep(1);
  }, [open, prefyll]);

  if (!open) return null;

  const fraSelskap = findAvd(fraAvd)?.id?.startsWith('stab-') ? 'okm' : 'okm';
  const tilSelskap = 'okm';
  const krever = (() => {
    if (konto >= 5000 && konto < 6000) return 'r4';
    if (belop > 100_000) return 'r3';
    if (belop > 20_000 || fraSelskap !== tilSelskap) return 'r2';
    return 'r1';
  })();
  const regel = OK_FLYTT_REGLER.find(r => r.id === krever);

  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: 640,
        boxShadow: '0 20px 60px rgba(17,24,61,.4)', overflow: 'hidden',
      }}>
        <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 kostnadsflytting</div>
            <h2 style={{ margin: '4px 0 0', fontSize: 18, fontWeight: 600 }}>Steg {step} av 3 · {step === 1 ? 'Hvor & hva' : step === 2 ? 'Beløp & begrunnelse' : 'Bekreft & send'}</h2>
          </div>
          <Button variant="ghost" size="icon" onClick={onClose} style={{ marginLeft: 'auto' }}>×</Button>
        </div>
        <div style={{ padding: 22 }}>
          {step === 1 && (
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
              <div>
                <label style={{ fontSize: 11, color: SK.soft, fontWeight: 600, letterSpacing: 0.05, textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>Fra avdeling</label>
                <select className="ok-input" value={fraAvd} onChange={e => setFraAvd(e.target.value)}>
                  {OK_AVDELINGER.map(a => <option key={a.id} value={a.id}>{a.navn}</option>)}
                </select>
              </div>
              <div>
                <label style={{ fontSize: 11, color: SK.soft, fontWeight: 600, letterSpacing: 0.05, textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>Til avdeling</label>
                <select className="ok-input" value={tilAvd} onChange={e => setTilAvd(e.target.value)}>
                  {OK_AVDELINGER.filter(a => a.id !== fraAvd).map(a => <option key={a.id} value={a.id}>{a.navn}</option>)}
                </select>
              </div>
              <div style={{ gridColumn: '1 / -1' }}>
                <label style={{ fontSize: 11, color: SK.soft, fontWeight: 600, letterSpacing: 0.05, textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>Kontogruppe</label>
                <select className="ok-input" value={konto} onChange={e => setKonto(Number(e.target.value))}>
                  <option value={5000}>5000 · Lønn fast ansatte</option>
                  <option value={5400}>5400 · Arbeidsgiveravgift & sosialt</option>
                  <option value={6300}>6300 · Husleie & lokaler</option>
                  <option value={6500}>6500 · Inventar & datautstyr</option>
                  <option value={6700}>6700 · Fremmedtjenester</option>
                  <option value={6800}>6800 · Kontor, IT, telefon</option>
                  <option value={7100}>7100 · Reise & opphold</option>
                  <option value={7700}>7700 · Kurs, opplæring, mat</option>
                </select>
              </div>
            </div>
          )}
          {step === 2 && (
            <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 }}>Beløp (NOK)</label>
                <input
                  className="ok-input"
                  type="number"
                  value={belop}
                  onChange={e => setBelop(Number(e.target.value))}
                  style={{ fontVariantNumeric: 'tabular-nums', fontSize: 16, fontWeight: 600 }}
                />
              </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 skal denne kostnaden flyttes? Vis til faktura/bilag, periode, allokerings­grunnlag."
                  style={{ resize: 'vertical', fontFamily: 'inherit' }}
                />
              </div>
              <div style={{ background: SK.iceBlueLight, padding: 12, borderRadius: 8, fontSize: 12, lineHeight: 1.45 }}>
                <div style={{ fontSize: 10.5, color: SK.soft, fontWeight: 600, letterSpacing: 0.05, textTransform: 'uppercase', marginBottom: 4 }}>Regel som gjelder</div>
                <div style={{ fontWeight: 600 }}>{regel.regel}</div>
                <div style={{ color: SK.soft, marginTop: 2 }}>{regel.krav}</div>
              </div>
            </div>
          )}
          {step === 3 && (
            <div>
              <div style={{ background: SK.iceBlueLight, padding: 16, borderRadius: 10 }}>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, fontSize: 13 }}>
                  <div><b>Fra:</b> {findAvd(fraAvd)?.navn}</div>
                  <div><b>Til:</b> {findAvd(tilAvd)?.navn}</div>
                  <div><b>Konto:</b> {konto}</div>
                  <div><b>Beløp:</b> {okFmtKr(belop)} kr</div>
                </div>
                <div style={{ fontSize: 12, color: SK.soft, marginTop: 10, paddingTop: 10, borderTop: '1px solid rgba(17,24,61,.08)' }}>
                  <b>Begrunnelse:</b> {begrunnelse || <i>(ingen)</i>}
                </div>
              </div>
              <div style={{ marginTop: 14, fontSize: 11.5, color: SK.soft, lineHeight: 1.5 }}>
                Når du sender, varsles avdelingsleder for <b style={{ color: SK.ink }}>{findAvd(tilAvd)?.navn}</b> ({TEAM[findAvd(tilAvd)?.leder]?.n}). De må godkjenne før kostnaden posteres i Finago.
                {(belop > 20_000) && <> Saken eskaleres deretter til økonomisjef (Øystein Sand) før postering.</>}
              </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>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// WORKSPACE
// ═══════════════════════════════════════════════════════════════════════════
function OkonomiWorkspaceMock({ go }) {
  const [tab, setTab] = React.useState('oversikt');
  const [rolle, setRolle] = React.useState('daglig-leder');
  const [flytt, setFlytt] = React.useState({ open: false });

  const tabs = [
    { id: 'oversikt', label: 'Oversikt' },
    { id: 'min', label: 'Min avdeling' },
    { id: 'konsern', label: 'Konsernregnskap' },
    { id: 'flytting', label: `Kostnadsflytting · ${OK_FLYTT.filter(f => f.status === 'venter-mottaker' || f.status === 'venter-okonomi').length}` },
    { id: 'lonn', label: `Lønn / HR · ${OK_LONN_KORENINGER.apneEndringer + OK_LONN_KORENINGER.ventendeHR}` },
    { id: 'rapporter', label: 'Rapporter' },
  ];

  return (
    <div className="ok-content__inner">
      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 16, marginBottom: 14 }}>
        <div>
          <div style={{ fontSize: 11, fontWeight: 600, color: SK.soft, letterSpacing: 0.08, textTransform: 'uppercase' }}>Modul</div>
          <h1 style={{ margin: '4px 0 0', fontSize: 26, fontWeight: 600, letterSpacing: -0.01 }}>Økonomi</h1>
        </div>
        <div style={{ marginLeft: 'auto' }}>
          <RolleVelger value={rolle} onChange={setRolle} />
        </div>
      </div>

      <FinagoBanner />

      <Tabs tabs={tabs} value={tab} onChange={setTab} />

      {tab === 'oversikt' && <TabOversikt rolle={rolle} goTab={setTab} />}
      {tab === 'min' && <TabMinAvdeling goTab={setTab} setFlytt={setFlytt} />}
      {tab === 'konsern' && <TabKonsern />}
      {tab === 'flytting' && <TabFlytting setFlytt={setFlytt} rolle={rolle} />}
      {tab === 'lonn' && <TabLonnHR />}
      {tab === 'rapporter' && <TabRapporter rolle={rolle} />}

      <NyFlyttingModal open={flytt.open} onClose={() => setFlytt({ open: false })} prefyll={flytt} />
    </div>
  );
}

Object.assign(window, { OkonomiWorkspaceMock });
