// dashboard-screens.jsx — Tilpassbar Forside.
// Brukeren kan bytte mal, legge til/fjerne/flytte widgets, og lagre bokmerker
// til tredjepartssystemer. Alt persisteres pr. nettleser (localStorage).
// Erstatter den gamle Dashboard-komponenten.

// ── Persistens-hjelpere ──────────────────────────────────────────────────────
const DASH_IDAG = new Date('2026-05-21');
const dashRead = (key, fb) => { try { const v = localStorage.getItem(key); return v ? JSON.parse(v) : fb; } catch (e) { return fb; } };
const dashWrite = (key, v) => { try { localStorage.setItem(key, JSON.stringify(v)); } catch (e) {} };
const dashDager = (iso) => iso ? Math.round((new Date(iso) - DASH_IDAG) / 86400000) : null;
const dashMnd = ['jan', 'feb', 'mar', 'apr', 'mai', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'des'];

// Liten gjenbrukbar liste-rad
const DashRow = ({ children, onClick, last }) => (
  <div onClick={onClick} style={{
    padding: '10px 0', borderTop: last ? 'none' : '1px solid rgba(17,24,61,.06)',
    display: 'flex', gap: 10, alignItems: 'center', cursor: onClick ? 'pointer' : 'default',
  }}>{children}</div>
);

// ═══════════════════════════════════════════════════════════════════════════
// WIDGETS
// ═══════════════════════════════════════════════════════════════════════════
function WKpi() {
  const active = PROJECTS.filter(p => p.status !== 'done');
  const risk = PROJECTS.filter(p => p.status === 'risk').length;
  const delay = PROJECTS.filter(p => p.status === 'delay').length;
  const totalTiltak = PROJECTS.reduce((s, p) => s + p.openTiltak, 0);
  const tB = PROJECTS.reduce((s, p) => s + p.budget.plan, 0);
  const tS = PROJECTS.reduce((s, p) => s + p.budget.spent, 0);
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5, 1fr)', gap: 14 }}>
      <Card padded><KPI label="Aktive prosjekter" value={active.length} sub={`${PROJECTS.length - active.length} avsluttet`} /></Card>
      <Card padded><KPI label="I risiko" value={risk} sub={`av ${active.length} aktive`} accent={risk > 0} /></Card>
      <Card padded><KPI label="Forsinkelse" value={delay} sub={delay > 0 ? 'krever handling' : 'på spor'} accent={delay > 0} /></Card>
      <Card padded><KPI label="Åpne tiltak" value={totalTiltak} sub="siste 90 dager" /></Card>
      <Card padded><KPI label="Budsjett brukt" value={`${Math.round(tS / tB * 100)} %`} sub={`${Math.round(tS / 1000)}k av ${Math.round(tB / 1000)}k`} /></Card>
    </div>
  );
}

function WPortefolje({ go }) {
  const active = PROJECTS.filter(p => p.status !== 'done');
  const dist = ['track', 'risk', 'delay', 'draft'].map(s => ({ s, n: active.filter(p => p.status === s).length }));
  const tot = dist.reduce((sum, x) => sum + x.n, 0);
  const farge = (s) => s === 'track' ? SK.success : s === 'risk' ? SK.warn : s === 'delay' ? SK.coral : SK.lightBlue;
  return (
    <Card title="Porteføljestatus"
      action={<Button size="sm" variant="ghost" onClick={() => go({ screen: 'projects' })}>Se alle ({PROJECTS.length}) {I.chevron}</Button>}>
      <div style={{ display: 'flex', height: 10, borderRadius: 99, overflow: 'hidden', marginBottom: 12 }}>
        {dist.map((d, i) => d.n > 0 && <div key={i} style={{ width: `${(d.n / tot) * 100}%`, background: farge(d.s) }} />)}
      </div>
      <div style={{ display: 'flex', gap: 18, fontSize: 12, flexWrap: 'wrap' }}>
        {dist.map((d, i) => (
          <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
            <span style={{ width: 8, height: 8, borderRadius: '50%', background: farge(d.s) }} />
            <span style={{ color: SK.soft, fontWeight: 500 }}>{STATUS_LABELS[d.s]}</span>
            <span style={{ fontWeight: 600 }}>{d.n}</span>
          </div>
        ))}
      </div>
    </Card>
  );
}

function WFrister({ go }) {
  const upcoming = PROJECTS.filter(p => p.status !== 'done').map(p => ({ ...p, days: daysUntil(p.end) })).sort((a, b) => a.days - b.days).slice(0, 5);
  return (
    <Card title="Kommende frister" padded={false}>
      <table className="ok-table"><tbody>
        {upcoming.map(p => (
          <TR key={p.id} onClick={() => go({ screen: 'project', id: p.id })}>
            <td style={{ paddingLeft: 18 }}>
              <div style={{ fontWeight: 600, fontSize: 12.5 }}>{p.name}</div>
              <div style={{ fontSize: 11, color: SK.soft, marginTop: 2 }}>{p.nextMilestone}</div>
            </td>
            <td style={{ paddingRight: 18, textAlign: 'right' }}>
              <div style={{ fontWeight: 600, fontSize: 12.5, color: p.days < 14 ? SK.coral : SK.ink }}>{p.days < 0 ? `${Math.abs(p.days)} d forsinket` : `om ${p.days} d`}</div>
              <div style={{ fontSize: 11, color: SK.soft }}>{fmtDate(p.end)}</div>
            </td>
          </TR>
        ))}
      </tbody></table>
    </Card>
  );
}

function WKrever({ go }) {
  const mine = PROTOCOLS.flatMap(pr => pr.tiltak.filter(t => (t.ansvarlig === 'KS' || t.gruppe === 'Ledergruppen') && t.status !== 'done').map(t => ({ ...t, protokoll: pr.title, protokollId: pr.id })));
  return (
    <Card title="Krever deg" action={<span style={{ background: SK.coral, color: '#fff', padding: '2px 8px', borderRadius: 99, fontSize: 11, fontWeight: 600 }}>{mine.length}</span>}>
      {mine.slice(0, 5).map((t, i) => (
        <DashRow key={i} onClick={() => go({ screen: 'protocol', id: t.protokollId })} last={i === Math.min(mine.length, 5) - 1}>
          <input type="checkbox" style={{ marginTop: 0, accentColor: SK.coral, flexShrink: 0 }} onClick={e => e.stopPropagation()} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 12.5, lineHeight: 1.35 }}>{t.title}</div>
            <div style={{ fontSize: 11, color: SK.soft, marginTop: 3 }}>Fra: {t.protokoll}</div>
          </div>
          <Pill status={daysUntil(t.frist) < 3 ? 'delay' : 'draft'}>{daysUntil(t.frist) < 0 ? `${Math.abs(daysUntil(t.frist))}d` : daysUntil(t.frist) === 0 ? 'i dag' : `${daysUntil(t.frist)}d`}</Pill>
        </DashRow>
      ))}
    </Card>
  );
}

function WProtokoller({ go }) {
  return (
    <Card title="Nylige protokoller" padded={false}
      action={<Button size="sm" variant="ghost" onClick={() => go({ screen: 'protocols' })}>Alle {I.chevron}</Button>}>
      <table className="ok-table"><tbody>
        {PROTOCOLS.slice(0, 4).map(pr => (
          <TR key={pr.id} onClick={() => go({ screen: 'protocol', id: pr.id })}>
            <td style={{ paddingLeft: 18 }}>
              <div style={{ fontWeight: 600, fontSize: 12.5 }}>{pr.title}</div>
              <div style={{ fontSize: 11, color: SK.soft, marginTop: 2 }}>{fmtDate(pr.date)} · {pr.tiltak.length} tiltak</div>
            </td>
            <td style={{ paddingRight: 18, textAlign: 'right' }}><AvatarGroup people={pr.attendees.map(k => TEAM[k])} /></td>
          </TR>
        ))}
      </tbody></table>
    </Card>
  );
}

function WIntegrasjoner() {
  const items = [
    { src: 'Visma', dot: SK.success, t: 'Lønnskjøring klar for godkjenning', s: 'uke 21 · 92 ansatte' },
    { src: 'Outlook', dot: SK.info, t: '12 nye e-poster, 3 høy prio', s: 'NAV Nordstrand venter svar' },
    { src: 'Teams', dot: SK.purple, t: '4 nye meldinger i # ledelse', s: 'sist: Marius R.' },
    { src: 'Kvalitet (ISO)', dot: SK.coral, t: '1 nytt avvik registrert', s: 'kategori: Miljø · OK:sykkel' },
    { src: 'SharePoint', dot: SK.green, t: '7 nye dokumenter denne uka', s: 'i 4 prosjekt-mapper' },
  ];
  return (
    <Card title="Fra integrasjonene">
      {items.map((x, i) => (
        <DashRow key={i} last={i === items.length - 1}>
          <span style={{ width: 8, height: 8, borderRadius: '50%', background: x.dot, flexShrink: 0 }} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 12.5 }}>{x.t}</div>
            <div style={{ fontSize: 11, color: SK.soft, marginTop: 2 }}>{x.src} · {x.s}</div>
          </div>
        </DashRow>
      ))}
    </Card>
  );
}

function WKvalitet({ go }) {
  const avvik = dashRead('ok_kval_avvik', typeof KVAL_AVVIK !== 'undefined' ? KVAL_AVVIK : []);
  const risiko = dashRead('ok_kval_risiko', typeof KVAL_RISIKO !== 'undefined' ? KVAL_RISIKO : []);
  const apne = avvik.filter(a => a.status !== 'lukket');
  const hoy = risiko.filter(r => r.sann * r.kons >= 12);
  return (
    <Card title="Kvalitet & ISO" action={<Button size="sm" variant="ghost" onClick={() => go({ screen: 'kvalitet' })}>Åpne {I.chevron}</Button>}>
      <div style={{ display: 'flex', gap: 10, marginBottom: 12 }}>
        {typeof ISOTag !== 'undefined' && <><ISOTag std="9001" /><ISOTag std="14001" /></>}
      </div>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 12 }}>
        <div style={{ padding: 10, background: SK.iceBlueLight, borderRadius: 8 }}>
          <div style={{ fontSize: 24, fontWeight: 700, color: apne.length > 4 ? SK.coral : SK.ink }}>{apne.length}</div>
          <div style={{ fontSize: 11, color: SK.soft }}>åpne avvik</div>
        </div>
        <div style={{ padding: 10, background: SK.iceBlueLight, borderRadius: 8 }}>
          <div style={{ fontSize: 24, fontWeight: 700, color: hoy.length > 0 ? SK.coral : SK.ink }}>{hoy.length}</div>
          <div style={{ fontSize: 11, color: SK.soft }}>høye/kritiske risikoer</div>
        </div>
      </div>
      {apne.slice(0, 3).map((a, i) => (
        <DashRow key={a.id} onClick={() => go({ screen: 'kvalitet', tab: 'avvik' })} last={i === Math.min(apne.length, 3) - 1}>
          <span style={{ fontSize: 10.5, fontWeight: 700, color: SK.soft, flexShrink: 0 }}>{a.nr}</span>
          <div style={{ flex: 1, minWidth: 0, fontSize: 12, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{a.tittel}</div>
          {typeof ISOTags !== 'undefined' && <ISOTags std={a.std} mini />}
        </DashRow>
      ))}
    </Card>
  );
}

function WIsoOppgaver({ go }) {
  const oppg = dashRead('ok_kval_oppg', typeof KVAL_OPPGAVER !== 'undefined' ? KVAL_OPPGAVER : []);
  const apne = oppg.filter(o => o.status !== 'done' && (o.ansvarlig === 'KK' || o.ansvarlig === 'KS')).slice(0, 5);
  const liste = apne.length ? apne : oppg.filter(o => o.status !== 'done').slice(0, 5);
  return (
    <Card title="Mine ISO-oppgaver" action={<Button size="sm" variant="ghost" onClick={() => go({ screen: 'kvalitet', tab: 'oppgaver' })}>Alle {I.chevron}</Button>}>
      {liste.map((o, i) => {
        const d = dashDager(o.frist);
        return (
          <DashRow key={o.id} onClick={() => go({ screen: 'kvalitet', tab: 'oppgaver' })} last={i === liste.length - 1}>
            <span style={{ width: 16, height: 16, borderRadius: 5, border: '2px solid rgba(17,24,61,.3)', flexShrink: 0 }} />
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12.5, lineHeight: 1.3 }}>{o.tittel}</div>
              <div style={{ marginTop: 3 }}>{typeof ISOTags !== 'undefined' && <ISOTags std={o.std} klausul={o.klausul} mini />}</div>
            </div>
            <span style={{ fontSize: 11, fontWeight: 600, color: d < 0 ? SK.coral : d < 7 ? '#8e5a05' : SK.soft, flexShrink: 0 }}>{d < 0 ? `${Math.abs(d)}d` : `${d}d`}</span>
          </DashRow>
        );
      })}
    </Card>
  );
}

function WArshjul({ go }) {
  const hend = (typeof ÅR_HENDELSER !== 'undefined' ? ÅR_HENDELSER : [])
    .map(h => ({ ...h, date: new Date(2026, h.mnd, h.dag) }))
    .filter(h => h.date >= DASH_IDAG && h.status !== 'gjennomført')
    .sort((a, b) => a.date - b.date).slice(0, 5);
  const kat = typeof ÅR_KATEGORIER !== 'undefined' ? ÅR_KATEGORIER : {};
  return (
    <Card title="Kommende i årshjul" action={<Button size="sm" variant="ghost" onClick={() => go({ screen: 'arshjul' })}>Årshjul {I.chevron}</Button>}>
      {hend.map((h, i) => (
        <DashRow key={h.id} onClick={() => go({ screen: 'arshjul' })} last={i === hend.length - 1}>
          <div style={{ textAlign: 'center', width: 36, flexShrink: 0 }}>
            <div style={{ fontSize: 15, fontWeight: 700, lineHeight: 1 }}>{h.dag}</div>
            <div style={{ fontSize: 9.5, color: SK.soft, textTransform: 'uppercase' }}>{dashMnd[h.mnd]}</div>
          </div>
          <span style={{ width: 6, height: 28, borderRadius: 99, background: (kat[h.kategori] || {}).farge || SK.soft, flexShrink: 0 }} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 12.5, lineHeight: 1.3 }}>{h.navn}</div>
            <div style={{ fontSize: 11, color: SK.soft, marginTop: 2 }}>{(kat[h.kategori] || {}).label || h.kategori}</div>
          </div>
        </DashRow>
      ))}
    </Card>
  );
}

function WHr({ go }) {
  const emp = (typeof ALL_EMPLOYEES !== 'undefined' ? ALL_EMPLOYEES : [])
    .filter(e => e.sluttDato).map(e => ({ ...e, d: dashDager(e.sluttDato) }))
    .filter(e => e.d >= 0 && e.d <= 200).sort((a, b) => a.d - b.d).slice(0, 5);
  return (
    <Card title="HR — utgående kontrakter" action={<Button size="sm" variant="ghost" onClick={() => go({ screen: 'hr' })}>HR {I.chevron}</Button>}>
      {emp.map((e, i) => (
        <DashRow key={e.i} onClick={() => go({ screen: 'hr' })} last={i === emp.length - 1}>
          <Avatar initials={e.i} color={e.c} size={26} />
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ fontSize: 12.5, fontWeight: 500 }}>{e.n}</div>
            <div style={{ fontSize: 11, color: SK.soft }}>{e.r}</div>
          </div>
          <span style={{ fontSize: 11, fontWeight: 600, color: e.d < 30 ? SK.coral : e.d < 90 ? '#8e5a05' : SK.soft, flexShrink: 0 }}>{e.d} d igjen</span>
        </DashRow>
      ))}
      {emp.length === 0 && <div style={{ fontSize: 12, color: SK.soft, padding: '8px 0' }}>Ingen utgående kontrakter innen 200 dager.</div>}
    </Card>
  );
}

function WOkonomi({ go }) {
  const sel = typeof OK_SELSKAPER !== 'undefined' ? OK_SELSKAPER : [];
  const fmtM = (v) => `${(v / 1e6).toFixed(2).replace('.', ',')} M`;
  return (
    <Card title="Økonomi — selskaper" action={<Button size="sm" variant="ghost" onClick={() => go({ screen: 'finance' })}>Økonomi {I.chevron}</Button>}>
      {sel.map((s, i) => {
        const over = s.resultat >= s.budsjettResultat;
        return (
          <DashRow key={s.id} onClick={() => go({ screen: 'finance' })} last={i === sel.length - 1}>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12.5, fontWeight: 600 }}>{s.navn}</div>
              <div style={{ fontSize: 11, color: SK.soft }}>{s.ansatte} ansatte</div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontSize: 13, fontWeight: 700, color: s.resultat >= 0 ? SK.ink : SK.coral }}>{s.resultat >= 0 ? '+' : ''}{fmtM(s.resultat)}</div>
              <div style={{ fontSize: 10.5, color: over ? SK.success : SK.coral }}>{over ? 'over' : 'under'} budsjett</div>
            </div>
          </DashRow>
        );
      })}
    </Card>
  );
}

function WNotat({ notat, setNotat }) {
  return (
    <Card title="Mitt notat" action={<span style={{ fontSize: 10.5, color: SK.soft }}>kun for deg</span>}>
      <textarea
        value={notat}
        onChange={e => setNotat(e.target.value)}
        placeholder="Skriv en huskelapp…"
        style={{
          width: '100%', minHeight: 110, border: '1px solid rgba(17,24,61,.12)', borderRadius: 8,
          padding: 10, fontFamily: 'inherit', fontSize: 12.5, color: SK.ink, resize: 'vertical', background: SK.iceBlueLight,
        }}
      />
    </Card>
  );
}

function WBokmerker({ bookmarks, setBookmarks, edit }) {
  const [navn, setNavn] = React.useState('');
  const [url, setUrl] = React.useState('');
  const add = () => {
    if (!navn.trim()) return;
    const init = navn.trim().slice(0, 2).toUpperCase();
    const farger = ['#586ba4', '#08605f', '#8e5a05', '#28589f', '#a01a25'];
    setBookmarks(list => [...list, { id: 'b-' + Date.now(), navn: navn.trim(), undertittel: 'Egendefinert lenke', farge: farger[list.length % farger.length], init, url: url.trim() || '#' }]);
    setNavn(''); setUrl('');
  };
  return (
    <Card title="Bokmerker & snarveier" action={<span style={{ fontSize: 10.5, color: SK.soft }}>{bookmarks.length} lenker</span>}>
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 8 }}>
        {bookmarks.map(b => (
          <a key={b.id} href={b.url} target="_blank" rel="noreferrer" style={{
            display: 'flex', alignItems: 'center', gap: 10, padding: '9px 11px', borderRadius: 10,
            border: '1px solid rgba(17,24,61,.1)', textDecoration: 'none', color: SK.ink, position: 'relative',
          }}>
            <span style={{ width: 30, height: 30, borderRadius: 8, background: b.farge, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 12, fontWeight: 700, flexShrink: 0 }}>{b.init}</span>
            <div style={{ minWidth: 0, flex: 1 }}>
              <div style={{ fontSize: 12.5, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{b.navn}</div>
              <div style={{ fontSize: 10.5, color: SK.soft, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>{b.undertittel}</div>
            </div>
            {edit && (
              <button onClick={e => { e.preventDefault(); e.stopPropagation(); setBookmarks(list => list.filter(x => x.id !== b.id)); }}
                title="Fjern" style={{ position: 'absolute', top: -7, right: -7, width: 20, height: 20, borderRadius: 99, border: '1px solid rgba(17,24,61,.15)', background: SK.pureWhite, color: SK.coral, cursor: 'pointer', display: 'flex', alignItems: 'center', justifyContent: 'center', fontSize: 13, lineHeight: 1, padding: 0 }}>×</button>
            )}
          </a>
        ))}
      </div>
      {edit && (
        <div style={{ marginTop: 12, padding: 12, background: SK.iceBlueLight, borderRadius: 10 }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: SK.soft, letterSpacing: 0.04, textTransform: 'uppercase', marginBottom: 8 }}>Legg til lenke</div>
          <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
            <input className="ok-input" placeholder="Navn (f.eks. Power BI)" value={navn} onChange={e => setNavn(e.target.value)} style={{ flex: 1, minWidth: 120 }} />
            <input className="ok-input" placeholder="https://…" value={url} onChange={e => setUrl(e.target.value)} style={{ flex: 1, minWidth: 120 }} />
            <Button size="sm" variant="primary" onClick={add} disabled={!navn.trim()}>Legg til</Button>
          </div>
        </div>
      )}
    </Card>
  );
}

// Registry: id → komponent
const DASH_REGISTRY = {
  kpi: WKpi, portefolje: WPortefolje, frister: WFrister, krever: WKrever,
  protokoller: WProtokoller, integrasjoner: WIntegrasjoner, kvalitet: WKvalitet,
  isooppgaver: WIsoOppgaver, arshjul: WArshjul, hr: WHr, okonomi: WOkonomi,
  bokmerker: WBokmerker, notat: WNotat,
};

// ═══════════════════════════════════════════════════════════════════════════
// FORSIDE — tilpassbar
// ═══════════════════════════════════════════════════════════════════════════
function Dashboard({ go }) {
  const [edit, setEdit] = React.useState(false);
  const [layout, setLayout] = React.useState(() => dashRead('ok_dash_layout', DASH_TEMPLATES.leder.widgets));
  const [malNavn, setMalNavn] = React.useState(() => dashRead('ok_dash_mal', 'leder'));
  const [bookmarks, setBookmarks] = React.useState(() => dashRead('ok_dash_bookmarks', DASH_BOOKMARKS_DEFAULT));
  const [notat, setNotat] = React.useState(() => dashRead('ok_dash_notat', ''));

  React.useEffect(() => dashWrite('ok_dash_layout', layout), [layout]);
  React.useEffect(() => dashWrite('ok_dash_mal', malNavn), [malNavn]);
  React.useEffect(() => dashWrite('ok_dash_bookmarks', bookmarks), [bookmarks]);
  React.useEffect(() => dashWrite('ok_dash_notat', notat), [notat]);

  const ctx = { go, edit, bookmarks, setBookmarks, notat, setNotat };
  const applyMal = (key) => { setMalNavn(key); setLayout(DASH_TEMPLATES[key].widgets.slice()); };
  const fjern = (id) => setLayout(l => l.filter(x => x !== id));
  const leggTil = (id) => setLayout(l => l.includes(id) ? l : [...l, id]);
  const flytt = (id, dir) => setLayout(l => {
    const i = l.indexOf(id); const j = i + dir;
    if (i < 0 || j < 0 || j >= l.length) return l;
    const n = l.slice(); [n[i], n[j]] = [n[j], n[i]]; return n;
  });

  const ledige = Object.keys(DASH_WIDGETS).filter(id => !layout.includes(id));

  return (
    <div className="ok-content__inner">
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 18, gap: 16, flexWrap: 'wrap' }}>
        <div>
          <div style={{ fontSize: 11, fontWeight: 600, color: SK.soft, letterSpacing: 0.08, textTransform: 'uppercase' }}>Torsdag 21. mai 2026 · uke 21</div>
          <h1 style={{ margin: '6px 0 0', fontSize: 28, fontWeight: 600, letterSpacing: -0.02 }}>God morgen, Kari</h1>
          <div style={{ marginTop: 4, color: SK.soft, fontSize: 13 }}>
            Mal: <strong style={{ color: SK.ink }}>{DASH_TEMPLATES[malNavn] ? DASH_TEMPLATES[malNavn].navn : 'Egendefinert'}</strong> · {layout.length} widgets
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          {!edit && <Button icon={I.download} size="sm">Eksporter rapport</Button>}
          <Button variant={edit ? 'primary' : 'default'} icon={edit ? I.check : I.cog} onClick={() => setEdit(e => !e)}>
            {edit ? 'Ferdig' : 'Tilpass forside'}
          </Button>
        </div>
      </div>

      {/* Tilpasningspanel */}
      {edit && (
        <Card padded style={{ marginBottom: 14, border: `1.5px solid ${SK.coral}` }}>
          <div style={{ marginBottom: 14 }}>
            <div style={{ fontSize: 11, fontWeight: 600, color: SK.soft, letterSpacing: 0.04, textTransform: 'uppercase', marginBottom: 8 }}>Velg mal</div>
            <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
              {Object.entries(DASH_TEMPLATES).map(([key, m]) => (
                <button key={key} onClick={() => applyMal(key)} title={m.beskr} style={{
                  textAlign: 'left', padding: '8px 12px', borderRadius: 10, cursor: 'pointer', fontFamily: 'inherit',
                  border: `1.5px solid ${malNavn === key ? SK.coral : 'rgba(17,24,61,.14)'}`,
                  background: malNavn === key ? SK.lightCoral + '55' : SK.pureWhite, minWidth: 150,
                }}>
                  <div style={{ fontSize: 12.5, fontWeight: 600, color: SK.ink }}>{m.navn}</div>
                  <div style={{ fontSize: 10.5, color: SK.soft, marginTop: 2 }}>{m.widgets.length} widgets</div>
                </button>
              ))}
            </div>
          </div>
          <div>
            <div style={{ fontSize: 11, fontWeight: 600, color: SK.soft, letterSpacing: 0.04, textTransform: 'uppercase', marginBottom: 8 }}>Legg til widget</div>
            {ledige.length === 0 ? (
              <div style={{ fontSize: 12, color: SK.soft }}>Alle widgets er lagt til.</div>
            ) : (
              <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>
                {ledige.map(id => (
                  <button key={id} onClick={() => leggTil(id)} style={{
                    display: 'inline-flex', alignItems: 'center', gap: 7, padding: '7px 11px', borderRadius: 99, cursor: 'pointer',
                    border: '1px dashed rgba(17,24,61,.25)', background: SK.pureWhite, fontFamily: 'inherit', fontSize: 12, color: SK.ink,
                  }}>
                    <span style={{ color: SK.coral, fontWeight: 700 }}>+</span> {DASH_WIDGETS[id].navn}
                  </button>
                ))}
              </div>
            )}
          </div>
        </Card>
      )}

      {/* Widget-grid */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 14, alignItems: 'start' }}>
        {layout.map(id => {
          const W = DASH_REGISTRY[id];
          const meta = DASH_WIDGETS[id];
          if (!W || !meta) return null;
          const full = meta.size === 'full';
          return (
            <div key={id} style={{ gridColumn: full ? '1 / -1' : 'auto', position: 'relative' }}>
              {edit && (
                <div style={{
                  position: 'absolute', top: -10, right: 8, zIndex: 5, display: 'flex', gap: 4,
                  background: SK.ink, borderRadius: 99, padding: '3px 4px', boxShadow: '0 4px 12px rgba(17,24,61,.25)',
                }}>
                  <CtrlBtn label="◀" title="Flytt frem" onClick={() => flytt(id, -1)} />
                  <CtrlBtn label="▶" title="Flytt bak" onClick={() => flytt(id, 1)} />
                  <CtrlBtn label="×" title="Fjern" danger onClick={() => fjern(id)} />
                </div>
              )}
              {edit && <div style={{ position: 'absolute', inset: 0, zIndex: 4, borderRadius: 12, border: '1.5px dashed rgba(242,84,92,.5)', pointerEvents: 'none' }} />}
              <W {...ctx} />
            </div>
          );
        })}
      </div>

      {layout.length === 0 && (
        <Card padded><div style={{ padding: 30, textAlign: 'center', color: SK.soft }}>Forsiden er tom. Trykk «Tilpass forside» for å legge til widgets eller velge en mal.</div></Card>
      )}
    </div>
  );
}

const CtrlBtn = ({ label, title, onClick, danger }) => (
  <button onClick={onClick} title={title} style={{
    width: 22, height: 22, borderRadius: 99, border: 'none', cursor: 'pointer', padding: 0,
    background: danger ? SK.coral : 'rgba(255,255,255,.16)', color: '#fff', fontSize: 12, fontWeight: 700,
    display: 'inline-flex', alignItems: 'center', justifyContent: 'center', fontFamily: 'inherit',
  }}>{label}</button>
);

Object.assign(window, { Dashboard });
