// prototype-screens-5.jsx — Protokoll-hub, møteserie-detalj, hjelpere
// Fyller inn manglende komponenter referert fra screens-2 og app.jsx.

// ── Hjelpere brukt av protokoll-skjermen ──────────────────────────────────
const SERIES_ICONS = {
  crown: <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M3 6l4 4 5-7 5 7 4-4 1 12H2L3 6zm1 14h16v2H4v-2z"/></svg>,
  shield: <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M12 2L4 5v7c0 5 3.5 9 8 10 4.5-1 8-5 8-10V5l-8-3z"/></svg>,
  users: <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><circle cx="9" cy="7" r="3.5"/><circle cx="17" cy="9" r="2.5"/><path d="M2 19c0-3 3-5 7-5s7 2 7 5v1H2v-1zm14-1c0-2 2-3 4-3s4 1 4 3v1h-8v-1z"/></svg>,
  msg: <svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M3 4h18v13H7l-4 4V4z"/></svg>,
};

const CONF_TONES = {
  'åpen':       { bg: '#dbeed8', fg: '#1b6a2e', label: 'Åpen' },
  'begrenset':  { bg: '#fdeac8', fg: '#8e5a05', label: 'Begrenset' },
  'fortrolig':  { bg: '#fcddde', fg: '#a01a25', label: 'Fortrolig' },
};

const CadenceBadge = ({ children, style }) => (
  <span style={{
    display: 'inline-flex', alignItems: 'center', gap: 4,
    padding: '2px 9px', borderRadius: 99, fontSize: 10.5, fontWeight: 600,
    background: SK.iceBlueLight, color: SK.ink, letterSpacing: 0.02,
    fontFamily: 'Poppins, sans-serif', ...style,
  }}>{children}</span>
);

const ConfPill = ({ level, style }) => {
  const t = CONF_TONES[level] || CONF_TONES['åpen'];
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center', gap: 4,
      padding: '2px 9px', borderRadius: 99, fontSize: 10.5, fontWeight: 600,
      background: t.bg, color: t.fg, letterSpacing: 0.02,
      fontFamily: 'Poppins, sans-serif', ...style,
    }}>
      <span style={{ width: 5, height: 5, borderRadius: '50%', background: t.fg }} />
      {t.label}
    </span>
  );
};

// ═══════════════════════════════════════════════════════════════════════════
// PROTOCOL HUB — landingsside for møter & protokoller
// ═══════════════════════════════════════════════════════════════════════════
function ProtocolHubMock({ go }) {
  // KPI
  const draftCount = PROTOCOLS.filter(p => p.status === 'draft').length;
  const reviewCount = PROTOCOLS.filter(p => p.status === 'review').length;
  const openCarry = Object.keys(CARRYOVER).reduce((sum, pid) => {
    const cur = PROTOCOLS.find(p => p.id === pid);
    if (!cur) return sum;
    const prev = PROTOCOLS.find(p => p.id === CARRYOVER[pid].prevId);
    if (!prev) return sum;
    return sum + prev.tiltak.filter(t => t.status !== 'done').length;
  }, 0);

  return (
    <div className="ok-content__inner">
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', marginBottom: 22 }}>
        <div>
          <div style={{ fontSize: 11, fontWeight: 600, color: SK.soft, letterSpacing: 0.08, textTransform: 'uppercase' }}>Møter & referater</div>
          <h1 style={{ margin: '6px 0 0', fontSize: 28, fontWeight: 600, letterSpacing: -0.02 }}>Protokoller</h1>
          <div style={{ marginTop: 4, color: SK.soft, fontSize: 13 }}>
            {MEETING_SERIES.length} faste møteserier · {PROTOCOLS.length} protokoller totalt
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <Button size="sm" icon={I.download}>Last opp opptak</Button>
          <Button variant="primary" icon={I.mic} onClick={() => go({ screen: 'new-protocol' })}>Start nytt opptak</Button>
        </div>
      </div>

      {/* KPI strip */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 22 }}>
        <Card padded><KPI label="Faste møteserier" value={MEETING_SERIES.length} sub="med egen tilgangsstyring" /></Card>
        <Card padded><KPI label="Utkast" value={draftCount} sub="venter på godkjenning" accent={draftCount > 0} /></Card>
        <Card padded><KPI label="Til gjennomgang" value={reviewCount} sub="signering" /></Card>
        <Card padded><KPI label="Åpne tiltak fra forrige" value={openCarry} sub="til behandling i neste møte" accent={openCarry > 0} /></Card>
      </div>

      {/* Møteserier */}
      <div style={{ marginBottom: 14 }}>
        <div style={{ fontSize: 12, fontWeight: 600, color: SK.soft, letterSpacing: 0.06, textTransform: 'uppercase', marginBottom: 10 }}>
          Møteserier
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 14 }}>
          {MEETING_SERIES.map(s => {
            const series_protocols = PROTOCOLS.filter(p => p.seriesId === s.id);
            const lastProtocol = series_protocols.sort((a, b) => new Date(b.date) - new Date(a.date))[0];
            const openTiltak = series_protocols.reduce((sum, pr) => sum + pr.tiltak.filter(t => t.status !== 'done').length, 0);
            return (
              <Card key={s.id} padded={false} style={{ cursor: 'pointer', borderTop: `3px solid ${s.accent}` }}>
                <div onClick={() => go({ screen: 'series', id: s.id })} style={{ padding: 16 }}>
                  <div style={{ display: 'flex', alignItems: 'flex-start', gap: 12, marginBottom: 12 }}>
                    <div style={{
                      width: 38, height: 38, borderRadius: 10,
                      background: s.accent + '22', color: s.accent,
                      display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                    }}>{SERIES_ICONS[s.icon]}</div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 15, fontWeight: 600, letterSpacing: -0.01 }}>{s.name}</div>
                      <div style={{ fontSize: 11.5, color: SK.soft, marginTop: 2 }}>{s.desc}</div>
                    </div>
                  </div>

                  <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6, marginBottom: 12 }}>
                    <CadenceBadge>{s.cadenceShort}</CadenceBadge>
                    <ConfPill level={s.confidentiality} />
                  </div>

                  <div style={{ display: 'flex', flexDirection: 'column', gap: 6, fontSize: 12 }}>
                    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                      <span style={{ color: SK.soft }}>Neste møte</span>
                      <span style={{ fontWeight: 600 }}>{fmtDate(s.nextDate)} · {s.nextTime.split(' ')[0]}</span>
                    </div>
                    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                      <span style={{ color: SK.soft }}>Forrige protokoll</span>
                      <span style={{ fontWeight: 600 }}>
                        {lastProtocol ? fmtDate(lastProtocol.date) : '—'}
                      </span>
                    </div>
                    <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                      <span style={{ color: SK.soft }}>Åpne tiltak fra serien</span>
                      <span style={{ fontWeight: 600, color: openTiltak > 0 ? SK.coral : SK.ink }}>{openTiltak}</span>
                    </div>
                  </div>

                  <div style={{ marginTop: 14, paddingTop: 12, borderTop: '1px solid rgba(17,24,61,.06)', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                    <AvatarGroup people={s.members.map(k => TEAM[k])} max={4} />
                    <span style={{ fontSize: 11, color: SK.soft }}>{s.members.length} medlemmer</span>
                  </div>
                </div>
              </Card>
            );
          })}

          {/* + Ny møteserie-kort */}
          <div
            onClick={() => alert('Demo — opprettelse av møteserie kommer i full versjon')}
            style={{
              borderRadius: 12, border: '2px dashed rgba(17,24,61,.18)', background: 'transparent',
              display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
              padding: 24, minHeight: 220, cursor: 'pointer', color: SK.soft,
            }}
          >
            <div style={{
              width: 36, height: 36, borderRadius: '50%', border: '1.5px dashed rgba(17,24,61,.3)',
              display: 'flex', alignItems: 'center', justifyContent: 'center', marginBottom: 10,
            }}>{I.plus}</div>
            <div style={{ fontSize: 13, fontWeight: 600 }}>Ny møteserie</div>
            <div style={{ fontSize: 11, marginTop: 4, textAlign: 'center', maxWidth: 200 }}>
              Definer kadens, medlemmer og fast agenda
            </div>
          </div>
        </div>
      </div>

      {/* Nylige protokoller — alle, uavhengig av serie */}
      <Card padded={false} title="Nylige protokoller">
        <table className="ok-table">
          <thead>
            <tr>
              <th style={{ paddingLeft: 18 }}>Møte</th>
              <th>Serie</th>
              <th>Dato</th>
              <th>Lengde</th>
              <th>Deltakere</th>
              <th>Tiltak</th>
              <th>Status</th>
            </tr>
          </thead>
          <tbody>
            {PROTOCOLS.slice().sort((a, b) => new Date(b.date) - new Date(a.date)).map(pr => {
              const series = MEETING_SERIES.find(s => s.id === pr.seriesId);
              return (
                <TR key={pr.id} onClick={() => go({ screen: 'protocol', id: pr.id })}>
                  <td style={{ paddingLeft: 18 }}>
                    <div style={{ fontWeight: 600 }}>{pr.title}</div>
                    <div style={{ fontSize: 11.5, color: SK.soft, marginTop: 2 }}>{pr.summary?.slice(0, 80)}…</div>
                  </td>
                  <td>
                    {series ? (
                      <span style={{
                        display: 'inline-flex', alignItems: 'center', gap: 6, fontSize: 11.5,
                        padding: '2px 8px', borderRadius: 99,
                        background: series.accent + '22', color: series.accent, fontWeight: 600,
                      }}>{series.name}</span>
                    ) : <span style={{ fontSize: 11.5, color: SK.soft }}>—</span>}
                  </td>
                  <td style={{ fontSize: 12 }}>{fmtDate(pr.date)}</td>
                  <td style={{ fontSize: 12 }}>{pr.duration} min</td>
                  <td><AvatarGroup people={pr.attendees.map(k => TEAM[k])} /></td>
                  <td style={{ fontSize: 12, fontWeight: 600 }}>
                    {pr.tiltak.filter(t => t.status === 'done').length}/{pr.tiltak.length}
                  </td>
                  <td>
                    <Pill status={pr.status === 'approved' ? 'done' : pr.status === 'review' ? 'risk' : 'draft'}>
                      {pr.status === 'approved' ? 'Godkjent' : pr.status === 'review' ? 'Til gjennomgang' : 'Utkast'}
                    </Pill>
                  </td>
                </TR>
              );
            })}
          </tbody>
        </table>
      </Card>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// MEETING SERIES DETAIL
// ═══════════════════════════════════════════════════════════════════════════
function MeetingSeriesDetailMock({ id, go }) {
  const series = MEETING_SERIES.find(s => s.id === id) || MEETING_SERIES[0];
  const series_protocols = PROTOCOLS.filter(p => p.seriesId === series.id)
    .sort((a, b) => new Date(b.date) - new Date(a.date));
  const allTiltak = series_protocols.flatMap(pr =>
    pr.tiltak.map(t => ({ ...t, protokoll: pr.title, protokollId: pr.id, protokollDate: pr.date }))
  );
  const openTiltak = allTiltak.filter(t => t.status !== 'done');
  const lastProtocol = series_protocols[0];

  return (
    <div className="ok-content__inner">
      {/* Header */}
      <div style={{
        padding: 20, marginBottom: 18, borderRadius: 14,
        background: series.accent + '15',
        border: `1px solid ${series.accent}30`,
      }}>
        <div style={{ display: 'flex', alignItems: 'flex-start', gap: 16 }}>
          <div style={{
            width: 56, height: 56, borderRadius: 14,
            background: series.accent, color: '#fff',
            display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
          }}>{React.cloneElement(SERIES_ICONS[series.icon], { width: 24, height: 24 })}</div>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 4 }}>
              <CadenceBadge>{series.cadenceShort}</CadenceBadge>
              <ConfPill level={series.confidentiality} />
            </div>
            <h1 style={{ margin: 0, fontSize: 26, fontWeight: 600, letterSpacing: -0.02 }}>{series.name}</h1>
            <div style={{ marginTop: 4, color: SK.soft, fontSize: 13 }}>{series.desc}</div>
            <div style={{ marginTop: 8, fontSize: 12, color: SK.ink }}>
              {series.cadence} · {series.location}
            </div>
          </div>
          <div style={{ display: 'flex', gap: 8 }}>
            <Button size="sm" variant="ghost">Innstillinger</Button>
            <Button variant="accent" icon={I.mic} onClick={() => go({ screen: 'new-protocol' })}>
              Spille inn neste møte
            </Button>
          </div>
        </div>
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: '1.5fr 1fr', gap: 14 }}>
        {/* Venstre: protokoller i serien */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          {/* Neste møte */}
          <Card padded>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
              <div style={{
                width: 52, height: 52, borderRadius: 10, background: SK.iceBlue,
                display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center',
              }}>
                <div style={{ fontSize: 9, fontWeight: 700, color: SK.soft, textTransform: 'uppercase' }}>
                  {new Date(series.nextDate).toLocaleDateString('nb-NO', { month: 'short' })}
                </div>
                <div style={{ fontSize: 20, fontWeight: 700, color: SK.ink, lineHeight: 1 }}>
                  {new Date(series.nextDate).getDate()}
                </div>
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 11, fontWeight: 600, color: SK.soft, letterSpacing: 0.06, textTransform: 'uppercase' }}>Neste møte</div>
                <div style={{ fontSize: 16, fontWeight: 600, marginTop: 2 }}>
                  {new Date(series.nextDate).toLocaleDateString('nb-NO', { weekday: 'long', day: 'numeric', month: 'long' })}
                </div>
                <div style={{ fontSize: 12, color: SK.soft, marginTop: 2 }}>{series.nextTime} · {series.location}</div>
              </div>
              {lastProtocol && (
                <div style={{ textAlign: 'right' }}>
                  <div style={{ fontSize: 10.5, color: SK.soft, fontWeight: 600, letterSpacing: 0.04, textTransform: 'uppercase' }}>Carryover</div>
                  <div style={{ fontSize: 22, fontWeight: 700, color: openTiltak.length ? SK.coral : SK.ink, lineHeight: 1.1, marginTop: 2 }}>
                    {lastProtocol.tiltak.filter(t => t.status !== 'done').length}
                  </div>
                  <div style={{ fontSize: 10.5, color: SK.soft }}>åpne tiltak å behandle</div>
                </div>
              )}
            </div>
            {series.standardAgenda?.length > 0 && (
              <div style={{ marginTop: 14, paddingTop: 12, borderTop: '1px solid rgba(17,24,61,.06)' }}>
                <div style={{ fontSize: 11, fontWeight: 600, color: SK.soft, letterSpacing: 0.06, textTransform: 'uppercase', marginBottom: 6 }}>
                  Standard agenda
                </div>
                <ol style={{ margin: 0, paddingLeft: 18, fontSize: 12.5, lineHeight: 1.6 }}>
                  {series.standardAgenda.map((a, i) => <li key={i}>{a}</li>)}
                </ol>
              </div>
            )}
          </Card>

          {/* Tidligere protokoller */}
          <Card title={`Tidligere protokoller (${series_protocols.length})`} padded={false}>
            <table className="ok-table">
              <tbody>
                {series_protocols.map(pr => {
                  const open = pr.tiltak.filter(t => t.status !== 'done').length;
                  return (
                    <TR key={pr.id} onClick={() => go({ screen: 'protocol', id: pr.id })}>
                      <td style={{ paddingLeft: 18, width: 70 }}>
                        <div style={{ fontSize: 11, fontWeight: 600, color: SK.soft, textTransform: 'uppercase' }}>
                          {new Date(pr.date).toLocaleDateString('nb-NO', { month: 'short' })}
                        </div>
                        <div style={{ fontSize: 18, fontWeight: 700, lineHeight: 1.1 }}>
                          {new Date(pr.date).getDate()}
                        </div>
                      </td>
                      <td>
                        <div style={{ fontWeight: 600 }}>{pr.title}</div>
                        <div style={{ fontSize: 11.5, color: SK.soft, marginTop: 2 }}>{pr.summary?.slice(0, 100)}…</div>
                      </td>
                      <td style={{ fontSize: 12, textAlign: 'center', fontWeight: 600 }}>
                        {pr.tiltak.filter(t => t.status === 'done').length}/{pr.tiltak.length}
                        <div style={{ fontSize: 10.5, color: open ? SK.coral : SK.soft, fontWeight: 500, marginTop: 1 }}>
                          {open ? `${open} åpne` : 'alt fullført'}
                        </div>
                      </td>
                      <td style={{ paddingRight: 18 }}>
                        <Pill status={pr.status === 'approved' ? 'done' : pr.status === 'review' ? 'risk' : 'draft'}>
                          {pr.status === 'approved' ? 'Godkjent' : pr.status === 'review' ? 'Til gjennomgang' : 'Utkast'}
                        </Pill>
                      </td>
                    </TR>
                  );
                })}
              </tbody>
            </table>
          </Card>
        </div>

        {/* Høyre: medlemmer + tilgang + statistikk */}
        <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
          <Card title={`Medlemmer (${series.members.length})`} action={<Button size="sm" variant="ghost">Endre</Button>}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {series.members.map(k => {
                const p = TEAM[k];
                const isChair = k === series.chair;
                const isWriter = series.writers.includes(k);
                return (
                  <div key={k} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                    <Avatar initials={p.i} color={p.c} />
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 12.5, fontWeight: 500 }}>{p.n}</div>
                      <div style={{ fontSize: 11, color: SK.soft }}>{p.r}</div>
                    </div>
                    <div style={{ display: 'flex', gap: 4 }}>
                      {isChair ? <Pill status="done">Møteleder</Pill> : null}
                      {isWriter && !isChair ? <Pill status="draft">Skriverettighet</Pill> : null}
                    </div>
                  </div>
                );
              })}
            </div>
          </Card>

          <Card title="Tilgang & deling">
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, fontSize: 12.5 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ color: SK.soft }}>Konfidensialitet</span>
                <ConfPill level={series.confidentiality} />
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ color: SK.soft }}>Skriverettighet</span>
                <span style={{ fontWeight: 600 }}>{series.writers.length} personer</span>
              </div>
              <div style={{ paddingTop: 8, marginTop: 4, borderTop: '1px solid rgba(17,24,61,.06)' }}>
                <div style={{ fontSize: 11, fontWeight: 600, color: SK.soft, letterSpacing: 0.04, textTransform: 'uppercase', marginBottom: 6 }}>
                  Tiltak publiseres til
                </div>
                <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
                  {series.accessGroups.map(g => (
                    <div key={g} style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                      <span style={{ width: 6, height: 6, borderRadius: '50%', background: series.accent }} />
                      <span style={{ fontSize: 12 }}>{g}</span>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          </Card>

          <Card title="Statistikk siste 6 mnd">
            <div style={{ display: 'flex', flexDirection: 'column', gap: 6, fontSize: 12.5 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ color: SK.soft }}>Møter avholdt</span>
                <span style={{ fontWeight: 600 }}>{series_protocols.length}</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ color: SK.soft }}>Snitt-lengde</span>
                <span style={{ fontWeight: 600 }}>
                  {Math.round(series_protocols.reduce((s, p) => s + p.duration, 0) / Math.max(1, series_protocols.length))} min
                </span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ color: SK.soft }}>Tiltak fordelt</span>
                <span style={{ fontWeight: 600 }}>{allTiltak.length}</span>
              </div>
              <div style={{ display: 'flex', justifyContent: 'space-between' }}>
                <span style={{ color: SK.soft }}>Gjennomføringsgrad</span>
                <span style={{ fontWeight: 600 }}>
                  {Math.round((allTiltak.filter(t => t.status === 'done').length / Math.max(1, allTiltak.length)) * 100)} %
                </span>
              </div>
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
}
Object.assign(window, { SERIES_ICONS, CadenceBadge, ConfPill, ProtocolHubMock, MeetingSeriesDetailMock });
