// vvj-screens-2.jsx — Kontrakter, Timer, NyBy, Lønn & forskudd, Ansattportal

// ═══════════════════════════════════════════════════════════════════════════
// KONTRAKTER
// ═══════════════════════════════════════════════════════════════════════════
function VVJKontrakter({ setTab, setSelectedAnsattId }) {
  const [view, setView] = React.useState('kontrakter'); // kontrakter | maler

  const utkast = VVJ_KONTRAKTER.filter(k => k.status === 'utkast').length;
  const signering = VVJ_KONTRAKTER.filter(k => k.status === 'signering').length;
  const aktive = VVJ_KONTRAKTER.filter(k => k.status === 'aktiv').length;
  const utlopende = VVJ_KONTRAKTER.filter(k => k.status === 'utløper').length;

  return (
    <div>
      {/* KPI-bar */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 14 }}>
        <Card padded><KPI label="Utkast" value={utkast} sub="trenger review" accent={utkast > 0} /></Card>
        <Card padded><KPI label="Til signering" value={signering} sub="sendt til BankID" /></Card>
        <Card padded><KPI label="Aktive" value={aktive} sub="signerte kontrakter" /></Card>
        <Card padded><KPI label="Utløper snart" value={utlopende} sub="innen 30 dager" accent={utlopende > 0} /></Card>
      </div>

      <Card padded={false}>
        <div style={{ padding: '10px 16px', display: 'flex', alignItems: 'center', gap: 10, borderBottom: '1px solid rgba(17,24,61,.08)' }}>
          <div style={{ display: 'flex', gap: 4 }}>
            <button onClick={() => setView('kontrakter')} className="ok-btn ok-btn--sm" style={{
              background: view === 'kontrakter' ? SK.ink : 'transparent',
              color: view === 'kontrakter' ? '#fff' : SK.ink,
              borderColor: view === 'kontrakter' ? SK.ink : 'rgba(17,24,61,.15)',
            }}>Kontrakter ({VVJ_KONTRAKTER.length})</button>
            <button onClick={() => setView('maler')} className="ok-btn ok-btn--sm" style={{
              background: view === 'maler' ? SK.ink : 'transparent',
              color: view === 'maler' ? '#fff' : SK.ink,
              borderColor: view === 'maler' ? SK.ink : 'rgba(17,24,61,.15)',
            }}>Maler ({VVJ_MALER.length})</button>
          </div>
          <div style={{ marginLeft: 'auto', display: 'flex', gap: 6 }}>
            <Button size="sm" icon={I.download}>Eksporter</Button>
            <Button size="sm" variant="primary" icon={I.plus}>
              {view === 'maler' ? 'Ny mal' : 'Ny kontrakt fra mal'}
            </Button>
          </div>
        </div>

        {view === 'kontrakter' ? (
          <table className="ok-table">
            <thead>
              <tr>
                <th style={{ paddingLeft: 18 }}>Ansatt</th>
                <th>Mal</th>
                <th>Eier</th>
                <th>Opprettet</th>
                <th>Sendt</th>
                <th>Signert</th>
                <th>Status</th>
                <th></th>
              </tr>
            </thead>
            <tbody>
              {VVJ_KONTRAKTER.map(k => {
                const a = VVJ_ANSATTE.find(x => x.id === k.ansattId);
                const mal = VVJ_MALER.find(m => m.id === k.mal);
                const pillMap = {
                  utkast:    { cls: 'draft',  label: 'Utkast' },
                  signering: { cls: 'risk',   label: 'Til signering' },
                  aktiv:     { cls: 'track',  label: 'Aktiv' },
                  utløper:   { cls: 'delay',  label: 'Utløper snart' },
                };
                const pill = pillMap[k.status];
                return (
                  <TR key={k.id} onClick={() => { setSelectedAnsattId(k.ansattId); setTab('ansatte'); }}>
                    <td style={{ paddingLeft: 18 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <Avatar initials={a?.initials} color={a?.color} size={22} />
                        <div>
                          <div style={{ fontWeight: 600, fontSize: 12.5 }}>{a?.name}</div>
                          <div style={{ fontSize: 11, color: SK.soft, marginTop: 1 }}>{a?.role}</div>
                        </div>
                      </div>
                    </td>
                    <td style={{ fontSize: 12 }}>{mal?.name}</td>
                    <td>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                        <Avatar initials={TEAM[k.eier]?.i} color={TEAM[k.eier]?.c} size={20} />
                        <span style={{ fontSize: 12 }}>{TEAM[k.eier]?.n?.split(' ')[0]}</span>
                      </div>
                    </td>
                    <td style={{ fontSize: 12 }}>{vvjFmtDate(k.created)}</td>
                    <td style={{ fontSize: 12, color: k.sentDigSig ? SK.ink : SK.soft }}>{k.sentDigSig ? vvjFmtDate(k.sentDigSig) : '—'}</td>
                    <td style={{ fontSize: 12, color: k.signed ? SK.ink : SK.soft }}>{k.signed ? vvjFmtDate(k.signed) : '—'}</td>
                    <td><Pill status={pill.cls}>{pill.label}</Pill></td>
                    <td style={{ paddingRight: 18, textAlign: 'right' }}>
                      <span style={{ color: SK.soft }}>{I.chevron}</span>
                    </td>
                  </TR>
                );
              })}
            </tbody>
          </table>
        ) : (
          <div style={{ padding: 18, display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 14 }}>
            {VVJ_MALER.map(m => (
              <div key={m.id} style={{ border: '1px solid rgba(17,24,61,.08)', borderRadius: 10, padding: 16 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
                  <span style={{ width: 36, height: 36, borderRadius: 8, background: SK.iceBlue, display: 'flex', alignItems: 'center', justifyContent: 'center', color: SK.ink }}>
                    {VI.briefcase}
                  </span>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontWeight: 600, fontSize: 14 }}>{m.name}</div>
                    <div style={{ fontSize: 11.5, color: SK.soft }}>{m.basis}</div>
                  </div>
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 4, fontSize: 12, color: SK.soft, marginBottom: 12 }}>
                  <div><b style={{ color: SK.ink }}>Arbeidstid:</b> {m.timer}</div>
                  <div><b style={{ color: SK.ink }}>Sats:</b> {m.kr}</div>
                  <div><b style={{ color: SK.ink }}>Klausuler:</b> {m.clauses} stk</div>
                  <div><b style={{ color: SK.ink }}>Sist oppdatert:</b> {vvjFmtDate(m.sist)}</div>
                </div>
                <div style={{ display: 'flex', gap: 6 }}>
                  <Button size="sm" variant="primary">Opprett ny</Button>
                  <Button size="sm" variant="ghost">Rediger mal</Button>
                </div>
              </div>
            ))}
          </div>
        )}
      </Card>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// TIMER — godkjenning + ukestabell
// ═══════════════════════════════════════════════════════════════════════════
function VVJTimer() {
  // Vi viser uke 21 (18.-21. mai = man-tor)
  const DAGER = [
    { iso: '2026-05-18', kort: 'Man', dato: '18.05' },
    { iso: '2026-05-19', kort: 'Tir', dato: '19.05' },
    { iso: '2026-05-20', kort: 'Ons', dato: '20.05' },
    { iso: '2026-05-21', kort: 'Tor', dato: '21.05' },
    { iso: '2026-05-22', kort: 'Fre', dato: '22.05' },
  ];
  const ANSATTE_MED_TIMER = VVJ_ANSATTE.filter(a => a.status === 'aktiv' || a.status === 'pause')
    .map(a => {
      const timer = VVJ_TIMER.filter(t => t.ansattId === a.id);
      const total = timer.reduce((s, t) => s + t.hours, 0);
      const ventende = timer.filter(t => t.status === 'ventende').length;
      const avvist = timer.filter(t => t.status === 'avvist').length;
      return { ...a, _timer: timer, _total: total, _ventende: ventende, _avvist: avvist };
    })
    .filter(a => a._timer.length > 0)
    .sort((b, a) => a._ventende - b._ventende);

  const totalVentende = VVJ_TIMER.filter(t => t.status === 'ventende').reduce((s, t) => s + t.hours, 0);
  const totalGodkjent = VVJ_TIMER.filter(t => t.status === 'godkjent').reduce((s, t) => s + t.hours, 0);
  const totalAvvist = VVJ_TIMER.filter(t => t.status === 'avvist').length;
  const totalNyBy = VVJ_TIMER.filter(t => t.kilde === 'NyBy-API').reduce((s, t) => s + t.hours, 0);

  return (
    <div>
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 14 }}>
        <Card padded><KPI label="Timer godkjent · uke 21" value={`${totalGodkjent}`} sub="til lønnskjøring" /></Card>
        <Card padded><KPI label="Venter godkjenning" value={`${totalVentende}`} sub="timer fra ansatte" accent={totalVentende > 0} /></Card>
        <Card padded><KPI label="Avvist" value={totalAvvist} sub="krever oppfølging" accent={totalAvvist > 0} /></Card>
        <Card padded><KPI label="Fra NyBy" value={`${totalNyBy} t`} sub={`${VVJ_TIMER.filter(t=>t.kilde==='NyBy-API').length} oppdrag synket inn`} /></Card>
      </div>

      <Card title={`Uke 21 (${DAGER[0].dato}–${DAGER[DAGER.length-1].dato} · 2026)`}
        padded={false}
        action={
          <div style={{ display: 'flex', gap: 6 }}>
            <Button size="sm" icon={I.download}>CSV / SAF-T</Button>
            <Button size="sm" variant="primary" icon={VI.export}>Send til Visma</Button>
          </div>
        }
      >
        <div style={{ overflow: 'auto' }}>
          <table className="ok-table">
            <thead>
              <tr>
                <th style={{ paddingLeft: 18, minWidth: 220 }}>Ansatt</th>
                {DAGER.map(d => (
                  <th key={d.iso} style={{ textAlign: 'center', minWidth: 80 }}>
                    <div style={{ fontSize: 10, color: SK.soft, fontWeight: 500 }}>{d.kort}</div>
                    <div style={{ fontWeight: 600 }}>{d.dato}</div>
                  </th>
                ))}
                <th style={{ textAlign: 'right' }}>Sum</th>
                <th style={{ textAlign: 'right', paddingRight: 18 }}>Handling</th>
              </tr>
            </thead>
            <tbody>
              {ANSATTE_MED_TIMER.map(a => {
                const sumUke = a._timer.filter(t => t.date >= '2026-05-18' && t.date <= '2026-05-22').reduce((s, t) => s + t.hours, 0);
                return (
                  <tr key={a.id} style={{ cursor: 'default' }}>
                    <td style={{ paddingLeft: 18 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <Avatar initials={a.initials} color={a.color} size={24} />
                        <div>
                          <div style={{ fontWeight: 600, fontSize: 12.5 }}>{a.name}</div>
                          <div style={{ fontSize: 10.5, color: SK.soft }}>{a.role}</div>
                        </div>
                      </div>
                    </td>
                    {DAGER.map(d => {
                      const t = a._timer.find(x => x.date === d.iso);
                      if (!t) return <td key={d.iso} style={{ textAlign: 'center', color: 'rgba(17,24,61,.18)' }}>·</td>;
                      const bg = t.status === 'godkjent' ? 'transparent'
                        : t.status === 'ventende' ? '#fdeac8'
                        : t.status === 'avvist' ? SK.lightCoral : 'transparent';
                      const color = t.status === 'avvist' ? '#a01a25' : SK.ink;
                      return (
                        <td key={d.iso} style={{ textAlign: 'center', padding: 8 }}>
                          <div style={{
                            background: bg, padding: '6px 0', borderRadius: 6,
                            color, fontWeight: 600, fontSize: 13, position: 'relative',
                          }}>
                            {t.hours}
                            {t.kilde === 'NyBy-API' ? (
                              <span style={{
                                position: 'absolute', top: 2, right: 2,
                                fontSize: 8, fontWeight: 700, color: SK.purple, letterSpacing: 0.05,
                              }}>NB</span>
                            ) : null}
                          </div>
                        </td>
                      );
                    })}
                    <td style={{ textAlign: 'right', fontWeight: 600, fontSize: 13.5 }}>{sumUke}</td>
                    <td style={{ paddingRight: 18, textAlign: 'right' }}>
                      {a._ventende > 0 ? (
                        <Button size="sm" variant="primary">Godkjenn ({a._ventende})</Button>
                      ) : a._avvist > 0 ? (
                        <Button size="sm" variant="accent">Følg opp</Button>
                      ) : (
                        <span style={{ fontSize: 11, color: SK.success, fontWeight: 600 }}>✓ alle godkjent</span>
                      )}
                    </td>
                  </tr>
                );
              })}
              <tr style={{ background: SK.iceBlueLight, fontWeight: 700 }}>
                <td style={{ paddingLeft: 18, fontSize: 12 }}>Sum uke 21</td>
                {DAGER.map(d => {
                  const sum = VVJ_TIMER.filter(t => t.date === d.iso).reduce((s, t) => s + t.hours, 0);
                  return <td key={d.iso} style={{ textAlign: 'center', fontSize: 13 }}>{sum || '—'}</td>;
                })}
                <td style={{ textAlign: 'right', fontSize: 13.5 }}>
                  {VVJ_TIMER.filter(t => t.date >= '2026-05-18' && t.date <= '2026-05-22').reduce((s, t) => s + t.hours, 0)}
                </td>
                <td style={{ paddingRight: 18 }}></td>
              </tr>
            </tbody>
          </table>
        </div>
        <div style={{ padding: '12px 18px', display: 'flex', alignItems: 'center', gap: 18, borderTop: '1px solid rgba(17,24,61,.06)', fontSize: 11.5, color: SK.soft }}>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
            <span style={{ width: 12, height: 12, background: '#fdeac8', borderRadius: 3 }} /> Venter godkjenning
          </span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
            <span style={{ width: 12, height: 12, background: SK.lightCoral, borderRadius: 3 }} /> Avvist
          </span>
          <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}>
            <b style={{ color: SK.purple }}>NB</b> = importert fra NyBy
          </span>
        </div>
      </Card>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// NyBy
// ═══════════════════════════════════════════════════════════════════════════
function VVJNyBy() {
  const [filter, setFilter] = React.useState('tilgjengelig');
  const counts = {
    tilgjengelig: VVJ_NYBY_OPPDRAG.filter(o => o.status === 'tilgjengelig').length,
    påtatt:       VVJ_NYBY_OPPDRAG.filter(o => o.status === 'påtatt').length,
    fullført:     VVJ_NYBY_OPPDRAG.filter(o => o.status === 'fullført').length,
  };
  const liste = VVJ_NYBY_OPPDRAG.filter(o => o.status === filter);

  const totalUtbetaltViaNyBy = VVJ_NYBY_OPPDRAG.filter(o => o.status === 'fullført').reduce((s, o) => s + (o.timer * o.sats), 0);

  return (
    <div>
      {/* Integrasjons-status */}
      <Card padded style={{ marginBottom: 14, background: 'linear-gradient(to right, rgba(88,107,164,.06), rgba(88,107,164,.02))' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <span style={{ width: 44, height: 44, borderRadius: 10, background: SK.purple, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            {VI.nyby}
          </span>
          <div style={{ flex: 1 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
              <span style={{ fontWeight: 600, fontSize: 14 }}>NyBy-API · tilkoblet</span>
              <span style={{ width: 8, height: 8, borderRadius: '50%', background: SK.success }} />
            </div>
            <div style={{ fontSize: 12, color: SK.soft, marginTop: 3 }}>
              Sist sync: i dag 09:14 · neste sync om 32 min · API-v2 · 6 nye oppdrag siden i går
            </div>
          </div>
          <Button size="sm" variant="ghost" icon={VI.link}>Innstillinger</Button>
          <Button size="sm" icon={I.download}>Sync nå</Button>
        </div>
      </Card>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 14 }}>
        <Card padded><KPI label="Tilgjengelige nå" value={counts.tilgjengelig} sub="ferske fra NyBy" /></Card>
        <Card padded><KPI label="Påtatt" value={counts.påtatt} sub="ikke fullført ennå" /></Card>
        <Card padded><KPI label="Fullført i år" value={counts.fullført} sub="lagt på timegrunnlag" /></Card>
        <Card padded><KPI label="Utbetalt via NyBy" value={`${vvjFmtKrShort(totalUtbetaltViaNyBy)} kr`} sub="ekstrainntekt totalt" /></Card>
      </div>

      <Card padded={false}>
        <div style={{ padding: '12px 16px', display: 'flex', gap: 10, alignItems: 'center', borderBottom: '1px solid rgba(17,24,61,.08)' }}>
          <div style={{ display: 'flex', gap: 4 }}>
            {[
              ['tilgjengelig', `Tilgjengelig (${counts.tilgjengelig})`],
              ['påtatt',       `Påtatt (${counts.påtatt})`],
              ['fullført',     `Fullført (${counts.fullført})`],
            ].map(([k, l]) => (
              <button key={k} onClick={() => setFilter(k)} className="ok-btn ok-btn--sm" style={{
                background: filter === k ? SK.ink : 'transparent',
                color: filter === k ? '#fff' : SK.ink,
                borderColor: filter === k ? SK.ink : 'rgba(17,24,61,.15)',
              }}>{l}</button>
            ))}
          </div>
          <div style={{ marginLeft: 'auto', display: 'flex', gap: 6 }}>
            <Button size="sm" icon={VI.filter}>Filter</Button>
            <Button size="sm" variant="primary">Foreslå til ansatte</Button>
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 0 }}>
          {liste.map((o, i) => {
            const a = o.ansattId ? VVJ_ANSATTE.find(x => x.id === o.ansattId) : null;
            return (
              <div key={o.id} style={{
                padding: 16,
                borderTop: i >= 2 ? '1px solid rgba(17,24,61,.06)' : 'none',
                borderRight: i % 2 === 0 ? '1px solid rgba(17,24,61,.06)' : 'none',
              }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', gap: 12, marginBottom: 10 }}>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: 'flex', gap: 6, marginBottom: 4 }}>
                      <span style={{ fontSize: 10, fontWeight: 700, color: SK.purple, letterSpacing: 0.05, textTransform: 'uppercase' }}>NyBy · {o.type}</span>
                    </div>
                    <div style={{ fontWeight: 600, fontSize: 14, marginBottom: 4 }}>{o.tittel}</div>
                    <div style={{ fontSize: 11.5, color: SK.soft, display: 'flex', alignItems: 'center', gap: 4 }}>
                      <span style={{ display: 'inline-flex' }}>{VI.pin}</span>
                      {o.sted} · {o.oppdragsgiver}
                    </div>
                  </div>
                  <div style={{ textAlign: 'right' }}>
                    <div style={{ fontWeight: 600, fontSize: 16 }}>{o.timer} t</div>
                    <div style={{ fontSize: 11.5, color: SK.soft }}>{vvjFmtKr(o.sats)} kr/t</div>
                  </div>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginTop: 12, paddingTop: 12, borderTop: '1px solid rgba(17,24,61,.06)' }}>
                  <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4, color: SK.soft, fontSize: 11.5 }}>
                    {I.cal} {vvjFmtDate(o.dato)}
                  </span>
                  <span style={{ color: SK.soft, fontSize: 11.5 }}>·</span>
                  <span style={{ fontSize: 11.5, color: SK.ink, fontWeight: 600 }}>{vvjFmtKr(o.timer * o.sats)} kr totalt</span>
                  <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 8 }}>
                    {a ? (
                      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                        <Avatar initials={a.initials} color={a.color} size={20} />
                        <span style={{ fontSize: 11.5 }}>{a.name.split(' ')[0]}</span>
                      </div>
                    ) : null}
                    {o.status === 'tilgjengelig' ? <Button size="sm" variant="primary">Tildel</Button> : null}
                    {o.status === 'påtatt' ? <Pill status="draft">Avtalt</Pill> : null}
                    {o.status === 'fullført' ? <Pill status="track">Fullført</Pill> : null}
                  </div>
                </div>
              </div>
            );
          })}
          {liste.length === 0 ? (
            <div style={{ gridColumn: '1 / -1', padding: 40, textAlign: 'center', color: SK.soft, fontSize: 13 }}>
              Ingen oppdrag i denne kategorien.
            </div>
          ) : null}
        </div>
      </Card>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// LØNN & FORSKUDD
// ═══════════════════════════════════════════════════════════════════════════
function VVJLonn() {
  const periode = VVJ_LONNSPERIODE;
  const totalAccrued = VVJ_ANSATTE.reduce((s, a) => s + (a.accruedKr || 0), 0);
  const totalAdvanced = VVJ_ANSATTE.reduce((s, a) => s + (a.paidAdvanceKr || 0), 0);
  const totalNetto = totalAccrued - totalAdvanced;
  const forskuddVentende = VVJ_FORSKUDD.filter(f => f.status === 'ventende');
  const ansattePerLonn = VVJ_ANSATTE.filter(a => a.status === 'aktiv' || a.status === 'pause');

  const ansatteMedTotaler = ansattePerLonn.map(a => {
    const forskudd = VVJ_FORSKUDD.filter(f => f.ansattId === a.id);
    const utbetalt = forskudd.filter(f => f.status === 'utbetalt').reduce((s, f) => s + f.belop, 0);
    const ventende = forskudd.filter(f => f.status === 'ventende').reduce((s, f) => s + f.belop, 0);
    return { ...a, _forskuddUtbetalt: utbetalt, _forskuddVentende: ventende, _utestaende: (a.accruedKr || 0) - utbetalt - ventende };
  });

  return (
    <div>
      {/* Periode-banner */}
      <Card padded style={{ marginBottom: 14 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 18 }}>
          <div style={{ width: 56, height: 56, borderRadius: 12, background: SK.iceBlue, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
            <span style={{ fontSize: 22 }}>{I.cal}</span>
          </div>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 11, fontWeight: 600, color: SK.soft, letterSpacing: 0.08, textTransform: 'uppercase' }}>Lønnsperiode</div>
            <div style={{ fontSize: 20, fontWeight: 600, marginTop: 2 }}>{periode.label} <span style={{ color: SK.soft, fontSize: 13, fontWeight: 500 }}> · {vvjFmtDate(periode.start)} – {vvjFmtDate(periode.slutt)}</span></div>
            <div style={{ fontSize: 12.5, color: SK.soft, marginTop: 3 }}>
              Ordinær utbetaling: <b style={{ color: SK.ink }}>{vvjFmtDateLong(periode.lonningsDato)}</b> · Visma-eksport: <b style={{ color: SK.ink }}>{periode.vismaStatus === 'utkast' ? 'utkast' : periode.vismaStatus}</b>
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8, flexShrink: 0 }}>
            <Button size="sm" variant="ghost">Lukk periode</Button>
            <Button size="sm" variant="primary" icon={VI.export}>Eksporter til Visma</Button>
          </div>
        </div>
      </Card>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 14 }}>
        <Card padded><KPI label="Opptjent (mai)" value={`${vvjFmtKrShort(totalAccrued)} kr`} sub={`${ansattePerLonn.length} ansatte`} /></Card>
        <Card padded><KPI label="Forskudd utbetalt" value={`${vvjFmtKrShort(totalAdvanced)} kr`} sub={`${Math.round((totalAdvanced/totalAccrued)*100)}% av opptjent`} /></Card>
        <Card padded><KPI label="Til netto-utbetaling" value={`${vvjFmtKrShort(totalNetto)} kr`} sub="ved lønnskjøring 12/6" /></Card>
        <Card padded><KPI label="Forskudd · venter" value={forskuddVentende.length} sub={`${vvjFmtKr(forskuddVentende.reduce((s,f)=>s+f.belop,0))} kr totalt`} accent={forskuddVentende.length > 0} /></Card>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 14, marginBottom: 14 }}>
        {/* Forskudd-forespørsler */}
        <Card title={`Forskudd-forespørsler · ${forskuddVentende.length} venter`}
          padded={false}
          action={<span style={{ fontSize: 11, color: SK.soft }}>Auto-godkjenn under 60% av opptjent</span>}
        >
          <table className="ok-table">
            <thead>
              <tr>
                <th style={{ paddingLeft: 18 }}>Ansatt</th>
                <th>Forespurt</th>
                <th style={{ textAlign: 'right' }}>Beløp</th>
                <th style={{ textAlign: 'right' }}>% av opptjent</th>
                <th>Status</th>
                <th style={{ paddingRight: 18 }}></th>
              </tr>
            </thead>
            <tbody>
              {[...forskuddVentende, ...VVJ_FORSKUDD.filter(f => f.status === 'utbetalt').slice(-4)].map(f => {
                const a = VVJ_ANSATTE.find(x => x.id === f.ansattId);
                const pctAvOpp = a?.accruedKr > 0 ? Math.round((f.belop / a.accruedKr) * 100) : 0;
                return (
                  <tr key={f.id} style={{ cursor: 'default' }}>
                    <td style={{ paddingLeft: 18 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                        <Avatar initials={a?.initials} color={a?.color} size={22} />
                        <span style={{ fontSize: 12.5, fontWeight: 500 }}>{a?.name}</span>
                      </div>
                    </td>
                    <td style={{ fontSize: 12 }}>{vvjFmtDate(f.dato)}</td>
                    <td style={{ textAlign: 'right', fontWeight: 600, fontSize: 13 }}>{vvjFmtKr(f.belop)} kr</td>
                    <td style={{ textAlign: 'right', fontSize: 12, color: pctAvOpp > 50 ? SK.coral : SK.soft }}>{pctAvOpp}%</td>
                    <td>
                      {f.status === 'ventende' ? (
                        <Pill status="risk">Venter</Pill>
                      ) : (
                        <Pill status="track">Utbetalt</Pill>
                      )}
                    </td>
                    <td style={{ paddingRight: 18, textAlign: 'right' }}>
                      {f.status === 'ventende' ? (
                        <div style={{ display: 'flex', gap: 4, justifyContent: 'flex-end' }}>
                          <Button size="sm" variant="ghost">Avslå</Button>
                          <Button size="sm" variant="primary">Godkjenn</Button>
                        </div>
                      ) : (
                        <span style={{ fontSize: 11, color: SK.soft, fontFamily: 'monospace' }}>{f.ref}</span>
                      )}
                    </td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </Card>

        {/* Visma-eksport historikk */}
        <Card title="Lønnseksport · Visma" padded={false}
          action={<Button size="sm" variant="ghost">Innstillinger</Button>}
        >
          {VVJ_VISMA_EKSPORT.map((v, i) => (
            <div key={v.id} style={{ padding: '12px 18px', borderTop: i ? '1px solid rgba(17,24,61,.06)' : 'none' }}>
              <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 4 }}>
                <span style={{ fontWeight: 600, fontSize: 13 }}>{v.periode}</span>
                <Pill status="track">Utbetalt</Pill>
              </div>
              <div style={{ fontSize: 11.5, color: SK.soft, marginBottom: 6 }}>
                Eksportert {vvjFmtDate(v.dato)} · {v.ansatte} ansatte
              </div>
              <div style={{ fontSize: 12, display: 'flex', gap: 14 }}>
                <span style={{ color: SK.soft }}>Brutto <b style={{ color: SK.ink }}>{vvjFmtKr(v.brutto)}</b></span>
                <span style={{ color: SK.soft }}>− forsk. <b style={{ color: SK.ink }}>{vvjFmtKr(v.forskudd)}</b></span>
                <span style={{ color: SK.soft }}>= netto <b style={{ color: SK.ink }}>{vvjFmtKr(v.netto)}</b></span>
              </div>
              <div style={{ marginTop: 6, fontSize: 10.5, fontFamily: 'monospace', color: SK.soft }}>{v.filnavn}</div>
            </div>
          ))}
        </Card>
      </div>

      {/* Ansatt-saldo */}
      <Card title="Saldo pr. ansatt — denne perioden" padded={false}>
        <table className="ok-table">
          <thead>
            <tr>
              <th style={{ paddingLeft: 18 }}>Ansatt</th>
              <th style={{ textAlign: 'right' }}>Timer (mnd)</th>
              <th style={{ textAlign: 'right' }}>Sats</th>
              <th style={{ textAlign: 'right' }}>Opptjent</th>
              <th style={{ textAlign: 'right' }}>Forskudd</th>
              <th style={{ textAlign: 'right' }}>Ventende</th>
              <th style={{ textAlign: 'right', paddingRight: 18 }}>Til utbetaling</th>
            </tr>
          </thead>
          <tbody>
            {ansatteMedTotaler.map(a => (
              <tr key={a.id} style={{ cursor: 'default' }}>
                <td style={{ paddingLeft: 18 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <Avatar initials={a.initials} color={a.color} size={22} />
                    <div>
                      <div style={{ fontWeight: 500, fontSize: 12.5 }}>{a.name}</div>
                      <div style={{ fontSize: 10.5, color: SK.soft }}>{a.avd}</div>
                    </div>
                  </div>
                </td>
                <td style={{ textAlign: 'right', fontSize: 12.5 }}>{a.monthHours}</td>
                <td style={{ textAlign: 'right', fontSize: 12.5, color: SK.soft }}>{vvjFmtKr(a.hourRate)} kr</td>
                <td style={{ textAlign: 'right', fontWeight: 600, fontSize: 12.5 }}>{vvjFmtKr(a.accruedKr)}</td>
                <td style={{ textAlign: 'right', fontSize: 12.5, color: SK.soft }}>{vvjFmtKr(a._forskuddUtbetalt)}</td>
                <td style={{ textAlign: 'right', fontSize: 12.5, color: a._forskuddVentende ? SK.coral : SK.soft }}>
                  {a._forskuddVentende ? vvjFmtKr(a._forskuddVentende) : '—'}
                </td>
                <td style={{ textAlign: 'right', paddingRight: 18, fontWeight: 700, fontSize: 13.5 }}>{vvjFmtKr(a._utestaende)} kr</td>
              </tr>
            ))}
            <tr style={{ background: SK.iceBlueLight, fontWeight: 700 }}>
              <td style={{ paddingLeft: 18, fontSize: 12 }}>Sum</td>
              <td style={{ textAlign: 'right' }}>{ansatteMedTotaler.reduce((s, a) => s + a.monthHours, 0)}</td>
              <td></td>
              <td style={{ textAlign: 'right' }}>{vvjFmtKr(ansatteMedTotaler.reduce((s, a) => s + a.accruedKr, 0))}</td>
              <td style={{ textAlign: 'right' }}>{vvjFmtKr(ansatteMedTotaler.reduce((s, a) => s + a._forskuddUtbetalt, 0))}</td>
              <td style={{ textAlign: 'right' }}>{vvjFmtKr(ansatteMedTotaler.reduce((s, a) => s + a._forskuddVentende, 0))}</td>
              <td style={{ textAlign: 'right', paddingRight: 18, fontSize: 13.5 }}>{vvjFmtKr(ansatteMedTotaler.reduce((s, a) => s + a._utestaende, 0))} kr</td>
            </tr>
          </tbody>
        </table>
      </Card>
    </div>
  );
}

Object.assign(window, { VVJKontrakter, VVJTimer, VVJNyBy, VVJLonn });
