// styre-screens.jsx — Styreportalen (kuratert, lukket visning for styret)
// Faner: Oversikt · Møter · Dokumenter · Vedtak · Årshjul · Styret

const styreFmtDato = (iso) => {
  const mnd = ['jan', 'feb', 'mar', 'apr', 'mai', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'des'];
  const d = new Date(iso + 'T00:00');
  return `${d.getDate()}. ${mnd[d.getMonth()]} ${d.getFullYear()}`;
};
const sakstype = (t) => SAKSTYPE_TONE[t] || SAKSTYPE_TONE.orientering;

const SakstypePill = ({ type }) => {
  const t = sakstype(type);
  return <span style={{ fontSize: 10, fontWeight: 700, letterSpacing: 0.03, textTransform: 'uppercase', padding: '2px 8px', borderRadius: 99, background: t.bg, color: t.fg, whiteSpace: 'nowrap' }}>{t.label}</span>;
};

// ── Liten resultat-sparkline ─────────────────────────────────────────────────
function ResultatGraf() {
  const data = STYRE_RESULTAT;
  const W = 280, H = 96, pad = 6;
  const maxV = Math.max(...data.map(d => Math.max(d.faktisk, d.budsjett))) * 1.1;
  const x = i => pad + (i * (W - pad * 2)) / (data.length - 1);
  const y = v => H - pad - (v / maxV) * (H - pad * 2);
  const line = key => data.map((d, i) => `${i === 0 ? 'M' : 'L'} ${x(i).toFixed(1)} ${y(d[key]).toFixed(1)}`).join(' ');
  const area = `${line('faktisk')} L ${x(data.length - 1).toFixed(1)} ${H - pad} L ${x(0).toFixed(1)} ${H - pad} Z`;
  return (
    <svg width="100%" viewBox={`0 0 ${W} ${H}`} preserveAspectRatio="none" style={{ display: 'block' }}>
      <path d={area} fill="rgba(242,84,92,.10)" />
      <path d={line('budsjett')} fill="none" stroke="rgba(17,24,61,.28)" strokeWidth="1.6" strokeDasharray="3 3" />
      <path d={line('faktisk')} fill="none" stroke={SK.coral} strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" />
      {data.map((d, i) => <circle key={i} cx={x(i)} cy={y(d.faktisk)} r="2.6" fill={SK.coral} />)}
    </svg>
  );
}

// ═════════════════════════════════════════════════════════════════
// FANE · OVERSIKT
// ═════════════════════════════════════════════════════════════════
function StyreOversikt({ setTab }) {
  const neste = STYRE_MOTER.find(m => m.status === 'innkalt') || STYRE_MOTER.find(m => m.status === 'planlagt');
  const apneDok = STYRE_DOKUMENTER.filter(d => d.moteId === neste?.id);
  return (
    <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 16, alignItems: 'start' }}>
      {/* Venstre kolonne */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        {/* Neste møte — hero */}
        {neste && (
          <div style={{ background: SK.ink, borderRadius: 14, padding: '22px 24px', color: '#fff', position: 'relative', overflow: 'hidden' }}>
            <Fjelltopper width={220} height={44} color="rgba(187,232,255,.16)" accent="rgba(242,84,92,.7)" style={{ position: 'absolute', right: 0, bottom: 0 }} />
            <div style={{ position: 'relative' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <span style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: 0.1, textTransform: 'uppercase', color: 'rgba(255,255,255,.6)' }}>Neste styremøte</span>
                <span style={{ fontSize: 10, fontWeight: 700, color: '#fff', background: 'rgba(242,84,92,.9)', padding: '2px 9px', borderRadius: 99 }}>INNKALT</span>
              </div>
              <div style={{ fontSize: 23, fontWeight: 600, marginTop: 8, letterSpacing: -0.01 }}>{neste.nr}</div>
              <div style={{ display: 'flex', gap: 18, marginTop: 10, fontSize: 12.5, color: 'rgba(255,255,255,.82)', flexWrap: 'wrap' }}>
                <span>{styreFmtDato(neste.dato)}</span>
                <span>{neste.tid}</span>
                <span>{neste.sted}</span>
              </div>
              <div style={{ fontSize: 11.5, color: 'rgba(255,255,255,.6)', marginTop: 8 }}>{neste.frister}</div>
              <div style={{ display: 'flex', gap: 8, marginTop: 16 }}>
                <button onClick={() => setTab('moter')} style={{ border: 'none', cursor: 'pointer', fontFamily: 'inherit', fontWeight: 600, fontSize: 12.5, padding: '8px 16px', borderRadius: 20, background: '#fff', color: SK.ink }}>Se sakliste ({neste.saker.length})</button>
                <button onClick={() => setTab('dok')} style={{ border: '1px solid rgba(255,255,255,.3)', cursor: 'pointer', fontFamily: 'inherit', fontWeight: 600, fontSize: 12.5, padding: '8px 16px', borderRadius: 20, background: 'transparent', color: '#fff' }}>Sakspapirer ({apneDok.length})</button>
              </div>
            </div>
          </div>
        )}

        {/* Nøkkeltall */}
        <Card title="Nøkkeltall — konsern" action={<span style={{ fontSize: 11, color: SK.soft }}>Per 18.05.2026</span>}>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 16 }}>
            {STYRE_KPI.map(k => (
              <div key={k.k} style={{ paddingTop: 4 }}>
                <div className="ok-kpi__label">{k.label}</div>
                <div style={{ fontSize: 23, fontWeight: 600, letterSpacing: -0.01, marginTop: 4, color: SK.ink }}>{k.value}</div>
                <div style={{ fontSize: 11, marginTop: 3, fontWeight: 600, color: k.positiv ? SK.success : SK.coral }}>
                  {k.positiv ? '▲' : '▼'} {k.delta}
                </div>
                <div style={{ fontSize: 10.5, color: SK.soft, marginTop: 1 }}>{k.sub}</div>
              </div>
            ))}
          </div>
        </Card>

        {/* Resultat-utvikling */}
        <Card title="Resultatutvikling 2026" action={<span style={{ fontSize: 11, color: SK.soft }}>MNOK akkumulert</span>}>
          <ResultatGraf />
          <div style={{ display: 'flex', gap: 18, marginTop: 8, fontSize: 11, color: SK.soft }}>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><span style={{ width: 14, height: 2.5, background: SK.coral, borderRadius: 2 }} />Faktisk</span>
            <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6 }}><span style={{ width: 14, height: 0, borderTop: '2px dashed rgba(17,24,61,.35)' }} />Budsjett</span>
            <span style={{ marginLeft: 'auto', color: SK.success, fontWeight: 600 }}>+0,28 M foran budsjett</span>
          </div>
        </Card>
      </div>

      {/* Høyre kolonne */}
      <div style={{ display: 'flex', flexDirection: 'column', gap: 16 }}>
        <Card title="Strategisk risiko" action={<button onClick={() => setTab('vedtak')} style={ghostLink}>Alle vedtak</button>}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {STYRE_RISIKO.map((r, i) => {
              const t = RISIKO_TONE[r.niva];
              return (
                <div key={i} style={{ display: 'flex', gap: 10, alignItems: 'flex-start' }}>
                  <span style={{ width: 8, height: 8, borderRadius: '50%', background: t.dot, marginTop: 5, flexShrink: 0 }} />
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ fontSize: 12.5, fontWeight: 600, lineHeight: 1.3 }}>{r.navn}</div>
                    <div style={{ fontSize: 11, color: SK.soft, marginTop: 2 }}>{r.tiltak}</div>
                  </div>
                  <span style={{ fontSize: 9.5, fontWeight: 700, textTransform: 'uppercase', padding: '2px 7px', borderRadius: 99, background: t.bg, color: t.fg, flexShrink: 0 }}>{r.niva}</span>
                </div>
              );
            })}
          </div>
        </Card>

        <Card title="Til behandling neste møte">
          <div style={{ display: 'flex', flexDirection: 'column', gap: 2 }}>
            {neste?.saker.filter(s => s.type === 'beslutning').map((s, i) => (
              <div key={i} style={{ display: 'flex', gap: 10, padding: '8px 0', borderTop: i > 0 ? '1px solid rgba(17,24,61,.06)' : 'none', alignItems: 'center' }}>
                <span style={{ fontSize: 11, fontWeight: 700, color: SK.soft, minWidth: 38, fontVariantNumeric: 'tabular-nums' }}>{s.nr}</span>
                <span style={{ flex: 1, fontSize: 12.5, fontWeight: 500 }}>{s.tittel}</span>
                <SakstypePill type={s.type} />
              </div>
            ))}
          </div>
        </Card>

        <div style={{ background: SK.iceBlueLight, borderRadius: 12, padding: '14px 16px', display: 'flex', gap: 10, alignItems: 'flex-start' }}>
          {I.shield}
          <div style={{ fontSize: 11.5, color: SK.soft, lineHeight: 1.5 }}>
            <b style={{ color: SK.ink }}>Fortrolig.</b> Styreportalen viser kuratert informasjon for styrets medlemmer. Dokumenter merket fortrolig deles ikke utenfor styret.
          </div>
        </div>
      </div>
    </div>
  );
}
const ghostLink = { border: 'none', background: 'none', cursor: 'pointer', fontFamily: 'inherit', fontSize: 11.5, fontWeight: 600, color: SK.coral, padding: 0 };

// ═════════════════════════════════════════════════════════════════
// FANE · MØTER
// ═════════════════════════════════════════════════════════════════
function StyreMoter() {
  const [apen, setApen] = React.useState(STYRE_MOTER.find(m => m.status === 'innkalt')?.id);
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      {STYRE_MOTER.map(m => {
        const erApen = apen === m.id;
        const tone = m.status === 'innkalt' ? { bg: '#fcddde', fg: '#a01a25', label: 'Innkalt' }
          : m.status === 'gjennomfort' ? { bg: '#dbeed8', fg: '#2f5a28', label: 'Gjennomført' }
          : { bg: '#e9eef7', fg: '#3c4a6b', label: 'Planlagt' };
        return (
          <Card key={m.id} padded={false}>
            <div onClick={() => setApen(erApen ? null : m.id)} style={{ padding: '16px 20px', cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 14 }}>
              <div style={{ width: 52, textAlign: 'center', flexShrink: 0 }}>
                <div style={{ fontSize: 22, fontWeight: 700, lineHeight: 1, color: SK.ink }}>{new Date(m.dato + 'T00:00').getDate()}</div>
                <div style={{ fontSize: 10.5, fontWeight: 600, textTransform: 'uppercase', color: SK.soft }}>{['jan', 'feb', 'mar', 'apr', 'mai', 'jun', 'jul', 'aug', 'sep', 'okt', 'nov', 'des'][new Date(m.dato + 'T00:00').getMonth()]}</div>
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                  <span style={{ fontSize: 14.5, fontWeight: 600 }}>{m.nr}</span>
                  <span style={{ fontSize: 9.5, fontWeight: 700, textTransform: 'uppercase', padding: '2px 8px', borderRadius: 99, background: tone.bg, color: tone.fg }}>{tone.label}</span>
                </div>
                <div style={{ fontSize: 11.5, color: SK.soft, marginTop: 3 }}>{m.tid} · {m.sted} · {m.saker.length} saker</div>
              </div>
              {m.protokoll && <span style={{ fontSize: 11, color: SK.soft, display: 'inline-flex', alignItems: 'center', gap: 5 }}>{I.doc} Protokoll</span>}
              <span style={{ transform: erApen ? 'rotate(90deg)' : 'none', transition: 'transform .15s', color: SK.soft, display: 'inline-flex' }}>{I.chevron}</span>
            </div>
            {erApen && (
              <div style={{ borderTop: '1px solid rgba(17,24,61,.08)', padding: '14px 20px 18px' }}>
                {m.tilstede && (
                  <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 14, fontSize: 11.5, color: SK.soft, flexWrap: 'wrap' }}>
                    <span style={{ fontWeight: 600, color: SK.ink }}>Til stede:</span>
                    <span className="ok-av-group">{m.tilstede.map(id => <Avatar key={id} initials={id} color={styreFarge(id)} />)}</span>
                    {m.forfall && m.forfall.length > 0 && <span>· Forfall: {m.forfall.map(styreNavn).join(', ')}</span>}
                  </div>
                )}
                <div style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: 0.06, textTransform: 'uppercase', color: SK.soft, marginBottom: 8 }}>Sakliste</div>
                <div style={{ display: 'flex', flexDirection: 'column' }}>
                  {m.saker.map((s, i) => (
                    <div key={i} style={{ display: 'flex', gap: 12, padding: '9px 0', borderTop: i > 0 ? '1px solid rgba(17,24,61,.05)' : 'none', alignItems: 'center' }}>
                      <span style={{ fontSize: 11.5, fontWeight: 700, color: SK.soft, minWidth: 42, fontVariantNumeric: 'tabular-nums' }}>{s.nr}</span>
                      <span style={{ flex: 1, fontSize: 12.5, fontWeight: 500 }}>{s.tittel}</span>
                      <SakstypePill type={s.type} />
                    </div>
                  ))}
                </div>
                <div style={{ fontSize: 11, color: SK.soft, marginTop: 14, fontStyle: 'italic' }}>{m.frister}</div>
              </div>
            )}
          </Card>
        );
      })}
    </div>
  );
}

Object.assign(window, { styreFmtDato, SakstypePill, ResultatGraf, StyreOversikt, StyreMoter, ghostLink });
