// ressursbank-screens.jsx — Ressursbank workspace + Mål & resultater tab + Wizard

// ── helpers ──────────────────────────────────────────────────────────────
const rbStatusMap = (s) => ({
  done:  { cls: 'track',  label: 'Fullført' },
  risk:  { cls: 'risk',   label: 'I risiko' },
  delay: { cls: 'delay',  label: 'Forsinket' },
  open:  { cls: 'draft',  label: 'Åpen' },
}[s] || { cls: 'draft', label: s });

const rbTrendIcon = (t) => {
  if (t === 'stigende') return <span style={{ color: SK.success, fontSize: 14 }}>▲</span>;
  if (t === 'synkende') return <span style={{ color: SK.coral, fontSize: 14 }}>▼</span>;
  return <span style={{ color: SK.soft, fontSize: 14 }}>—</span>;
};

// ═══════════════════════════════════════════════════════════════════════════
// RESSURSBANK WORKSPACE
// ═══════════════════════════════════════════════════════════════════════════
function RessursbankWorkspaceMock({ go }) {
  const [tab, setTab] = React.useState('maler');
  const [selectedMalId, setSelectedMalId] = React.useState(null);
  const [wizardOpen, setWizardOpen] = React.useState(false);
  const [wizardMalId, setWizardMalId] = React.useState(null);

  const tabs = [
    { id: 'maler',     label: `Prosjektmaler (${RB_MALER.length})` },
    { id: 'rammeverk', label: `Målrammeverk (${RB_RAMMEVERK.length})` },
    { id: 'dok',       label: `Dokumentmaler (${RB_DOKUMENTER.length})` },
  ];

  const openWizard = (malId) => {
    setWizardMalId(malId);
    setWizardOpen(true);
    setSelectedMalId(null);
  };

  return (
    <div className="ok-content__inner" style={{ maxWidth: 1280 }}>
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 18, gap: 24 }}>
        <div style={{ flex: 1 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 8 }}>
            <Pill status="track">Bibliotek</Pill>
            <span style={{ fontSize: 11.5, color: SK.soft, fontWeight: 500 }}>
              {RB_MALER.length} prosjektmaler · {RB_RAMMEVERK.length} rammeverk · {RB_DOKUMENTER.length} dokumentmaler
            </span>
          </div>
          <h1 style={{ margin: 0, fontSize: 28, fontWeight: 600, letterSpacing: -0.02 }}>
            Ressursbank
          </h1>
          <div style={{ marginTop: 6, color: SK.soft, fontSize: 13, maxWidth: 720 }}>
            Start nye prosjekter fra ferdige oppskrifter med mål, milepæler og roller på plass.
            Velg rammeverk for målsetting og last ned malverk for hver prosjektfase.
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8, flexShrink: 0 }}>
          <Button size="sm" icon={I.download}>Eksporter</Button>
          <Button variant="primary" icon={I.plus} onClick={() => { setTab('maler'); }}>
            Start nytt prosjekt
          </Button>
        </div>
      </div>

      <div className="ok-tabs" style={{ marginBottom: 20 }}>
        {tabs.map(t => (
          <button key={t.id}
            className={`ok-tab ${tab === t.id ? 'ok-tab--active' : ''}`}
            onClick={() => setTab(t.id)}
          >{t.label}</button>
        ))}
      </div>

      {tab === 'maler'     && <RBMalerView openMal={setSelectedMalId} openWizard={openWizard} />}
      {tab === 'rammeverk' && <RBRammeverkView />}
      {tab === 'dok'       && <RBDokumenterView />}

      {/* Mal-detalj modal */}
      {selectedMalId ? (
        <RBMalDetalj malId={selectedMalId} onClose={() => setSelectedMalId(null)} onStart={() => openWizard(selectedMalId)} />
      ) : null}

      {/* Wizard */}
      {wizardOpen ? (
        <RBWizard malId={wizardMalId} onClose={() => setWizardOpen(false)} go={go} />
      ) : null}
    </div>
  );
}

// ── Maler grid ───────────────────────────────────────────────────────────
function RBMalerView({ openMal, openWizard }) {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }}>
      {RB_MALER.map(m => (
        <Card key={m.id} padded={false} style={{ overflow: 'hidden', cursor: 'pointer' }}>
          <div onClick={() => openMal(m.id)} style={{ padding: 18 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
              <span style={{
                width: 38, height: 38, borderRadius: 9,
                background: `${m.accent}22`, color: m.accent,
                display: 'flex', alignItems: 'center', justifyContent: 'center',
              }}>{VI.briefcase}</span>
              <div>
                <div style={{ fontSize: 10.5, fontWeight: 700, color: SK.soft, letterSpacing: 0.06, textTransform: 'uppercase' }}>{m.type}</div>
                <div style={{ fontWeight: 600, fontSize: 14.5, lineHeight: 1.25 }}>{m.navn}</div>
              </div>
            </div>
            <div style={{ fontSize: 12.5, color: SK.soft, marginBottom: 14, lineHeight: 1.5, minHeight: 56 }}>
              {m.beskrivelse}
            </div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6, fontSize: 11.5, marginBottom: 12 }}>
              <RBMeta l="Varighet" v={m.varighet} />
              <RBMeta l="Faser" v={`${m.faser.length} stk`} />
              <RBMeta l="Team-roller" v={`${m.teamRoller.length} stk`} />
              <RBMeta l="KPIer foreslått" v={`${m.kpiForslag.length} stk`} />
            </div>
            <div style={{ fontSize: 10.5, color: SK.soft, paddingTop: 10, borderTop: '1px solid rgba(17,24,61,.06)' }}>
              {m.bruk}
            </div>
          </div>
          <div style={{ padding: '10px 14px', borderTop: '1px solid rgba(17,24,61,.06)', background: SK.iceBlueLight, display: 'flex', gap: 6 }}>
            <Button size="sm" variant="primary" onClick={(e) => { e.stopPropagation(); openWizard(m.id); }}>
              Start nytt prosjekt
            </Button>
            <Button size="sm" variant="ghost" onClick={(e) => { e.stopPropagation(); openMal(m.id); }}>
              Se detaljer
            </Button>
          </div>
        </Card>
      ))}
    </div>
  );
}

function RBMeta({ l, v }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
      <span style={{ color: SK.soft }}>{l}</span>
      <span style={{ fontWeight: 500 }}>{v}</span>
    </div>
  );
}

// ── Mal-detalj (modal) ───────────────────────────────────────────────────
function RBMalDetalj({ malId, onClose, onStart }) {
  const m = RB_MALER.find(x => x.id === malId);
  if (!m) return null;
  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(17,24,61,.55)', zIndex: 100,
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 30,
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: '#fff', borderRadius: 16, width: '100%', maxWidth: 920, maxHeight: '90vh',
        overflow: 'auto', boxShadow: '0 30px 60px rgba(0,0,0,.25)',
      }}>
        <div style={{ padding: '24px 28px 18px', borderBottom: '1px solid rgba(17,24,61,.08)', display: 'flex', alignItems: 'flex-start', gap: 16 }}>
          <span style={{ width: 50, height: 50, borderRadius: 12, background: `${m.accent}22`, color: m.accent, display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>{VI.briefcase}</span>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 10.5, fontWeight: 700, color: SK.soft, letterSpacing: 0.06, textTransform: 'uppercase' }}>{m.type}</div>
            <h2 style={{ margin: '4px 0 6px', fontSize: 22, fontWeight: 600 }}>{m.navn}</h2>
            <div style={{ fontSize: 13, color: SK.soft }}>{m.beskrivelse}</div>
            <div style={{ marginTop: 8, fontSize: 11.5, color: SK.soft }}>{m.varighet} · {m.bruk}</div>
          </div>
          <button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 24, color: SK.soft, padding: 0, lineHeight: 1 }}>×</button>
        </div>

        <div style={{ padding: 28 }}>
          {/* Mål-rammeverk */}
          <RBSection title="Anbefalt mål-rammeverk">
            <div style={{ padding: 14, background: SK.iceBlueLight, borderRadius: 10 }}>
              <div style={{ fontSize: 10.5, fontWeight: 700, color: SK.soft, letterSpacing: 0.06, textTransform: 'uppercase', marginBottom: 4 }}>Effektmål</div>
              <div style={{ fontSize: 14, fontWeight: 600, marginBottom: 12 }}>{m.malForMal.effektmal}</div>
              <div style={{ fontSize: 10.5, fontWeight: 700, color: SK.soft, letterSpacing: 0.06, textTransform: 'uppercase', marginBottom: 6 }}>Resultatmål</div>
              {m.malForMal.delmal.map((d, i) => (
                <div key={i} style={{ display: 'flex', gap: 8, padding: '4px 0', fontSize: 13 }}>
                  <span style={{ color: SK.coral, fontWeight: 700 }}>R{i+1}</span>
                  <span>{d}</span>
                </div>
              ))}
            </div>
          </RBSection>

          {/* Faser */}
          <RBSection title={`Faser (${m.faser.length})`}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {m.faser.map((f, i) => (
                <div key={i} style={{ padding: '12px 14px', background: '#fff', border: '1px solid rgba(17,24,61,.08)', borderRadius: 8 }}>
                  <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', marginBottom: 6 }}>
                    <div style={{ fontWeight: 600, fontSize: 13.5 }}>
                      <span style={{ color: SK.coral, marginRight: 8 }}>{i+1}.</span>
                      {f.navn}
                    </div>
                    <span style={{ fontSize: 11.5, color: SK.soft }}>{f.dager} dgr</span>
                  </div>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 4 }}>
                    {f.leveranser.map((l, j) => (
                      <span key={j} style={{ fontSize: 11, padding: '3px 8px', background: SK.iceBlueLight, borderRadius: 99, color: SK.ink }}>{l}</span>
                    ))}
                  </div>
                </div>
              ))}
            </div>
          </RBSection>

          {/* Team-roller + KPI */}
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 18 }}>
            <RBSection title="Team-roller">
              <ul style={{ margin: 0, padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 6 }}>
                {m.teamRoller.map((r, i) => (
                  <li key={i} style={{ display: 'flex', gap: 8, alignItems: 'center', fontSize: 13 }}>
                    <span style={{ width: 6, height: 6, borderRadius: '50%', background: m.accent }} />
                    {r}
                  </li>
                ))}
              </ul>
            </RBSection>
            <RBSection title="KPIer som anbefales">
              <ul style={{ margin: 0, padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 8 }}>
                {m.kpiForslag.map((k, i) => (
                  <li key={i} style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12.5 }}>
                    <span>{k.navn}</span>
                    <span style={{ color: SK.soft }}>{k.mal}</span>
                  </li>
                ))}
              </ul>
            </RBSection>
          </div>

          {/* Sjekkliste */}
          <RBSection title="Oppstart-sjekkliste">
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
              {m.sjekkliste.map((s, i) => (
                <div key={i} style={{ display: 'flex', gap: 10, alignItems: 'center', fontSize: 13, padding: '6px 0' }}>
                  <span style={{ width: 18, height: 18, border: `2px solid rgba(17,24,61,.18)`, borderRadius: 4, flexShrink: 0 }} />
                  {s}
                </div>
              ))}
            </div>
          </RBSection>

          {m.referanser ? (
            <div style={{ padding: 12, background: SK.iceBlueLight, borderRadius: 8, fontSize: 12, color: SK.soft }}>
              <b style={{ color: SK.ink }}>Referanser:</b> {m.referanser}
            </div>
          ) : null}
        </div>

        <div style={{ padding: '16px 28px', background: SK.iceBlueLight, borderTop: '1px solid rgba(17,24,61,.08)', display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
          <Button variant="ghost" onClick={onClose}>Lukk</Button>
          <Button variant="primary" icon={I.plus} onClick={onStart}>Start prosjekt fra denne mal</Button>
        </div>
      </div>
    </div>
  );
}

function RBSection({ title, children }) {
  return (
    <div style={{ marginBottom: 22 }}>
      <div style={{ fontSize: 11, fontWeight: 700, color: SK.soft, letterSpacing: 0.08, textTransform: 'uppercase', marginBottom: 10 }}>{title}</div>
      {children}
    </div>
  );
}

// ── Rammeverk view ───────────────────────────────────────────────────────
function RBRammeverkView() {
  return (
    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 14 }}>
      {RB_RAMMEVERK.map(r => (
        <Card key={r.id} padded>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 10 }}>
            <span style={{
              width: 42, height: 42, borderRadius: 10,
              background: `${r.accent}22`, color: r.accent,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: 'monospace', fontWeight: 700, fontSize: 16,
            }}>{r.elementer[0].k}</span>
            <div>
              <div style={{ fontWeight: 600, fontSize: 15 }}>{r.navn}</div>
              <div style={{ fontSize: 11.5, color: SK.soft, marginTop: 2 }}>{r.kort}</div>
            </div>
          </div>
          <div style={{ fontSize: 12.5, color: SK.soft, lineHeight: 1.55, marginBottom: 12 }}>
            {r.desc}
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6, marginBottom: 12 }}>
            {r.elementer.map((e, i) => (
              <div key={i} style={{ display: 'flex', alignItems: 'flex-start', gap: 10, fontSize: 12 }}>
                <span style={{
                  flexShrink: 0, minWidth: 36, padding: '2px 4px',
                  background: r.accent, color: '#fff', borderRadius: 4,
                  fontFamily: 'monospace', fontWeight: 700, fontSize: 11, textAlign: 'center',
                }}>{e.k}</span>
                <div>
                  <b>{e.l}</b> <span style={{ color: SK.soft }}>— {e.d}</span>
                </div>
              </div>
            ))}
          </div>
          <div style={{ padding: 10, background: SK.iceBlueLight, borderRadius: 6, fontSize: 11.5, color: SK.soft }}>
            <b style={{ color: SK.ink }}>Egnet for:</b> {r.egnet}
          </div>
        </Card>
      ))}
    </div>
  );
}

// ── Dokumenter view ──────────────────────────────────────────────────────
function RBDokumenterView() {
  const kat = [...new Set(RB_DOKUMENTER.map(d => d.kategori))];
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      {kat.map(k => (
        <Card key={k} title={k} padded={false}>
          <table className="ok-table">
            <thead>
              <tr>
                <th style={{ paddingLeft: 18 }}>Dokument</th>
                <th>Type</th>
                <th>Omfang</th>
                <th>Brukt</th>
                <th>Sist oppdatert</th>
                <th style={{ paddingRight: 18, textAlign: 'right' }}>Handling</th>
              </tr>
            </thead>
            <tbody>
              {RB_DOKUMENTER.filter(d => d.kategori === k).map(d => (
                <tr key={d.id} style={{ cursor: 'default' }}>
                  <td style={{ paddingLeft: 18, fontWeight: 600, fontSize: 12.5 }}>{d.navn}</td>
                  <td>
                    <span style={{
                      fontSize: 10, padding: '2px 8px', borderRadius: 99, fontWeight: 700,
                      background: d.type === 'DOCX' ? 'rgba(40,88,159,.15)' : d.type === 'XLSX' ? 'rgba(8,96,95,.15)' : 'rgba(242,84,92,.15)',
                      color: d.type === 'DOCX' ? '#28589f' : d.type === 'XLSX' ? '#08605f' : SK.coral,
                    }}>{d.type}</span>
                  </td>
                  <td style={{ fontSize: 12, color: SK.soft }}>{d.sider} {typeof d.sider === 'number' ? (d.sider === 1 ? 'side' : 'sider') : ''}</td>
                  <td style={{ fontSize: 12, color: SK.soft }}>{d.brukt} ggr.</td>
                  <td style={{ fontSize: 12, color: SK.soft }}>{rutFmtDate(d.sist)}</td>
                  <td style={{ paddingRight: 18, textAlign: 'right' }}>
                    <Button size="sm" icon={I.download}>Last ned</Button>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      ))}
    </div>
  );
}

// ── WIZARD: Start nytt prosjekt fra mal ──────────────────────────────────
function RBWizard({ malId, onClose, go }) {
  const [steg, setSteg] = React.useState(0);
  const m = RB_MALER.find(x => x.id === malId);
  const [navn, setNavn] = React.useState('');
  const [avd, setAvd] = React.useState('Lambertseter');
  const [start, setStart] = React.useState('2026-06-01');
  const [eier, setEier] = React.useState('KS');
  if (!m) return null;

  const stegene = [
    { n: 'Grunnlag',   sub: 'Navn, eier, avdeling, oppstart' },
    { n: 'Mål',        sub: 'Effektmål og resultatmål' },
    { n: 'Plan',       sub: 'Faser og milepæler' },
    { n: 'Team',       sub: 'Roller og ansvar' },
    { n: 'Oppsummering', sub: 'Bekreft og opprett' },
  ];

  return (
    <div onClick={onClose} style={{
      position: 'fixed', inset: 0, background: 'rgba(17,24,61,.55)', zIndex: 100,
      display: 'flex', alignItems: 'center', justifyContent: 'center', padding: 30,
    }}>
      <div onClick={(e) => e.stopPropagation()} style={{
        background: '#fff', borderRadius: 16, width: '100%', maxWidth: 920, maxHeight: '90vh',
        overflow: 'hidden', boxShadow: '0 30px 60px rgba(0,0,0,.25)', display: 'flex', flexDirection: 'column',
      }}>
        {/* Header */}
        <div style={{ padding: '20px 28px 14px', borderBottom: '1px solid rgba(17,24,61,.08)' }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', marginBottom: 14 }}>
            <div>
              <div style={{ fontSize: 10.5, fontWeight: 700, color: SK.soft, letterSpacing: 0.06, textTransform: 'uppercase' }}>Start nytt prosjekt</div>
              <h2 style={{ margin: '4px 0 0', fontSize: 20, fontWeight: 600 }}>Basert på «{m.navn}»</h2>
            </div>
            <button onClick={onClose} style={{ background: 'none', border: 'none', cursor: 'pointer', fontSize: 24, color: SK.soft }}>×</button>
          </div>
          {/* Stegmarkør */}
          <div style={{ display: 'flex', gap: 4 }}>
            {stegene.map((s, i) => (
              <div key={i} style={{
                flex: 1, height: 4, borderRadius: 2,
                background: i <= steg ? SK.coral : 'rgba(17,24,61,.1)',
              }} />
            ))}
          </div>
          <div style={{ marginTop: 8, fontSize: 12, color: SK.soft }}>
            Steg {steg + 1} av {stegene.length}: <b style={{ color: SK.ink }}>{stegene[steg].n}</b> — {stegene[steg].sub}
          </div>
        </div>

        {/* Body */}
        <div style={{ padding: 28, flex: 1, overflow: 'auto' }}>
          {steg === 0 ? (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <WizardField label="Prosjektnavn">
                <input className="ok-input" value={navn} onChange={e => setNavn(e.target.value)} placeholder="F.eks. AFT 2026 høstkohort" />
              </WizardField>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 14 }}>
                <WizardField label="Avdeling">
                  <select className="ok-input" value={avd} onChange={e => setAvd(e.target.value)}>
                    {['Lambertseter', 'Holmlia', 'Vulkan', 'Skullerud', 'Alle', 'Stab'].map(a => <option key={a}>{a}</option>)}
                  </select>
                </WizardField>
                <WizardField label="Prosjekteier">
                  <select className="ok-input" value={eier} onChange={e => setEier(e.target.value)}>
                    {Object.entries(TEAM).map(([k, v]) => <option key={k} value={k}>{v.n} · {v.r}</option>)}
                  </select>
                </WizardField>
              </div>
              <WizardField label="Oppstartsdato">
                <input type="date" className="ok-input" value={start} onChange={e => setStart(e.target.value)} />
              </WizardField>
              <div style={{ padding: 12, background: SK.iceBlueLight, borderRadius: 8, fontSize: 12, color: SK.soft }}>
                Mal-varighet: <b style={{ color: SK.ink }}>{m.varighet}</b>. Beregnet sluttdato settes automatisk.
              </div>
            </div>
          ) : null}

          {steg === 1 ? (
            <div>
              <div style={{ fontSize: 11, fontWeight: 700, color: SK.soft, letterSpacing: 0.06, textTransform: 'uppercase', marginBottom: 8 }}>Effektmål (kan endres senere)</div>
              <div style={{ padding: 14, background: SK.iceBlueLight, borderRadius: 8, marginBottom: 20 }}>
                <div style={{ fontSize: 14, fontWeight: 600 }}>{m.malForMal.effektmal}</div>
              </div>
              <div style={{ fontSize: 11, fontWeight: 700, color: SK.soft, letterSpacing: 0.06, textTransform: 'uppercase', marginBottom: 8 }}>Resultatmål · juster ved behov</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {m.malForMal.delmal.map((d, i) => (
                  <div key={i} style={{ display: 'flex', gap: 10, padding: 12, border: '1px solid rgba(17,24,61,.08)', borderRadius: 8 }}>
                    <span style={{ fontSize: 12, color: SK.coral, fontWeight: 700, flexShrink: 0 }}>R{i+1}</span>
                    <input className="ok-input" defaultValue={d} style={{ flex: 1 }} />
                  </div>
                ))}
                <Button size="sm" variant="ghost" icon={I.plus}>Legg til resultatmål</Button>
              </div>
            </div>
          ) : null}

          {steg === 2 ? (
            <div>
              <div style={{ fontSize: 11, fontWeight: 700, color: SK.soft, letterSpacing: 0.06, textTransform: 'uppercase', marginBottom: 8 }}>Faser fra mal · juster ved behov</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {m.faser.map((f, i) => (
                  <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: 12, border: '1px solid rgba(17,24,61,.08)', borderRadius: 8 }}>
                    <input type="checkbox" defaultChecked style={{ accentColor: SK.coral }} />
                    <span style={{ flex: 1, fontWeight: 500, fontSize: 13 }}>{i+1}. {f.navn}</span>
                    <span style={{ fontSize: 11, color: SK.soft }}>{f.dager} dgr · {f.leveranser.length} leveranser</span>
                  </div>
                ))}
              </div>
            </div>
          ) : null}

          {steg === 3 ? (
            <div>
              <div style={{ fontSize: 11, fontWeight: 700, color: SK.soft, letterSpacing: 0.06, textTransform: 'uppercase', marginBottom: 8 }}>Roller fra mal · tilordne personer</div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                {m.teamRoller.map((r, i) => (
                  <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: 12, border: '1px solid rgba(17,24,61,.08)', borderRadius: 8 }}>
                    <span style={{ flex: 1, fontSize: 13 }}>{r}</span>
                    <select className="ok-input" style={{ maxWidth: 240, padding: '6px 10px' }}>
                      <option>— Velg person —</option>
                      {Object.entries(TEAM).map(([k, v]) => <option key={k} value={k}>{v.n}</option>)}
                    </select>
                  </div>
                ))}
              </div>
              <div style={{ marginTop: 14, padding: 12, background: SK.iceBlueLight, borderRadius: 8, fontSize: 12, color: SK.soft }}>
                <b style={{ color: SK.ink }}>Tips:</b> Stedfortredere settes automatisk basert på Rutiner-modulen, og kan justeres i prosjekt­detaljen.
              </div>
            </div>
          ) : null}

          {steg === 4 ? (
            <div>
              <div style={{ fontSize: 13, color: SK.soft, marginBottom: 14 }}>
                Prosjektet vil bli opprettet med følgende oppsett:
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                <SumRow l="Prosjektnavn" v={navn || `${m.navn} · ny`} />
                <SumRow l="Mal" v={m.navn} />
                <SumRow l="Avdeling / eier" v={`${avd} · ${TEAM[eier]?.n}`} />
                <SumRow l="Oppstart" v={rutFmtDate(start)} />
                <SumRow l="Mål-rammeverk" v={m.id.includes('aft') ? 'LFA · 1 effektmål + 3 resultatmål' : 'iht. mal · 3 resultatmål'} />
                <SumRow l="Faser" v={`${m.faser.length} stk`} />
                <SumRow l="Team-roller" v={`${m.teamRoller.length} stk`} />
                <SumRow l="KPIer" v={`${m.kpiForslag.length} forhåndsvalgt`} />
                <SumRow l="Sjekklister" v={`${m.sjekkliste.length} oppstartspunkter`} />
                <SumRow l="Dokumentmaler" v="Mandat, statusrapport, risikoregister, kommunikasjons­plan klare i prosjekt­mappa" />
              </div>
              <div style={{ marginTop: 18, padding: 14, background: SK.lightCoral, borderRadius: 10 }}>
                <div style={{ fontSize: 12.5, color: '#a01a25', fontWeight: 600 }}>
                  Når du oppretter prosjektet:
                </div>
                <ul style={{ margin: '8px 0 0', paddingLeft: 18, fontSize: 12, color: '#a01a25' }}>
                  <li>Møteserie og ukestrutiner opprettes automatisk</li>
                  <li>SharePoint-mappe genereres med malverk lastet inn</li>
                  <li>Prosjektkode reserveres i Visma</li>
                </ul>
              </div>
            </div>
          ) : null}
        </div>

        {/* Footer */}
        <div style={{ padding: '14px 28px', background: SK.iceBlueLight, borderTop: '1px solid rgba(17,24,61,.08)', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Button variant="ghost" onClick={() => steg > 0 ? setSteg(steg - 1) : onClose()}>
            {steg === 0 ? 'Avbryt' : 'Tilbake'}
          </Button>
          {steg < 4 ? (
            <Button variant="primary" onClick={() => setSteg(steg + 1)}>
              Neste · {stegene[steg + 1].n}
            </Button>
          ) : (
            <Button variant="primary" icon={I.check} onClick={() => { onClose(); go({ screen: 'projects' }); }}>
              Opprett prosjekt
            </Button>
          )}
        </div>
      </div>
    </div>
  );
}

function WizardField({ label, children }) {
  return (
    <div>
      <div style={{ fontSize: 11, fontWeight: 700, color: SK.soft, letterSpacing: 0.06, textTransform: 'uppercase', marginBottom: 6 }}>{label}</div>
      {children}
    </div>
  );
}

function SumRow({ l, v }) {
  return (
    <div style={{ display: 'flex', gap: 14, padding: '6px 0', borderBottom: '1px solid rgba(17,24,61,.06)' }}>
      <span style={{ flex: '0 0 180px', fontSize: 11.5, color: SK.soft, fontWeight: 600 }}>{l}</span>
      <span style={{ flex: 1, fontSize: 12.5 }}>{v}</span>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// MÅL & RESULTATER · ny fane på ProjectDetail
// ═══════════════════════════════════════════════════════════════════════════
function ProjectMaalViewMock({ projectId, go }) {
  const data = RB_PROSJEKTMAL[projectId];
  if (!data) {
    return (
      <Card padded>
        <div style={{ padding: '40px 20px', textAlign: 'center' }}>
          <div style={{ fontSize: 38, marginBottom: 14 }}>🎯</div>
          <h3 style={{ margin: '0 0 8px', fontSize: 18, fontWeight: 600 }}>Mål er ikke definert ennå</h3>
          <div style={{ fontSize: 13, color: SK.soft, marginBottom: 18, maxWidth: 460, margin: '0 auto 18px' }}>
            Sett opp et mål-hierarki for dette prosjektet med effektmål, resultatmål og KPIer.
            Du kan starte fra et rammeverk eller en mal i Ressursbanken.
          </div>
          <div style={{ display: 'flex', gap: 8, justifyContent: 'center' }}>
            <Button variant="primary" onClick={() => go({ screen: 'ressursbank' })}>
              Åpne Ressursbanken
            </Button>
            <Button variant="ghost">Sett opp mål manuelt</Button>
          </div>
        </div>
      </Card>
    );
  }

  const mal = data.malFromTemplate ? RB_MALER.find(m => m.id === data.malFromTemplate) : null;

  return (
    <div>
      {/* Header bar med rammeverk */}
      <Card padded style={{ marginBottom: 14, background: 'linear-gradient(to right, rgba(242,84,92,.06), rgba(242,84,92,.01))' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <span style={{ width: 42, height: 42, borderRadius: 10, background: SK.coral, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>🎯</span>
          <div style={{ flex: 1 }}>
            <div style={{ fontSize: 10.5, fontWeight: 700, color: SK.soft, letterSpacing: 0.06, textTransform: 'uppercase' }}>Mål-rammeverk · {data.metode}</div>
            <div style={{ fontWeight: 600, fontSize: 14.5, marginTop: 2 }}>{data.effektmal.tittel}</div>
            <div style={{ fontSize: 12, color: SK.soft, marginTop: 3 }}>
              Effektmål-eier: <b style={{ color: SK.ink }}>{TEAM[data.effektmal.eier]?.n}</b> · måles {data.effektmal.horisont}
            </div>
          </div>
          {mal ? (
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontSize: 10.5, color: SK.soft, fontWeight: 600, letterSpacing: 0.04, textTransform: 'uppercase' }}>Opprettet fra mal</div>
              <div style={{ fontSize: 13, fontWeight: 600, marginTop: 2 }}>{mal.navn}</div>
            </div>
          ) : null}
        </div>
      </Card>

      {/* Mål-hierarki */}
      <Card title="Mål-hierarki · effektmål → resultatmål → KPI" padded={false} style={{ marginBottom: 14 }}>
        <div style={{ padding: '18px 22px' }}>
          {/* Effektmål */}
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 14, marginBottom: 12 }}>
            <span style={{ width: 28, height: 28, borderRadius: 7, background: SK.ink, color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center', fontWeight: 700, fontSize: 11, flexShrink: 0 }}>E</span>
            <div style={{ flex: 1, padding: 12, background: SK.iceBlue, borderRadius: 8 }}>
              <div style={{ fontSize: 10, fontWeight: 700, color: SK.ink, letterSpacing: 0.08, textTransform: 'uppercase' }}>Effektmål</div>
              <div style={{ fontWeight: 600, fontSize: 14, marginTop: 4 }}>{data.effektmal.tittel}</div>
            </div>
          </div>

          {/* Tråd ned */}
          <div style={{ marginLeft: 13, borderLeft: '2px dashed rgba(17,24,61,.2)', paddingLeft: 22, display: 'flex', flexDirection: 'column', gap: 14 }}>
            {data.resultatmal.map((r, i) => {
              const pct = typeof r.aktuell === 'number' && typeof r.mal === 'number'
                ? Math.min(100, Math.round((r.aktuell / r.mal) * 100))
                : null;
              return (
                <div key={r.id} style={{ display: 'flex', alignItems: 'flex-start', gap: 14 }}>
                  <span style={{
                    width: 28, height: 28, borderRadius: 7,
                    background: SK.coral, color: '#fff',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontWeight: 700, fontSize: 11, flexShrink: 0, marginLeft: -36,
                  }}>R{i+1}</span>
                  <div style={{ flex: 1, padding: 12, background: '#fff', border: '1px solid rgba(17,24,61,.08)', borderRadius: 8 }}>
                    <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: 12, marginBottom: 8 }}>
                      <div style={{ flex: 1 }}>
                        <div style={{ fontSize: 10, fontWeight: 700, color: SK.soft, letterSpacing: 0.08, textTransform: 'uppercase' }}>Resultatmål R{i+1}</div>
                        <div style={{ fontWeight: 600, fontSize: 13.5, marginTop: 3 }}>{r.tittel}</div>
                        <div style={{ fontSize: 11.5, color: SK.soft, marginTop: 4 }}>
                          {r.delmal} · eier <b style={{ color: SK.ink }}>{TEAM[r.eier]?.n}</b>
                        </div>
                      </div>
                      <div style={{ textAlign: 'right', minWidth: 100 }}>
                        <div style={{ fontSize: 10, fontWeight: 700, color: SK.soft, letterSpacing: 0.04, textTransform: 'uppercase' }}>Aktuell / mål</div>
                        <div style={{ fontSize: 16, fontWeight: 700, marginTop: 2 }}>
                          {r.aktuell} <span style={{ color: SK.soft, fontSize: 12, fontWeight: 500 }}>/ {r.mal}</span>
                        </div>
                        <div style={{ fontSize: 10.5, color: SK.soft }}>{r.metrikk} {rbTrendIcon(r.trend)}</div>
                      </div>
                    </div>
                    {pct !== null ? (
                      <Progress value={pct} status={pct >= 90 ? 'track' : pct >= 70 ? 'risk' : 'delay'} />
                    ) : null}
                  </div>
                </div>
              );
            })}
          </div>
        </div>
      </Card>

      {/* KPIer + Risikoer */}
      <div style={{ display: 'grid', gridTemplateColumns: '1.4fr 1fr', gap: 14, marginBottom: 14 }}>
        <Card title="KPIer · ukentlig oppdatert" padded={false}>
          <table className="ok-table">
            <thead>
              <tr>
                <th style={{ paddingLeft: 18 }}>Indikator</th>
                <th style={{ textAlign: 'right' }}>Mål</th>
                <th style={{ textAlign: 'right' }}>Aktuell</th>
                <th style={{ textAlign: 'right' }}>Trend</th>
                <th style={{ width: 140 }}>Fremdrift</th>
              </tr>
            </thead>
            <tbody>
              {data.kpier.map((k, i) => {
                const pct = typeof k.aktuell === 'number' && typeof k.mal === 'number' && k.mal > 0
                  ? Math.min(100, Math.round((k.aktuell / k.mal) * 100))
                  : null;
                const status = pct === null ? 'track' : pct >= 90 ? 'track' : pct >= 70 ? 'risk' : 'delay';
                return (
                  <tr key={i} style={{ cursor: 'default' }}>
                    <td style={{ paddingLeft: 18, fontWeight: 600, fontSize: 12.5 }}>{k.navn}</td>
                    <td style={{ textAlign: 'right', fontSize: 12.5, color: SK.soft }}>{k.mal} {k.enhet}</td>
                    <td style={{ textAlign: 'right', fontSize: 13, fontWeight: 700 }}>{k.aktuell} {k.enhet}</td>
                    <td style={{ textAlign: 'right' }}>{rbTrendIcon(k.trend)}</td>
                    <td>{pct !== null ? <Progress value={pct} status={status} /> : <span style={{ color: SK.soft, fontSize: 11 }}>—</span>}</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </Card>

        <Card title={`Risikoregister · ${data.risikoer.length}`} padded={false}>
          {data.risikoer.map((r, i) => {
            const score = r.sann * r.kons;
            const cls = score >= 12 ? 'delay' : score >= 8 ? 'risk' : 'draft';
            return (
              <div key={r.id} style={{ padding: '12px 18px', borderTop: i ? '1px solid rgba(17,24,61,.06)' : 'none' }}>
                <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 8, marginBottom: 4 }}>
                  <span style={{ fontWeight: 600, fontSize: 12.5, flex: 1 }}>{r.tittel}</span>
                  <Pill status={cls}>{r.sann}×{r.kons}={score}</Pill>
                </div>
                <div style={{ fontSize: 11.5, color: SK.soft, marginTop: 4 }}>
                  Eier <b style={{ color: SK.ink }}>{TEAM[r.eier]?.n?.split(' ')[0]}</b> · {r.tiltak}
                </div>
              </div>
            );
          })}
        </Card>
      </div>

      {/* Milepæler */}
      <Card title={`Milepæler · ${data.milepaeler.length}`} padded={false}>
        <div style={{ padding: 18 }}>
          <div style={{ display: 'flex', alignItems: 'stretch', gap: 0, position: 'relative' }}>
            {data.milepaeler.map((mp, i) => {
              const stat = rbStatusMap(mp.status);
              const bg = mp.status === 'done' ? SK.success
                : mp.status === 'risk' ? SK.warn
                : mp.status === 'delay' ? SK.coral
                : SK.iceBlue;
              const ic = mp.status === 'done' ? '#fff' : SK.ink;
              return (
                <React.Fragment key={mp.id}>
                  <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', gap: 8 }}>
                    <div style={{
                      width: 40, height: 40, borderRadius: '50%',
                      background: bg, color: ic,
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      border: mp.status === 'open' ? '2px dashed rgba(17,24,61,.3)' : 'none',
                      position: 'relative', zIndex: 2,
                    }}>
                      {mp.status === 'done' ? <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3"><polyline points="20 6 9 17 4 12"/></svg> : <span style={{ fontWeight: 700, fontSize: 12 }}>{i+1}</span>}
                    </div>
                    <div style={{ textAlign: 'center', padding: '0 6px' }}>
                      <div style={{ fontSize: 10, fontWeight: 700, color: SK.soft, letterSpacing: 0.04, textTransform: 'uppercase' }}>{rutFmtDate(mp.dato)}</div>
                      <div style={{ fontSize: 12, fontWeight: 600, marginTop: 3, lineHeight: 1.3 }}>{mp.tittel}</div>
                      <div style={{ marginTop: 6 }}>
                        <Pill status={stat.cls}>{stat.label}</Pill>
                      </div>
                    </div>
                  </div>
                  {i < data.milepaeler.length - 1 ? (
                    <div style={{
                      flex: '0 0 12px', alignSelf: 'flex-start', marginTop: 18,
                      height: 4, background: 'rgba(17,24,61,.1)',
                    }} />
                  ) : null}
                </React.Fragment>
              );
            })}
          </div>

          {/* Leveranser per milepæl */}
          <div style={{ marginTop: 24, display: 'grid', gridTemplateColumns: `repeat(${data.milepaeler.length}, 1fr)`, gap: 0 }}>
            {data.milepaeler.map((mp, i) => (
              <div key={mp.id} style={{
                padding: '12px',
                borderRight: i < data.milepaeler.length - 1 ? '1px solid rgba(17,24,61,.06)' : 'none',
              }}>
                <div style={{ fontSize: 10, fontWeight: 700, color: SK.soft, letterSpacing: 0.06, textTransform: 'uppercase', marginBottom: 6 }}>Leveranser</div>
                {mp.leveranser.map((l, j) => (
                  <div key={j} style={{ fontSize: 11.5, color: SK.ink, marginBottom: 4, display: 'flex', gap: 6, alignItems: 'flex-start' }}>
                    <span style={{ color: mp.status === 'done' ? SK.success : SK.soft, flexShrink: 0 }}>{mp.status === 'done' ? '✓' : '○'}</span>
                    <span>{l}</span>
                  </div>
                ))}
              </div>
            ))}
          </div>
        </div>
      </Card>
    </div>
  );
}

Object.assign(window, { RessursbankWorkspaceMock, ProjectMaalViewMock });
