// intranett-screens.jsx — Intranett-modul: Forside, Chat, AI-bot, Kunngjøringer

// "Innlogget bruker" = Kari Solberg
const INT_ME = 'KS';
const intFmtDate = (iso) => {
  const d = new Date(iso);
  return d.toLocaleDateString('nb-NO', { day: 'numeric', month: 'short' });
};

// ═══════════════════════════════════════════════════════════════════════════
// INTRANETT WORKSPACE
// ═══════════════════════════════════════════════════════════════════════════
function IntranettWorkspaceMock({ go }) {
  const [tab, setTab] = React.useState('forside');
  const totUnread = INT_DM.reduce((s, d) => s + d.unread, 0) + 3; // 3 ulest i kanaler
  const tabs = [
    { id: 'forside', label: 'Forside' },
    { id: 'chat',    label: 'Meldinger', badge: totUnread },
    { id: 'ai',      label: 'AI-Bot ✨' },
    { id: 'kunngj',  label: `Kunngjøringer (${INT_KUNNGJORINGER.length})` },
  ];

  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">Aktiv</Pill>
            <span style={{ fontSize: 11.5, color: SK.soft, fontWeight: 500 }}>
              {INT_KANALER.length} kanaler · 142 ansatte · 1 AI-assistent
            </span>
          </div>
          <h1 style={{ margin: 0, fontSize: 28, fontWeight: 600, letterSpacing: -0.02 }}>
            Intranett
          </h1>
          <div style={{ marginTop: 6, color: SK.soft, fontSize: 13, maxWidth: 720 }}>
            Hjemmet i hverdagen — kunngjøringer, samtaler på tvers og en AI-assistent som kjenner organisasjonen.
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8, flexShrink: 0 }}>
          <Button size="sm" icon={I.bell}>Varsler</Button>
          <Button variant="primary" icon={I.plus}>Ny kunngjøring</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}
            {t.badge ? (
              <span style={{
                marginLeft: 7, background: tab === t.id ? SK.coral : 'rgba(17,24,61,.1)',
                color: tab === t.id ? '#fff' : SK.soft,
                fontSize: 10, fontWeight: 600, padding: '1px 7px', borderRadius: 99,
              }}>{t.badge}</span>
            ) : null}
          </button>
        ))}
      </div>

      {tab === 'forside' && <IntForsideMock setTab={setTab} />}
      {tab === 'chat'    && <IntChatMock />}
      {tab === 'ai'      && <IntAIMock />}
      {tab === 'kunngj'  && <IntKunngjoringerMock />}
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// FORSIDE
// ═══════════════════════════════════════════════════════════════════════════
function IntForsideMock({ setTab }) {
  const featured = INT_KUNNGJORINGER[2]; // OK:sykkel ny hall

  return (
    <div>
      {/* Hero — featured kunngjøring */}
      <Card padded={false} style={{ marginBottom: 14, overflow: 'hidden' }}>
        <div style={{ background: 'linear-gradient(135deg, #11183d 0%, #28589f 100%)', color: '#fff', padding: '28px 32px' }}>
          <div style={{ display: 'flex', alignItems: 'flex-start', gap: 32 }}>
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 10 }}>
                <span style={{ background: SK.coral, padding: '3px 10px', borderRadius: 99, fontSize: 10.5, fontWeight: 700, letterSpacing: 0.06, textTransform: 'uppercase' }}>Featured</span>
                <span style={{ fontSize: 11.5, opacity: 0.75 }}>Fra {TEAM[featured.fra]?.n} · {intFmtDate(featured.dato)}</span>
              </div>
              <h2 style={{ margin: 0, fontSize: 28, fontWeight: 600, letterSpacing: -0.02, marginBottom: 8 }}>{featured.tittel}</h2>
              <div style={{ fontSize: 14.5, opacity: 0.85, maxWidth: 560, lineHeight: 1.55 }}>{featured.ingress}</div>
              <Button style={{ marginTop: 18 }} variant="accent">Les hele kunngjøringen →</Button>
            </div>
            <div style={{ flexShrink: 0 }}>
              <div style={{ fontSize: 76, lineHeight: 1, opacity: 0.4 }}>🚲</div>
            </div>
          </div>
        </div>
      </Card>

      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 14, marginBottom: 14 }}>
        {/* Min dag */}
        <Card title="Min dag · torsdag 21. mai" padded>
          <ul style={{ margin: 0, padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 8, fontSize: 12.5 }}>
            <li style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
              <span style={{ color: SK.coral }}>●</span> 11:00 — Statusrapport (frist)
            </li>
            <li style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
              <span style={{ color: SK.warn }}>●</span> 14:00 — Ledergruppemøte
            </li>
            <li style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
              <span style={{ color: SK.info }}>●</span> 15:30 — 1:1 med Hanne
            </li>
            <li style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
              <span style={{ color: SK.soft }}>●</span> 16:30 — Anbud-status (Marius)
            </li>
          </ul>
        </Card>

        {/* Aktive samtaler */}
        <Card title="Uleste meldinger" padded
          action={<Button size="sm" variant="ghost" onClick={() => setTab('chat')}>Åpne <span style={{ marginLeft: 4 }}>{I.chevron}</span></Button>}>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {INT_DM.filter(d => d.unread > 0).map(d => (
              <div key={d.id} style={{ display: 'flex', alignItems: 'center', gap: 8, padding: '6px 0' }} onClick={() => setTab('chat')}>
                <Avatar initials={TEAM[d.med]?.i} color={TEAM[d.med]?.c} size={24} />
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12.5, fontWeight: 600 }}>{TEAM[d.med]?.n}</div>
                  <div style={{ fontSize: 11, color: SK.soft, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{d.sist}</div>
                </div>
                <span style={{ background: SK.coral, color: '#fff', padding: '1px 7px', borderRadius: 99, fontSize: 10, fontWeight: 700 }}>{d.unread}</span>
              </div>
            ))}
            <div style={{ paddingTop: 8, marginTop: 4, borderTop: '1px solid rgba(17,24,61,.06)', fontSize: 11, color: SK.soft }}>
              + 3 uleste i #generelt og #ledelse
            </div>
          </div>
        </Card>

        {/* AI-bot snippet */}
        <Card title={<span><span style={{ fontSize: 16 }}>✨</span> Spør AI-assistenten</span>}
          padded
          action={<Button size="sm" variant="ghost" onClick={() => setTab('ai')}>Åpne <span style={{ marginLeft: 4 }}>{I.chevron}</span></Button>}
        >
          <div style={{ fontSize: 12.5, color: SK.soft, marginBottom: 10, lineHeight: 1.5 }}>
            Bot'en kjenner organisasjon, prosjekter og rutiner. Du kan spørre på norsk.
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
            {INT_AI_FORSLAG.slice(0, 3).map((s, i) => (
              <button key={i} onClick={() => setTab('ai')} className="ok-btn ok-btn--sm" style={{
                justifyContent: 'flex-start', width: '100%', fontSize: 12,
                background: SK.iceBlueLight, borderColor: 'rgba(17,24,61,.08)', color: SK.ink,
              }}>“{s}”</button>
            ))}
          </div>
        </Card>
      </div>

      {/* Hurtiglenker */}
      <Card title="Systemer og verktøy" padded={false} style={{ marginBottom: 14 }}>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)' }}>
          {INT_HURTIGLENKER.map((l, i) => (
            <div key={i} style={{
              padding: '20px 14px', textAlign: 'center',
              borderRight: (i+1) % 6 !== 0 ? '1px solid rgba(17,24,61,.06)' : 'none',
              cursor: 'pointer',
            }}>
              <div style={{ width: 44, height: 44, borderRadius: 10, background: `${l.farge}22`, color: l.farge, margin: '0 auto 10px', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                {VI.link}
              </div>
              <div style={{ fontSize: 13, fontWeight: 600 }}>{l.tittel}</div>
              <div style={{ fontSize: 11, color: SK.soft, marginTop: 2 }}>{l.beskrivelse}</div>
            </div>
          ))}
        </div>
      </Card>

      {/* Nyeste kunngjøringer */}
      <Card title="Siste kunngjøringer" padded={false}
        action={<Button size="sm" variant="ghost" onClick={() => setTab('kunngj')}>Alle <span style={{ marginLeft: 4 }}>{I.chevron}</span></Button>}>
        {INT_KUNNGJORINGER.slice(0, 3).map((k, i) => (
          <div key={k.id} style={{ padding: '14px 18px', borderTop: i ? '1px solid rgba(17,24,61,.06)' : 'none', display: 'flex', gap: 14, alignItems: 'flex-start' }}>
            <Avatar initials={TEAM[k.fra]?.i} color={TEAM[k.fra]?.c} size={32} />
            <div style={{ flex: 1 }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
                <span style={{ fontWeight: 600, fontSize: 13.5 }}>{k.tittel}</span>
                {k.viktighet === 'høy' ? <Pill status="delay">Viktig</Pill> : null}
              </div>
              <div style={{ fontSize: 12, color: SK.soft, marginTop: 3 }}>{k.ingress}</div>
              <div style={{ display: 'flex', gap: 10, marginTop: 6, fontSize: 10.5, color: SK.soft }}>
                <span>{TEAM[k.fra]?.n}</span><span>·</span><span>{intFmtDate(k.dato)}</span><span>·</span><span>{k.visninger} har sett</span>
              </div>
            </div>
          </div>
        ))}
      </Card>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// CHAT — Slack-style med kanaler + DM
// ═══════════════════════════════════════════════════════════════════════════
function IntChatMock() {
  const [active, setActive] = React.useState({ type: 'kanal', id: 'generelt' });
  const [allMsgs, setAllMsgs] = React.useState({ ...INT_MELDINGER, ...INT_DM_HISTORIKK });
  const [input, setInput] = React.useState('');
  const listRef = React.useRef(null);

  const kanal = active.type === 'kanal' ? INT_KANALER.find(k => k.id === active.id) : null;
  const dm = active.type === 'dm' ? INT_DM.find(d => d.id === active.id) : null;
  const msgs = allMsgs[active.id] || [];

  React.useEffect(() => {
    if (listRef.current) listRef.current.scrollTop = listRef.current.scrollHeight;
  }, [msgs.length, active.id]);

  const send = () => {
    if (!input.trim()) return;
    const now = new Date();
    const time = `${now.getHours().toString().padStart(2,'0')}:${now.getMinutes().toString().padStart(2,'0')}`;
    const newMsg = { id: 'new-' + Date.now(), who: INT_ME, time, date: '21.05', text: input.trim() };
    setAllMsgs(prev => ({ ...prev, [active.id]: [...(prev[active.id] || []), newMsg] }));
    setInput('');
  };

  return (
    <Card padded={false} style={{ height: 720, overflow: 'hidden' }}>
      <div style={{ display: 'grid', gridTemplateColumns: '260px 1fr', height: '100%' }}>
        {/* Venstre side · kanaler + DM */}
        <div style={{ background: '#fcfcfe', borderRight: '1px solid rgba(17,24,61,.08)', display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
          <div style={{ padding: '14px 14px 8px' }}>
            <input className="ok-input" placeholder="Søk kanaler/personer…" style={{ width: '100%', padding: '6px 10px', fontSize: 12 }} />
          </div>

          <div style={{ flex: 1, overflowY: 'auto', padding: '6px 8px' }}>
            <div style={{ padding: '8px 8px 6px', fontSize: 10, fontWeight: 700, color: SK.soft, letterSpacing: 0.08, textTransform: 'uppercase' }}>Kanaler</div>
            {INT_KANALER.map(k => {
              const isActive = active.type === 'kanal' && active.id === k.id;
              return (
                <button key={k.id} onClick={() => setActive({ type: 'kanal', id: k.id })} style={{
                  display: 'flex', alignItems: 'center', gap: 8, padding: '6px 10px',
                  width: '100%', border: 'none', cursor: 'pointer', borderRadius: 6,
                  background: isActive ? SK.ink : 'transparent', color: isActive ? '#fff' : SK.ink,
                  textAlign: 'left', fontFamily: 'Poppins', fontSize: 12.5,
                }}>
                  <span style={{ opacity: isActive ? 1 : 0.7 }}>{k.privat ? '🔒' : '#'}</span>
                  <span style={{ flex: 1 }}>{k.navn}</span>
                  {(k.id === 'generelt' || k.id === 'ledelse' || k.id === 'anbud-2027') ? (
                    <span style={{ background: isActive ? SK.coral : 'rgba(17,24,61,.1)', color: isActive ? '#fff' : SK.soft, fontSize: 10, fontWeight: 600, padding: '0 6px', borderRadius: 99 }}>
                      {k.id === 'generelt' ? 2 : k.id === 'ledelse' ? 1 : 4}
                    </span>
                  ) : null}
                </button>
              );
            })}

            <div style={{ padding: '14px 8px 6px', fontSize: 10, fontWeight: 700, color: SK.soft, letterSpacing: 0.08, textTransform: 'uppercase' }}>Direkte meldinger</div>
            {INT_DM.map(d => {
              const isActive = active.type === 'dm' && active.id === d.id;
              const a = TEAM[d.med];
              return (
                <button key={d.id} onClick={() => setActive({ type: 'dm', id: d.id })} style={{
                  display: 'flex', alignItems: 'center', gap: 8, padding: '6px 10px',
                  width: '100%', border: 'none', cursor: 'pointer', borderRadius: 6,
                  background: isActive ? SK.ink : 'transparent', color: isActive ? '#fff' : SK.ink,
                  textAlign: 'left', fontFamily: 'Poppins', fontSize: 12.5,
                }}>
                  <span style={{ position: 'relative' }}>
                    <Avatar initials={a?.i} color={a?.c} size={20} />
                    <span style={{ position: 'absolute', bottom: -1, right: -1, width: 8, height: 8, borderRadius: '50%', background: SK.success, border: `1.5px solid ${isActive ? SK.ink : '#fcfcfe'}` }} />
                  </span>
                  <span style={{ flex: 1 }}>{a?.n}</span>
                  {d.unread > 0 ? (
                    <span style={{ background: isActive ? SK.coral : SK.coral, color: '#fff', fontSize: 10, fontWeight: 600, padding: '0 6px', borderRadius: 99 }}>{d.unread}</span>
                  ) : null}
                </button>
              );
            })}
          </div>
        </div>

        {/* Høyre side · meldinger */}
        <div style={{ display: 'flex', flexDirection: 'column', overflow: 'hidden', background: '#fff' }}>
          {/* Header */}
          <div style={{ padding: '14px 18px', borderBottom: '1px solid rgba(17,24,61,.08)', display: 'flex', alignItems: 'center', gap: 10 }}>
            {kanal ? (
              <>
                <span style={{ fontSize: 18 }}>{kanal.emoji}</span>
                <div style={{ flex: 1 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span style={{ fontWeight: 600, fontSize: 14 }}>{kanal.privat ? '🔒 ' : '# '}{kanal.navn}</span>
                    <span style={{ fontSize: 11.5, color: SK.soft }}>· {kanal.medlemmer} medlemmer</span>
                  </div>
                  <div style={{ fontSize: 11.5, color: SK.soft, marginTop: 2 }}>{kanal.beskrivelse}</div>
                </div>
              </>
            ) : dm ? (
              <>
                <Avatar initials={TEAM[dm.med]?.i} color={TEAM[dm.med]?.c} size={32} />
                <div style={{ flex: 1 }}>
                  <div style={{ fontWeight: 600, fontSize: 14 }}>{TEAM[dm.med]?.n}</div>
                  <div style={{ fontSize: 11.5, color: SK.soft, marginTop: 2 }}>{TEAM[dm.med]?.r} · 🟢 aktiv</div>
                </div>
              </>
            ) : null}
            <Button size="sm" variant="ghost" icon={I.bell}>Varsler</Button>
          </div>

          {/* Meldinger */}
          <div ref={listRef} style={{ flex: 1, overflowY: 'auto', padding: '14px 18px', display: 'flex', flexDirection: 'column', gap: 14 }}>
            {msgs.length === 0 ? (
              <div style={{ textAlign: 'center', color: SK.soft, padding: 40, fontSize: 13 }}>
                Ingen meldinger ennå. Vær først ut!
              </div>
            ) : msgs.map((m, i) => {
              const a = TEAM[m.who];
              const prev = msgs[i - 1];
              const compact = prev && prev.who === m.who && prev.date === m.date;
              const newDay = !prev || prev.date !== m.date;
              return (
                <React.Fragment key={m.id}>
                  {newDay ? (
                    <div style={{ display: 'flex', alignItems: 'center', gap: 10, margin: '8px 0 4px' }}>
                      <div style={{ flex: 1, height: 1, background: 'rgba(17,24,61,.08)' }} />
                      <span style={{ fontSize: 10.5, fontWeight: 600, color: SK.soft, padding: '3px 10px', background: SK.iceBlueLight, borderRadius: 99 }}>{m.date === '21.05' ? 'I dag · 21. mai' : m.date === '20.05' ? 'I går · 20. mai' : m.date}</span>
                      <div style={{ flex: 1, height: 1, background: 'rgba(17,24,61,.08)' }} />
                    </div>
                  ) : null}
                  <div style={{ display: 'flex', gap: 10, marginTop: compact ? -8 : 0 }}>
                    {compact ? (
                      <div style={{ width: 32, flexShrink: 0, fontSize: 9, color: 'rgba(17,24,61,.3)', textAlign: 'right', paddingRight: 4, paddingTop: 4 }}>{m.time}</div>
                    ) : (
                      <Avatar initials={a?.i} color={a?.c} size={32} />
                    )}
                    <div style={{ flex: 1, minWidth: 0 }}>
                      {!compact ? (
                        <div style={{ display: 'flex', alignItems: 'baseline', gap: 8, marginBottom: 2 }}>
                          <span style={{ fontWeight: 600, fontSize: 13 }}>{a?.n || m.who}</span>
                          <span style={{ fontSize: 10.5, color: SK.soft }}>{m.time}</span>
                        </div>
                      ) : null}
                      <div style={{ fontSize: 13, lineHeight: 1.5, whiteSpace: 'pre-wrap' }}>
                        {renderText(m.text)}
                      </div>
                      {m.reactions ? (
                        <div style={{ display: 'flex', gap: 4, marginTop: 6, flexWrap: 'wrap' }}>
                          {m.reactions.map((r, j) => (
                            <span key={j} style={{ padding: '2px 8px', background: SK.iceBlueLight, borderRadius: 99, fontSize: 11, border: '1px solid rgba(17,24,61,.06)', display: 'inline-flex', gap: 4, alignItems: 'center', cursor: 'pointer' }}>
                              <span>{r.e}</span>
                              <span style={{ color: SK.soft, fontWeight: 600 }}>{r.n}</span>
                            </span>
                          ))}
                          <span style={{ padding: '2px 8px', background: 'transparent', borderRadius: 99, fontSize: 11, border: '1px dashed rgba(17,24,61,.15)', color: SK.soft, cursor: 'pointer' }}>+</span>
                        </div>
                      ) : null}
                    </div>
                  </div>
                </React.Fragment>
              );
            })}
          </div>

          {/* Composer */}
          <div style={{ borderTop: '1px solid rgba(17,24,61,.08)', padding: 14 }}>
            <div style={{ border: '1px solid rgba(17,24,61,.18)', borderRadius: 10, padding: 8, background: '#fff' }}>
              <textarea
                value={input}
                onChange={e => setInput(e.target.value)}
                onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); } }}
                placeholder={kanal ? `Melding til #${kanal.navn}` : `Melding til ${TEAM[dm?.med]?.n}`}
                style={{
                  width: '100%', border: 'none', resize: 'none', outline: 'none',
                  fontFamily: 'Poppins', fontSize: 13, minHeight: 40, padding: 4,
                }}
                rows={1}
              />
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, paddingTop: 4 }}>
                <button style={composerBtn}>𝐁</button>
                <button style={composerBtn}>𝐼</button>
                <button style={composerBtn}>{'</>'}</button>
                <button style={composerBtn}>📎</button>
                <button style={composerBtn}>😊</button>
                <button style={composerBtn}>@</button>
                <div style={{ flex: 1 }} />
                <Button size="sm" variant="primary" onClick={send} disabled={!input.trim()}>
                  Send →
                </Button>
              </div>
            </div>
            <div style={{ marginTop: 6, fontSize: 10.5, color: SK.soft }}>
              <b>Enter</b> for å sende · <b>Shift+Enter</b> for ny linje · @nevn noen for å varsle
            </div>
          </div>
        </div>
      </div>
    </Card>
  );
}

const composerBtn = {
  background: 'transparent', border: 'none', cursor: 'pointer',
  width: 26, height: 26, borderRadius: 5, color: SK.soft, fontSize: 13,
  display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
};

// Helper · highlight @mentions
function renderText(text) {
  const parts = text.split(/(@[A-ZÆØÅ]{2,3}|@\w+)/g);
  return parts.map((p, i) => {
    if (p.startsWith('@')) {
      return <span key={i} style={{ background: 'rgba(40,88,159,.12)', color: '#28589f', padding: '0 4px', borderRadius: 4, fontWeight: 600 }}>{p}</span>;
    }
    return <React.Fragment key={i}>{p}</React.Fragment>;
  });
}

// Enkel markdown-renderer for AI-svar: **fet**, *kursiv*, `code`, bullets, ## overskrifter, lenker
function renderMarkdown(text) {
  if (!text) return null;
  const lines = text.split('\n');
  const out = [];
  let listBuf = [];
  const flushList = () => {
    if (listBuf.length) {
      out.push(<ul key={'ul-' + out.length} style={{ margin: '6px 0 6px 18px', paddingLeft: 4 }}>
        {listBuf.map((l, i) => <li key={i} style={{ marginBottom: 3 }}>{renderInline(l)}</li>)}
      </ul>);
      listBuf = [];
    }
  };
  lines.forEach((raw, idx) => {
    const line = raw.trimEnd();
    if (/^\s*[-•*]\s+/.test(line)) {
      listBuf.push(line.replace(/^\s*[-•*]\s+/, ''));
    } else if (/^\s*\d+\.\s+/.test(line)) {
      listBuf.push(line.replace(/^\s*\d+\.\s+/, ''));
    } else {
      flushList();
      if (line.startsWith('### ')) out.push(<div key={idx} style={{ fontWeight: 700, fontSize: 13.5, marginTop: 8, marginBottom: 3 }}>{renderInline(line.slice(4))}</div>);
      else if (line.startsWith('## ')) out.push(<div key={idx} style={{ fontWeight: 700, fontSize: 14.5, marginTop: 10, marginBottom: 4 }}>{renderInline(line.slice(3))}</div>);
      else if (line === '') out.push(<div key={idx} style={{ height: 6 }} />);
      else out.push(<div key={idx}>{renderInline(line)}</div>);
    }
  });
  flushList();
  return out;
}
function renderInline(text) {
  // Order matters: bold ** first, then italic *, then code `…`
  const tokens = [];
  let i = 0; let key = 0;
  const push = (n) => tokens.push(React.cloneElement(n, { key: key++ }));
  while (i < text.length) {
    if (text.slice(i, i+2) === '**') {
      const end = text.indexOf('**', i+2);
      if (end > -1) { push(<b>{text.slice(i+2, end)}</b>); i = end + 2; continue; }
    }
    if (text[i] === '`') {
      const end = text.indexOf('`', i+1);
      if (end > -1) { push(<code style={{ background: 'rgba(17,24,61,.06)', padding: '1px 5px', borderRadius: 4, fontSize: '0.92em' }}>{text.slice(i+1, end)}</code>); i = end + 1; continue; }
    }
    if (text[i] === '*' && text[i+1] !== '*') {
      const end = text.indexOf('*', i+1);
      if (end > -1) { push(<i>{text.slice(i+1, end)}</i>); i = end + 1; continue; }
    }
    // Mention
    const mMatch = text.slice(i).match(/^@[A-ZÆØÅ]{2,3}\b/);
    if (mMatch) { push(<span style={{ background: 'rgba(40,88,159,.12)', color: '#28589f', padding: '0 4px', borderRadius: 4, fontWeight: 600 }}>{mMatch[0]}</span>); i += mMatch[0].length; continue; }
    // Find next special
    const next = text.slice(i).search(/(\*\*|`|\*|@[A-ZÆØÅ]{2,3})/);
    if (next === -1) { push(<React.Fragment>{text.slice(i)}</React.Fragment>); break; }
    push(<React.Fragment>{text.slice(i, i + next)}</React.Fragment>);
    i += next;
  }
  return <>{tokens}</>;
}

// ═══════════════════════════════════════════════════════════════════════════
// AI-BOT
// ═══════════════════════════════════════════════════════════════════════════
function IntAIMock() {
  const [messages, setMessages] = React.useState([
    {
      who: 'ai', text: 'Hei Kari! 👋 Jeg er Superkollega — OsloKollegas AI-assistent. Jeg kjenner organisasjonen, prosjekter, rutiner og kan hjelpe deg å skrive utkast. Hva trenger du hjelp med i dag?',
      time: 'nå',
    },
  ]);
  const [input, setInput] = React.useState('');
  const [thinking, setThinking] = React.useState(false);
  const listRef = React.useRef(null);

  React.useEffect(() => {
    if (listRef.current) listRef.current.scrollTop = listRef.current.scrollHeight;
  }, [messages.length, thinking]);

  const ask = async (prompt) => {
    const userMsg = { who: 'me', text: prompt, time: 'nå' };
    setMessages(prev => [...prev, userMsg]);
    setInput('');
    setThinking(true);
    try {
      // Bygg samtalehistorikk fra messages + ny prompt
      const conv = [
        { role: 'user', content: `${INT_AI_KONTEKST}\n\n---\n\nFørste spørsmål: ${prompt}` },
      ];
      // Hvis samtale fra før, prepend tidligere meldinger som context
      const earlier = messages.slice(1); // hopp over velkomst
      if (earlier.length > 0) {
        const earlierTekst = earlier.map(m => (m.who === 'me' ? `Bruker: ${m.text}` : `Superkollega: ${m.text}`)).join('\n');
        conv[0].content = `${INT_AI_KONTEKST}\n\nTidligere i denne samtalen:\n${earlierTekst}\n\n---\n\nNytt spørsmål fra bruker: ${prompt}`;
      }
      const response = await window.claude.complete({ messages: conv });
      const txt = typeof response === 'string' ? response : (response.text || JSON.stringify(response));
      setMessages(prev => [...prev, { who: 'ai', text: txt, time: 'nå' }]);
    } catch (err) {
      setMessages(prev => [...prev, { who: 'ai', text: '⚠️ Beklager, AI-tjenesten svarte ikke. Prøv igjen om et øyeblikk.', time: 'nå' }]);
    } finally {
      setThinking(false);
    }
  };

  const handleSend = () => {
    if (!input.trim() || thinking) return;
    ask(input.trim());
  };

  return (
    <Card padded={false} style={{ height: 720, overflow: 'hidden', display: 'flex', flexDirection: 'column' }}>
      {/* Header */}
      <div style={{ padding: '14px 22px', borderBottom: '1px solid rgba(17,24,61,.08)', display: 'flex', alignItems: 'center', gap: 14, background: 'linear-gradient(to right, rgba(242,84,92,.05), rgba(40,88,159,.05))' }}>
        <div style={{
          width: 44, height: 44, borderRadius: 12,
          background: 'linear-gradient(135deg, #f2545c 0%, #586ba4 100%)',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: '#fff', fontSize: 22,
        }}>✨</div>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 16, fontWeight: 600 }}>Superkollega — AI-assistent</div>
          <div style={{ fontSize: 11.5, color: SK.soft, marginTop: 2 }}>
            Kjenner OsloKollegas struktur, prosjekter, rutiner og malverk · ingen sensitive personopplysninger
          </div>
        </div>
        <Button size="sm" variant="ghost" onClick={() => setMessages(messages.slice(0, 1))}>Ny samtale</Button>
      </div>

      {/* Meldingsliste */}
      <div ref={listRef} style={{ flex: 1, overflowY: 'auto', padding: '20px 22px', display: 'flex', flexDirection: 'column', gap: 14, background: '#fcfcfe' }}>
        {messages.map((m, i) => (
          <div key={i} style={{
            display: 'flex', gap: 10,
            flexDirection: m.who === 'me' ? 'row-reverse' : 'row',
            maxWidth: '100%',
          }}>
            <div style={{
              width: 32, height: 32, borderRadius: '50%', flexShrink: 0,
              background: m.who === 'me' ? SK.coral : 'linear-gradient(135deg, #f2545c 0%, #586ba4 100%)',
              color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontWeight: 700, fontSize: 12,
            }}>{m.who === 'me' ? 'KS' : '✨'}</div>
            <div style={{
              maxWidth: '78%',
              background: m.who === 'me' ? SK.ink : '#fff',
              color: m.who === 'me' ? '#fff' : SK.ink,
              padding: '12px 14px', borderRadius: 12,
              border: m.who === 'me' ? 'none' : '1px solid rgba(17,24,61,.08)',
              fontSize: 13.5, lineHeight: 1.55,
            }}>
              {m.who === 'ai' ? renderMarkdown(m.text) : <div style={{ whiteSpace: 'pre-wrap' }}>{m.text}</div>}
              <div style={{ fontSize: 10, color: m.who === 'me' ? 'rgba(255,255,255,.5)' : SK.soft, marginTop: 6 }}>
                {m.time} {m.who === 'ai' ? '· Superkollega' : ''}
              </div>
            </div>
          </div>
        ))}
        {thinking ? (
          <div style={{ display: 'flex', gap: 10 }}>
            <div style={{
              width: 32, height: 32, borderRadius: '50%', flexShrink: 0,
              background: 'linear-gradient(135deg, #f2545c 0%, #586ba4 100%)',
              color: '#fff', display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontSize: 14,
            }}>✨</div>
            <div style={{
              background: '#fff', padding: '14px 16px', borderRadius: 12,
              border: '1px solid rgba(17,24,61,.08)', display: 'flex', gap: 4,
            }}>
              <Dot delay={0} />
              <Dot delay={150} />
              <Dot delay={300} />
            </div>
          </div>
        ) : null}
      </div>

      {/* Foreslåtte spørsmål (vises bare når kort samtale) */}
      {messages.length === 1 && !thinking ? (
        <div style={{ padding: '0 22px 14px', borderTop: '1px solid rgba(17,24,61,.06)' }}>
          <div style={{ fontSize: 10.5, fontWeight: 700, color: SK.soft, letterSpacing: 0.06, textTransform: 'uppercase', margin: '14px 0 8px' }}>Forsøk gjerne</div>
          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
            {INT_AI_FORSLAG.map((s, i) => (
              <button key={i} onClick={() => ask(s)} style={{
                padding: '10px 12px', textAlign: 'left', background: '#fff',
                border: '1px solid rgba(17,24,61,.12)', borderRadius: 10, cursor: 'pointer',
                fontSize: 12, color: SK.ink, fontFamily: 'Poppins', lineHeight: 1.4,
              }}>{s}</button>
            ))}
          </div>
        </div>
      ) : null}

      {/* Composer */}
      <div style={{ borderTop: '1px solid rgba(17,24,61,.08)', padding: 14, background: '#fff' }}>
        <div style={{ border: '1.5px solid rgba(17,24,61,.18)', borderRadius: 12, padding: 8 }}>
          <textarea
            value={input}
            onChange={e => setInput(e.target.value)}
            onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); handleSend(); } }}
            placeholder="Spør Superkollega om noe — for eksempel «Hva er status på AFT 2026?»"
            disabled={thinking}
            style={{
              width: '100%', border: 'none', resize: 'none', outline: 'none',
              fontFamily: 'Poppins', fontSize: 13.5, minHeight: 42, padding: 4,
              background: 'transparent', opacity: thinking ? 0.5 : 1,
            }}
            rows={2}
          />
          <div style={{ display: 'flex', alignItems: 'center', gap: 6, paddingTop: 4 }}>
            <span style={{ fontSize: 10.5, color: SK.soft }}>✨ Claude Haiku · 1 024 ord-grense</span>
            <div style={{ flex: 1 }} />
            <Button size="sm" variant="primary" onClick={handleSend} disabled={!input.trim() || thinking}>
              {thinking ? 'Tenker…' : 'Spør ✨'}
            </Button>
          </div>
        </div>
        <div style={{ marginTop: 8, fontSize: 10.5, color: SK.soft }}>
          Superkollega er en assistent — ikke en erstatning for fagvurdering. Sjekk fakta og dokumenter med kilde før handling.
        </div>
      </div>
    </Card>
  );
}

function Dot({ delay }) {
  return (
    <span style={{
      width: 7, height: 7, borderRadius: '50%', background: SK.soft,
      animation: 'intDot 1s infinite', animationDelay: `${delay}ms`,
    }} />
  );
}
// Inject keyframes once
if (typeof document !== 'undefined' && !document.getElementById('int-anim')) {
  const s = document.createElement('style');
  s.id = 'int-anim';
  s.textContent = `@keyframes intDot { 0%,80%,100% { opacity: 0.3; transform: scale(0.8);} 40% { opacity: 1; transform: scale(1.2);} }`;
  document.head.appendChild(s);
}

// ═══════════════════════════════════════════════════════════════════════════
// KUNNGJØRINGER
// ═══════════════════════════════════════════════════════════════════════════
function IntKunngjoringerMock() {
  const [valgt, setValgt] = React.useState(null);
  const v = valgt ? INT_KUNNGJORINGER.find(k => k.id === valgt) : null;

  return (
    <div style={{ display: 'grid', gridTemplateColumns: '380px 1fr', gap: 14 }}>
      <Card padded={false} style={{ overflow: 'hidden' }}>
        {INT_KUNNGJORINGER.map((k, i) => (
          <div key={k.id}
            onClick={() => setValgt(k.id)}
            style={{
              padding: '14px 18px',
              borderTop: i ? '1px solid rgba(17,24,61,.06)' : 'none',
              cursor: 'pointer',
              background: valgt === k.id ? SK.iceBlueLight : 'transparent',
            }}
          >
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
              {k.viktighet === 'høy' ? <Pill status="delay">Viktig</Pill> : null}
              <span style={{ fontSize: 11, color: SK.soft }}>{intFmtDate(k.dato)}</span>
            </div>
            <div style={{ fontWeight: 600, fontSize: 13.5, marginBottom: 4 }}>{k.tittel}</div>
            <div style={{ fontSize: 11.5, color: SK.soft, marginBottom: 6 }}>{k.ingress}</div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, color: SK.soft }}>
              <Avatar initials={TEAM[k.fra]?.i} color={TEAM[k.fra]?.c} size={18} />
              <span>{TEAM[k.fra]?.n} · {k.visninger} sett</span>
            </div>
          </div>
        ))}
      </Card>

      <Card padded={false}>
        {!v ? (
          <div style={{ padding: 60, textAlign: 'center', color: SK.soft }}>Velg en kunngjøring fra venstre.</div>
        ) : (
          <div style={{ padding: '28px 32px' }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 12 }}>
              {v.viktighet === 'høy' ? <Pill status="delay">Viktig</Pill> : null}
              {v.tags.map(t => <Pill key={t} status="draft">{t}</Pill>)}
            </div>
            <h1 style={{ margin: 0, fontSize: 26, fontWeight: 600, letterSpacing: -0.02 }}>{v.tittel}</h1>
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginTop: 14, paddingBottom: 18, borderBottom: '1px solid rgba(17,24,61,.06)' }}>
              <Avatar initials={TEAM[v.fra]?.i} color={TEAM[v.fra]?.c} size={40} />
              <div>
                <div style={{ fontWeight: 600, fontSize: 13 }}>{TEAM[v.fra]?.n}</div>
                <div style={{ fontSize: 11.5, color: SK.soft, marginTop: 2 }}>{TEAM[v.fra]?.r} · {intFmtDate(v.dato)} · {v.visninger} har sett</div>
              </div>
            </div>
            <div style={{ marginTop: 18, fontSize: 14.5, fontWeight: 500, color: SK.ink, lineHeight: 1.5 }}>
              {v.ingress}
            </div>
            <div style={{ marginTop: 14, fontSize: 13.5, color: SK.ink, lineHeight: 1.65 }}>
              {v.kropp}
            </div>
            <div style={{ marginTop: 24, display: 'flex', gap: 8 }}>
              <Button variant="primary">👍 Like ({Math.floor(v.visninger / 4)})</Button>
              <Button variant="ghost">💬 Kommentar</Button>
              <Button variant="ghost">Del på Teams</Button>
            </div>
          </div>
        )}
      </Card>
    </div>
  );
}

Object.assign(window, { IntranettWorkspaceMock, IntForsideMock, IntChatMock, IntAIMock, IntKunngjoringerMock });
