// handbok-screens.jsx — Shared workspace for håndbøker.
// HandbookWorkspace tar config = { tittel, undertittel, ikon, brand, kapitler,
// lesebekreftelse?, eier, intro }. Brukes av Personalhåndbok og Lederhåndbok.

function HandbookWorkspaceMock({ config, go }) {
  const allArticles = config.kapitler.flatMap(k => k.artikler.map(a => ({ ...a, kapittel: k })));

  const [activeId, setActiveId] = React.useState(allArticles[0]?.id);
  const [search, setSearch] = React.useState('');
  const [showAck, setShowAck] = React.useState(false);

  // Filter ved søk
  const matches = (a) => {
    if (!search) return true;
    const t = search.toLowerCase();
    return a.tittel.toLowerCase().includes(t)
      || a.intro?.toLowerCase().includes(t)
      || a.kropp?.some(b => b.text?.toLowerCase().includes(t) || b.items?.some(i => i.toLowerCase().includes(t)))
      || a.nokkel?.some(n => n.toLowerCase().includes(t));
  };

  const filteredKap = config.kapitler.map(k => ({
    ...k, artikler: k.artikler.filter(matches),
  })).filter(k => k.artikler.length > 0);

  // Når man søker — auto-velg første treff
  React.useEffect(() => {
    if (search && filteredKap.length > 0 && !filteredKap.some(k => k.artikler.some(a => a.id === activeId))) {
      setActiveId(filteredKap[0].artikler[0].id);
    }
  }, [search]);

  const aktiv = allArticles.find(a => a.id === activeId);
  const aktivKapittel = aktiv?.kapittel;

  const goToRef = (ref) => {
    if (ref) setActiveId(ref);
  };

  // Lesebekreftelse-stats
  const lesebekr = config.lesebekreftelse;
  const minHistorikk = lesebekr?.minHistorikk || {};
  const lestAvMeg = aktiv && minHistorikk[aktiv.id];
  const minTotalLest = Object.keys(minHistorikk).length;

  return (
    <div className="ok-content__inner" style={{ maxWidth: 1400 }}>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 20 }}>
        <div style={{ display: 'flex', alignItems: 'flex-end', gap: 16 }}>
          <div style={{
            width: 56, height: 56, borderRadius: 12, flexShrink: 0,
            background: config.brand + '15', color: config.brand,
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            fontSize: 28, fontWeight: 700,
          }}>{config.ikon}</div>
          <div>
            <div style={{ fontSize: 11, fontWeight: 600, color: SK.soft, letterSpacing: 0.08, textTransform: 'uppercase' }}>Håndbok</div>
            <h1 style={{ margin: '4px 0 0', fontSize: 26, fontWeight: 600, letterSpacing: -0.02 }}>{config.tittel}</h1>
            <div style={{ marginTop: 4, color: SK.soft, fontSize: 13 }}>{config.undertittel}</div>
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          {lesebekr && (
            <Button variant="ghost" size="sm" onClick={() => setShowAck(s => !s)}>
              Min lesestatus · {minTotalLest}/{allArticles.length}
            </Button>
          )}
          <Button size="sm" icon={I.download}>Last ned PDF</Button>
          <Button variant="primary" size="sm" icon={I.plus}>Ny artikkel</Button>
        </div>
      </div>

      {/* Søke- og metalinje */}
      <div style={{
        display: 'flex', alignItems: 'center', gap: 12,
        padding: '10px 14px', background: SK.pureWhite,
        border: '1px solid rgba(17,24,61,.08)', borderRadius: 10, marginBottom: 14,
      }}>
        <input
          className="ok-input ok-input--search"
          placeholder={`Søk i ${config.tittel.toLowerCase()}…`}
          value={search}
          onChange={e => setSearch(e.target.value)}
          style={{ maxWidth: 320 }}
        />
        <div style={{ display: 'flex', gap: 14, fontSize: 11.5, color: SK.soft }}>
          <span><b style={{ color: SK.ink }}>{allArticles.length}</b> artikler i <b style={{ color: SK.ink }}>{config.kapitler.length}</b> kapitler</span>
          <span>· Eier: <b style={{ color: SK.ink }}>{TEAM[config.eier]?.n || config.eier}</b></span>
          <span>· Sist publisert: <b style={{ color: SK.ink }}>{config.sistPublisert}</b></span>
        </div>
      </div>

      {/* Lesestatus-banner (kun personalhåndbok hvis åpnet) */}
      {showAck && lesebekr && (
        <Card padded style={{ marginBottom: 14 }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
            <div>
              <div style={{ fontSize: 11, fontWeight: 600, color: SK.soft, letterSpacing: 0.05, textTransform: 'uppercase' }}>Lesestatus · ansatte</div>
              <div style={{ fontSize: 17, fontWeight: 600, marginTop: 4 }}>Bekreftet lest pr. kapittel</div>
            </div>
            <div style={{ flex: 1, display: 'grid', gridTemplateColumns: 'repeat(6, 1fr)', gap: 10 }}>
              {config.kapitler.map(k => {
                const pct = Math.round(((lesebekr.bekreftet[k.id] || 0) / lesebekr.totalAnsatte) * 100);
                return (
                  <div key={k.id} style={{ background: SK.iceBlueLight, padding: 10, borderRadius: 8 }}>
                    <div style={{ fontSize: 10, fontWeight: 600, color: SK.soft, letterSpacing: 0.04, textTransform: 'uppercase' }}>Kap. {k.nr}</div>
                    <div style={{ fontSize: 18, fontWeight: 700, color: pct >= 80 ? SK.success : pct >= 60 ? '#8e5a05' : SK.coral, marginTop: 2 }}>{pct} %</div>
                    <div style={{ fontSize: 10.5, color: SK.soft, marginTop: 2 }}>{lesebekr.bekreftet[k.id]}/{lesebekr.totalAnsatte}</div>
                  </div>
                );
              })}
            </div>
            <Button variant="ghost" size="icon" onClick={() => setShowAck(false)}>×</Button>
          </div>
        </Card>
      )}

      {/* Hoved-layout: TOC + artikkel */}
      <div style={{ display: 'grid', gridTemplateColumns: '300px 1fr', gap: 14, alignItems: 'flex-start' }}>
        {/* TOC */}
        <Card padded={false} style={{ position: 'sticky', top: 14, maxHeight: 'calc(100vh - 200px)', overflowY: 'auto' }}>
          <div style={{ padding: '4px 0' }}>
            {filteredKap.length === 0 ? (
              <div style={{ padding: '40px 18px', textAlign: 'center', color: SK.soft, fontSize: 12.5 }}>
                Ingen treff på "<b>{search}</b>".
              </div>
            ) : (
              filteredKap.map((k, ki) => (
                <div key={k.id} style={{ borderBottom: ki === filteredKap.length - 1 ? 'none' : '1px solid rgba(17,24,61,.05)', padding: '8px 0' }}>
                  <div style={{
                    padding: '6px 14px', display: 'flex', alignItems: 'center', gap: 8,
                    fontSize: 11.5, fontWeight: 700, color: SK.ink,
                  }}>
                    <span style={{
                      width: 22, height: 22, borderRadius: 4, flexShrink: 0,
                      background: config.brand + '15', color: config.brand,
                      display: 'flex', alignItems: 'center', justifyContent: 'center',
                      fontSize: 12, fontWeight: 700,
                    }}>{k.nr}</span>
                    <span>{k.tittel}</span>
                  </div>
                  {k.artikler.map(a => {
                    const aktiv = a.id === activeId;
                    const lest = !!minHistorikk[a.id];
                    return (
                      <button
                        key={a.id}
                        onClick={() => setActiveId(a.id)}
                        style={{
                          display: 'flex', alignItems: 'center', gap: 8,
                          width: '100%', textAlign: 'left',
                          padding: '7px 14px 7px 44px',
                          background: aktiv ? config.brand + '12' : 'transparent',
                          color: aktiv ? config.brand : SK.ink,
                          border: 0, cursor: 'pointer', fontFamily: 'inherit',
                          fontSize: 12, fontWeight: aktiv ? 600 : 500,
                          borderLeft: `3px solid ${aktiv ? config.brand : 'transparent'}`,
                        }}
                      >
                        <span style={{ flex: 1 }}>{a.tittel}</span>
                        {lest && lesebekr && (
                          <span title={`Lest ${minHistorikk[a.id]}`} style={{
                            color: SK.success, fontSize: 14, lineHeight: 1, flexShrink: 0,
                          }}>✓</span>
                        )}
                      </button>
                    );
                  })}
                </div>
              ))
            )}
          </div>
        </Card>

        {/* Artikkel */}
        {aktiv && (
          <Card padded>
            <div style={{ padding: '4px 6px 0' }}>
              <div style={{ display: 'flex', alignItems: 'center', gap: 6, fontSize: 11, color: SK.soft, fontWeight: 600, letterSpacing: 0.05, textTransform: 'uppercase' }}>
                <span>Kapittel {aktivKapittel?.nr} · {aktivKapittel?.tittel}</span>
              </div>
              <h2 style={{ margin: '4px 0 0', fontSize: 26, fontWeight: 600, letterSpacing: -0.02, color: SK.ink }}>{aktiv.tittel}</h2>
              <p style={{ margin: '8px 0 0', fontSize: 15, color: SK.soft, lineHeight: 1.5 }}>{aktiv.intro}</p>

              {/* Artikkel-meta */}
              <div style={{
                display: 'flex', alignItems: 'center', gap: 16,
                marginTop: 16, padding: '10px 14px',
                background: SK.iceBlueLight, borderRadius: 8,
                fontSize: 11.5, color: SK.soft,
              }}>
                <div>
                  <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: 0.04, textTransform: 'uppercase' }}>Eier</div>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 3 }}>
                    {TEAM[aktiv.eier] && <Avatar initials={aktiv.eier} color={TEAM[aktiv.eier].c} size={18} />}
                    <span style={{ color: SK.ink, fontWeight: 600, fontSize: 12 }}>{TEAM[aktiv.eier]?.n || aktiv.eier}</span>
                  </div>
                </div>
                <div>
                  <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: 0.04, textTransform: 'uppercase' }}>Sist revidert</div>
                  <div style={{ color: SK.ink, fontWeight: 600, fontSize: 12, marginTop: 3 }}>{aktiv.revidert}</div>
                </div>
                <div>
                  <div style={{ fontSize: 10, fontWeight: 600, letterSpacing: 0.04, textTransform: 'uppercase' }}>Versjon</div>
                  <div style={{ color: SK.ink, fontWeight: 600, fontSize: 12, marginTop: 3 }}>{aktiv.versjon}</div>
                </div>
                {lesebekr && (
                  <div style={{ marginLeft: 'auto' }}>
                    {lestAvMeg ? (
                      <span style={{ display: 'inline-flex', alignItems: 'center', gap: 6, padding: '4px 10px', background: '#dbeed8', color: SK.success, borderRadius: 99, fontSize: 11, fontWeight: 600 }}>
                        ✓ Lest {lestAvMeg}
                      </span>
                    ) : (
                      <Button variant="primary" size="sm">Bekreft som lest</Button>
                    )}
                  </div>
                )}
              </div>

              {/* Innhold */}
              <div style={{ marginTop: 24, fontSize: 14.5, lineHeight: 1.65, color: SK.ink }}>
                {aktiv.kropp.map((b, i) => <Block key={i} block={b} brand={config.brand} />)}
              </div>

              {/* Nøkkelpunkter */}
              {aktiv.nokkel && aktiv.nokkel.length > 0 && (
                <div style={{
                  marginTop: 28, padding: '14px 18px',
                  background: config.brand + '08',
                  border: `1px solid ${config.brand}25`,
                  borderRadius: 10,
                }}>
                  <div style={{ fontSize: 11, fontWeight: 700, color: config.brand, letterSpacing: 0.06, textTransform: 'uppercase', marginBottom: 8 }}>Husk dette</div>
                  <ul style={{ margin: 0, paddingLeft: 18, fontSize: 13.5, lineHeight: 1.5 }}>
                    {aktiv.nokkel.map((n, i) => <li key={i} style={{ marginBottom: 3 }}>{n}</li>)}
                  </ul>
                </div>
              )}

              {/* Relaterte lenker */}
              {aktiv.relatert && aktiv.relatert.length > 0 && (
                <div style={{ marginTop: 22, paddingTop: 16, borderTop: '1px solid rgba(17,24,61,.08)' }}>
                  <div style={{ fontSize: 11, fontWeight: 600, color: SK.soft, letterSpacing: 0.06, textTransform: 'uppercase', marginBottom: 8 }}>Se også</div>
                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                    {aktiv.relatert.map((r, i) => (
                      <button
                        key={i}
                        onClick={() => {
                          if (r.screen) go({ screen: r.screen });
                          else if (r.ref) goToRef(r.ref);
                        }}
                        style={{
                          padding: '6px 12px', background: SK.iceBlueLight,
                          border: '1px solid rgba(17,24,61,.08)', borderRadius: 99,
                          cursor: 'pointer', fontFamily: 'inherit', fontSize: 12, fontWeight: 500,
                          color: SK.ink, display: 'inline-flex', alignItems: 'center', gap: 6,
                        }}
                      >
                        {r.screen ? '↗' : '→'} {r.tittel}
                      </button>
                    ))}
                  </div>
                </div>
              )}

              {/* Footer-nav: forrige / neste */}
              {(() => {
                const idx = allArticles.findIndex(a => a.id === activeId);
                const prev = idx > 0 ? allArticles[idx - 1] : null;
                const next = idx < allArticles.length - 1 ? allArticles[idx + 1] : null;
                return (
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 30, paddingTop: 18, borderTop: '1px solid rgba(17,24,61,.08)', gap: 12 }}>
                    {prev ? (
                      <button onClick={() => setActiveId(prev.id)} style={{
                        textAlign: 'left', padding: '8px 14px',
                        background: 'transparent', border: '1px solid rgba(17,24,61,.1)',
                        borderRadius: 8, cursor: 'pointer', fontFamily: 'inherit', maxWidth: 280,
                      }}>
                        <div style={{ fontSize: 10.5, color: SK.soft, fontWeight: 600, letterSpacing: 0.04, textTransform: 'uppercase' }}>← Forrige</div>
                        <div style={{ fontSize: 12.5, fontWeight: 600, color: SK.ink, marginTop: 3 }}>{prev.tittel}</div>
                      </button>
                    ) : <div />}
                    {next ? (
                      <button onClick={() => setActiveId(next.id)} style={{
                        textAlign: 'right', padding: '8px 14px',
                        background: 'transparent', border: '1px solid rgba(17,24,61,.1)',
                        borderRadius: 8, cursor: 'pointer', fontFamily: 'inherit', maxWidth: 280,
                      }}>
                        <div style={{ fontSize: 10.5, color: SK.soft, fontWeight: 600, letterSpacing: 0.04, textTransform: 'uppercase' }}>Neste →</div>
                        <div style={{ fontSize: 12.5, fontWeight: 600, color: SK.ink, marginTop: 3 }}>{next.tittel}</div>
                      </button>
                    ) : <div />}
                  </div>
                );
              })()}
            </div>
          </Card>
        )}
      </div>
    </div>
  );
}

// ── Block-renderer ────────────────────────────────────────────────────────
function Block({ block, brand }) {
  if (block.type === 'p') {
    return <p style={{ margin: '0 0 14px' }}>{block.text}</p>;
  }
  if (block.type === 'h') {
    return <h3 style={{ margin: '20px 0 10px', fontSize: 16, fontWeight: 700, color: SK.ink }}>{block.text}</h3>;
  }
  if (block.type === 'ul') {
    return (
      <ul style={{ margin: '0 0 14px', paddingLeft: 22, lineHeight: 1.6 }}>
        {block.items.map((it, i) => <li key={i} style={{ marginBottom: 4 }}>{it}</li>)}
      </ul>
    );
  }
  if (block.type === 'callout') {
    const palette = {
      warn: { bg: SK.lightCoral, border: SK.coral, color: '#a01a25', icon: '⚠' },
      info: { bg: '#dee1ed', border: brand || SK.lightBlue, color: SK.ink, icon: 'ℹ' },
      success: { bg: '#dbeed8', border: SK.success, color: SK.success, icon: '✓' },
    }[block.tone] || { bg: SK.iceBlueLight, border: 'rgba(17,24,61,.1)', color: SK.ink, icon: '·' };
    return (
      <div style={{
        margin: '14px 0', padding: '12px 14px 12px 40px',
        background: palette.bg, borderLeft: `3px solid ${palette.border}`,
        borderRadius: 6, position: 'relative',
        fontSize: 13.5, lineHeight: 1.5, color: palette.color,
      }}>
        <span style={{
          position: 'absolute', left: 14, top: 12,
          fontSize: 14, fontWeight: 700,
        }}>{palette.icon}</span>
        {block.text}
      </div>
    );
  }
  return null;
}

// ── Wrapper-komponenter ────────────────────────────────────────────────────
function PersonalhandbokMock({ go }) {
  return <HandbookWorkspaceMock
    config={{
      tittel: 'Personalhåndbok',
      undertittel: 'For deg som er ansatt — alt du trenger å vite om hvordan vi jobber hos OsloKollega',
      ikon: '👤',
      brand: '#586ba4',
      eier: 'HM',
      sistPublisert: '15. mars 2026',
      kapitler: PH_KAPITLER,
      lesebekreftelse: PH_LESEBEKR,
    }}
    go={go}
  />;
}

function LederhandbokMock({ go }) {
  return <HandbookWorkspaceMock
    config={{
      tittel: 'Lederhåndbok',
      undertittel: 'For deg som har personalansvar — verktøykasse for å lede mennesker hos OsloKollega',
      ikon: '🧭',
      brand: '#08605f',
      eier: 'KS',
      sistPublisert: '10. april 2026',
      kapitler: LH_KAPITLER,
    }}
    go={go}
  />;
}

Object.assign(window, { HandbookWorkspaceMock, PersonalhandbokMock, LederhandbokMock });
