// prototype-screens-3.jsx — Min tiltaksplan + Ny protokoll-flyt

// ═══════════════════════════════════════════════════════════════════════════
// MIN TILTAKSPLAN — actionplan på tvers av protokoller
// ═══════════════════════════════════════════════════════════════════════════
function TaskBoardMock({ go }) {
  const [pivot, setPivot] = React.useState('gruppe'); // gruppe | ansvarlig | frist
  const [statusFilter, setStatusFilter] = React.useState('open'); // open | all | done
  const [search, setSearch] = React.useState('');
  const [scope, setScope] = React.useState('all'); // all | mine

  // Flat-list alle tiltak med protokoll-kontekst
  const allTiltak = React.useMemo(() =>
    PROTOCOLS.flatMap(pr =>
      pr.tiltak.map(t => ({
        ...t,
        protokoll: pr.title,
        protokollId: pr.id,
        protokollDate: pr.date,
        projectIds: pr.projectIds,
      }))
    ), []);

  const filtered = React.useMemo(() => {
    let r = allTiltak;
    if (statusFilter === 'open') r = r.filter(t => t.status !== 'done');
    if (statusFilter === 'done') r = r.filter(t => t.status === 'done');
    if (scope === 'mine') r = r.filter(t => t.ansvarlig === 'KS' || t.gruppe === 'Ledergruppen');
    if (search) r = r.filter(t => t.title.toLowerCase().includes(search.toLowerCase()));
    return r;
  }, [allTiltak, statusFilter, scope, search]);

  // Pivot
  const groups = React.useMemo(() => {
    const m = new Map();
    for (const t of filtered) {
      const k = pivot === 'gruppe' ? t.gruppe
        : pivot === 'ansvarlig' ? t.ansvarlig
        : daysUntil(t.frist) < 0 ? 'Forsinket'
          : daysUntil(t.frist) < 7 ? 'Denne uka'
          : daysUntil(t.frist) < 14 ? 'Neste uke'
          : 'Senere';
      if (!m.has(k)) m.set(k, []);
      m.get(k).push(t);
    }
    // Sortér tiltak innenfor gruppe på frist
    for (const arr of m.values()) arr.sort((a, b) => new Date(a.frist) - new Date(b.frist));
    return [...m.entries()];
  }, [filtered, pivot]);

  // KPI
  const totalOpen = allTiltak.filter(t => t.status !== 'done').length;
  const overdue = allTiltak.filter(t => t.status !== 'done' && daysUntil(t.frist) < 0).length;
  const thisWeek = allTiltak.filter(t => t.status !== 'done' && daysUntil(t.frist) >= 0 && daysUntil(t.frist) < 7).length;
  const mineOpen = allTiltak.filter(t => t.status !== 'done' && (t.ansvarlig === 'KS' || t.gruppe === 'Ledergruppen')).length;

  return (
    <div className="ok-content__inner">
      <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' }}>Handlingsplan</div>
          <h1 style={{ margin: '6px 0 0', fontSize: 28, fontWeight: 600, letterSpacing: -0.02 }}>Tiltakene fra alle protokoller</h1>
          <div style={{ marginTop: 4, color: SK.soft, fontSize: 13 }}>
            {totalOpen} åpne · {overdue} forsinket · {thisWeek} denne uka
          </div>
        </div>
        <div style={{ display: 'flex', gap: 8 }}>
          <Button size="sm" icon={I.download}>Eksporter ukerapport</Button>
          <Button variant="primary" icon={I.plus}>Manuelt tiltak</Button>
        </div>
      </div>

      {/* KPI strip */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14, marginBottom: 22 }}>
        <Card padded><KPI label="Åpne totalt" value={totalOpen} sub={`${allTiltak.length - totalOpen} fullført`} /></Card>
        <Card padded><KPI label="Forsinket" value={overdue} sub="krever handling" accent={overdue > 0} /></Card>
        <Card padded><KPI label="Denne uka" value={thisWeek} sub="frist innen 7 dager" /></Card>
        <Card padded><KPI label="Mine egne" value={mineOpen} sub="der jeg er ansvarlig" /></Card>
      </div>

      {/* Toolbar */}
      <Card padded={false} style={{ marginBottom: 14 }}>
        <div style={{ padding: '12px 16px', display: 'flex', gap: 10, alignItems: 'center', flexWrap: 'wrap' }}>
          <input
            className="ok-input ok-input--search"
            placeholder="Søk i tiltak…"
            value={search}
            onChange={e => setSearch(e.target.value)}
            style={{ maxWidth: 240 }}
          />

          <div style={{ width: 1, height: 24, background: 'rgba(17,24,61,.1)' }} />
          <span style={{ fontSize: 11, fontWeight: 600, color: SK.soft, letterSpacing: 0.04, textTransform: 'uppercase' }}>Grupper på</span>
          <div style={{ display: 'flex', gap: 0, background: SK.iceBlueLight, borderRadius: 99, padding: 3 }}>
            {[
              ['gruppe', 'Gruppe'], ['ansvarlig', 'Ansvarlig'], ['frist', 'Frist'],
            ].map(([k, l]) => (
              <button key={k} onClick={() => setPivot(k)} style={{
                padding: '5px 14px', fontSize: 12, fontWeight: 500, border: 0, cursor: 'pointer',
                background: pivot === k ? SK.pureWhite : 'transparent',
                color: pivot === k ? SK.ink : SK.soft, borderRadius: 99,
                boxShadow: pivot === k ? '0 1px 3px rgba(17,24,61,.08)' : 'none',
                fontFamily: 'Poppins, sans-serif',
              }}>{l}</button>
            ))}
          </div>

          <div style={{ width: 1, height: 24, background: 'rgba(17,24,61,.1)' }} />
          <div style={{ display: 'flex', gap: 4 }}>
            {[['open', 'Åpne'], ['done', 'Fullført'], ['all', 'Alle']].map(([k, l]) => (
              <button key={k} onClick={() => setStatusFilter(k)} className="ok-btn ok-btn--sm" style={{
                background: statusFilter === k ? SK.ink : 'transparent',
                color: statusFilter === k ? '#fff' : SK.ink,
                borderColor: statusFilter === k ? SK.ink : 'rgba(17,24,61,.15)',
              }}>{l}</button>
            ))}
          </div>

          <div style={{ marginLeft: 'auto', display: 'flex', alignItems: 'center', gap: 8 }}>
            <span style={{ fontSize: 12, color: SK.soft }}>Visning:</span>
            <div style={{ display: 'flex', gap: 0, background: SK.iceBlueLight, borderRadius: 99, padding: 3 }}>
              {[['all', 'Hele org.'], ['mine', 'Mine']].map(([k, l]) => (
                <button key={k} onClick={() => setScope(k)} style={{
                  padding: '5px 12px', fontSize: 12, fontWeight: 500, border: 0, cursor: 'pointer',
                  background: scope === k ? SK.pureWhite : 'transparent',
                  color: scope === k ? SK.ink : SK.soft, borderRadius: 99,
                  fontFamily: 'Poppins, sans-serif',
                }}>{l}</button>
              ))}
            </div>
          </div>
        </div>
      </Card>

      {/* Kolonner per gruppe — kanban-aktig oppsett */}
      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(280px, 1fr))', gap: 12 }}>
        {groups.length === 0 && (
          <Card padded><div style={{ padding: '40px 0', textAlign: 'center', color: SK.soft }}>Ingen tiltak matcher filtrene.</div></Card>
        )}
        {groups.map(([gKey, items]) => {
          const label = pivot === 'ansvarlig' ? (TEAM[gKey]?.n || gKey) : gKey;
          const done = items.filter(t => t.status === 'done').length;
          const isOverdueGroup = gKey === 'Forsinket';
          return (
            <Card key={gKey} padded={false} style={{
              borderTop: `3px solid ${isOverdueGroup ? SK.coral : pivot === 'ansvarlig' ? (TEAM[gKey]?.c || SK.ink) : SK.ink}`,
            }}>
              <div style={{ padding: '12px 14px 8px', display: 'flex', alignItems: 'center', gap: 8 }}>
                {pivot === 'ansvarlig' && TEAM[gKey] ? (
                  <Avatar initials={TEAM[gKey].i} color={TEAM[gKey].c} size={22} />
                ) : null}
                <h3 style={{ margin: 0, fontSize: 13, fontWeight: 600, flex: 1, minWidth: 0,
                  color: isOverdueGroup ? SK.coral : SK.ink,
                }}>{label}</h3>
                <span style={{ fontSize: 11, color: SK.soft, fontWeight: 500 }}>
                  {statusFilter === 'open' ? items.length : `${done}/${items.length}`}
                </span>
              </div>
              <div style={{ padding: '0 8px 10px', display: 'flex', flexDirection: 'column', gap: 6 }}>
                {items.map(t => {
                  const d = daysUntil(t.frist);
                  return (
                    <div key={t.protokollId + t.id} style={{
                      padding: '10px 12px', borderRadius: 8,
                      background: SK.pureWhite, border: '1px solid rgba(17,24,61,.06)',
                      cursor: 'pointer',
                    }}
                      onClick={() => go({ screen: 'protocol', id: t.protokollId })}
                    >
                      <div style={{ display: 'flex', alignItems: 'flex-start', gap: 8 }}>
                        <input
                          type="checkbox"
                          checked={t.status === 'done'}
                          onClick={(e) => e.stopPropagation()}
                          onChange={() => {}}
                          style={{ marginTop: 2, accentColor: SK.coral, flexShrink: 0 }}
                        />
                        <div style={{ flex: 1, minWidth: 0 }}>
                          <div style={{
                            fontSize: 12.5, lineHeight: 1.35,
                            textDecoration: t.status === 'done' ? 'line-through' : 'none',
                            color: t.status === 'done' ? SK.soft : SK.ink,
                          }}>{t.title}</div>
                          <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginTop: 6, flexWrap: 'wrap' }}>
                            {pivot !== 'ansvarlig' && (
                              <span style={{ display: 'inline-flex', alignItems: 'center', gap: 4 }}>
                                <Avatar initials={TEAM[t.ansvarlig]?.i} color={TEAM[t.ansvarlig]?.c} size={16} />
                                <span style={{ fontSize: 10.5, color: SK.soft }}>{TEAM[t.ansvarlig]?.n.split(' ')[0]}</span>
                              </span>
                            )}
                            {pivot !== 'gruppe' && pivot !== 'frist' && (
                              <span style={{ fontSize: 10.5, color: SK.soft }}>{t.gruppe}</span>
                            )}
                            {pivot !== 'frist' && (
                              <Pill status={d < 0 ? 'delay' : d < 7 ? 'risk' : 'draft'} style={{ fontSize: 9.5, padding: '1px 7px' }}>
                                {d < 0 ? `${Math.abs(d)} dgr forsinket` : d === 0 ? 'i dag' : `om ${d} dgr`}
                              </Pill>
                            )}
                          </div>
                          <div style={{ fontSize: 10.5, color: SK.soft, marginTop: 5, opacity: 0.7 }}>
                            fra «{t.protokoll}»
                          </div>
                        </div>
                      </div>
                    </div>
                  );
                })}
                {items.length === 0 && (
                  <div style={{ padding: '20px 12px', textAlign: 'center', fontSize: 11.5, color: SK.soft }}>Ingen tiltak</div>
                )}
              </div>
            </Card>
          );
        })}
      </div>
    </div>
  );
}

// ═══════════════════════════════════════════════════════════════════════════
// NY PROTOKOLL-FLYT — tre inngangskort
// ═══════════════════════════════════════════════════════════════════════════
function NewProtocol({ go }) {
  const [step, setStep] = React.useState('choose'); // choose | live | upload | manual
  const [meetingName, setMeetingName] = React.useState('');
  const [linkedProject, setLinkedProject] = React.useState('');
  const [attendees, setAttendees] = React.useState(['KS']);

  const toggleAttendee = (k) => {
    setAttendees(a => a.includes(k) ? a.filter(x => x !== k) : [...a, k]);
  };

  if (step === 'choose') {
    return (
      <div className="ok-content__inner" style={{ maxWidth: 900 }}>
        <div style={{ marginBottom: 22 }}>
          <div style={{ fontSize: 11, fontWeight: 600, color: SK.soft, letterSpacing: 0.08, textTransform: 'uppercase' }}>Nytt referat</div>
          <h1 style={{ margin: '6px 0 0', fontSize: 28, fontWeight: 600, letterSpacing: -0.02 }}>Hvordan vil du lage protokoll?</h1>
          <div style={{ marginTop: 4, color: SK.soft, fontSize: 13 }}>
            AI lager utkast med sammendrag, vedtak og tiltaksplan i alle tre tilfeller. Du har siste ord.
          </div>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }}>
          {[
            {
              k: 'live', icon: I.mic, title: 'Spille inn nå',
              desc: 'Live-transkripsjon under møtet. AI bygger utkast og fanger tiltak underveis. Klar ~30 sek etter møtet.',
              tag: 'Anbefalt', tagAccent: true,
              cta: 'Start opptak',
            },
            {
              k: 'upload', icon: I.download, title: 'Last opp opptak',
              desc: '.mp3 / .mp4 / Teams-opptak / .m4a. Dra inn filen eller velg fra disk. Transkripsjon tar ca. 2 min per times opptak.',
              tag: 'Etter møtet',
              cta: 'Velg fil',
            },
            {
              k: 'manual', icon: I.doc, title: 'Skriv selv',
              desc: 'Tom mal med struktur. AI hjelper med formulering, henter tiltak fra teksten, foreslår frister.',
              tag: 'Tradisjonell',
              cta: 'Åpne mal',
            },
          ].map(opt => (
            <Card key={opt.k} padded style={{ cursor: 'pointer', position: 'relative' }}>
              <div onClick={() => setStep(opt.k)} style={{ padding: 8 }}>
                <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
                  <div style={{
                    width: 44, height: 44, borderRadius: 12, background: opt.tagAccent ? SK.lightCoral : SK.iceBlue,
                    color: opt.tagAccent ? SK.coral : SK.ink,
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}>{opt.icon}</div>
                  <Pill status={opt.tagAccent ? 'delay' : 'draft'}>{opt.tag}</Pill>
                </div>
                <h3 style={{ margin: '14px 0 6px', fontSize: 17, fontWeight: 600 }}>{opt.title}</h3>
                <p style={{ margin: 0, fontSize: 12.5, lineHeight: 1.5, color: SK.soft, minHeight: 60 }}>{opt.desc}</p>
                <div style={{ marginTop: 16 }}>
                  <Button variant={opt.tagAccent ? 'accent' : 'default'} size="sm">{opt.cta} →</Button>
                </div>
              </div>
            </Card>
          ))}
        </div>

        <div style={{ marginTop: 22 }}>
          <Card title="Hentes automatisk fra kalenderen" action={<span style={{ fontSize: 10.5, color: SK.soft }}>Outlook · Teams</span>}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 0 }}>
              {[
                { t: 'Inntakssamtale uke 21', d: 'I dag 11:00', dur: '60 min', a: ['KS'] },
                { t: 'Teamledermøte', d: 'I dag 14:30', dur: '60 min', a: ['KS', 'MR', 'TM', 'HE'] },
                { t: 'Samarbeid NAV Nordstrand', d: 'I morgen 09:00', dur: '45 min', a: ['KS', 'TM'] },
              ].map((m, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '11px 0', borderTop: i ? '1px solid rgba(17,24,61,.06)' : 'none' }}>
                  <span style={{ fontSize: 12, fontWeight: 600, width: 100 }}>{m.d}</span>
                  <div style={{ flex: 1 }}>
                    <div style={{ fontSize: 13, fontWeight: 500 }}>{m.t}</div>
                    <div style={{ fontSize: 11, color: SK.soft, marginTop: 2 }}>{m.dur}</div>
                  </div>
                  <AvatarGroup people={m.a.map(k => TEAM[k])} />
                  <Button size="sm" variant="accent" icon={I.mic}>Spill inn</Button>
                </div>
              ))}
            </div>
          </Card>
        </div>
      </div>
    );
  }

  if (step === 'live' || step === 'upload' || step === 'manual') {
    const title = step === 'live' ? 'Forbered live opptak' : step === 'upload' ? 'Last opp opptak' : 'Skriv referat manuelt';

    return (
      <div className="ok-content__inner" style={{ maxWidth: 720 }}>
        <div style={{ marginBottom: 18 }}>
          <Button size="sm" variant="ghost" onClick={() => setStep('choose')}>← Tilbake</Button>
        </div>

        <Card padded>
          <div style={{ padding: 10 }}>
            <h2 style={{ margin: 0, fontSize: 20, fontWeight: 600 }}>{title}</h2>
            <p style={{ margin: '6px 0 24px', color: SK.soft, fontSize: 13 }}>
              Disse opplysningene hjelper AI å forstå kontekst — koble til prosjekt, fordele tiltak riktig osv.
            </p>

            <div style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
              {/* Møtenavn */}
              <div>
                <label style={{ fontSize: 11.5, fontWeight: 600, color: SK.soft, letterSpacing: 0.04, textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>Møtetittel</label>
                <input
                  className="ok-input"
                  placeholder="F.eks. Ledergruppemøte 28. mai"
                  value={meetingName}
                  onChange={e => setMeetingName(e.target.value)}
                />
              </div>

              {/* Prosjekt-kobling */}
              <div>
                <label style={{ fontSize: 11.5, fontWeight: 600, color: SK.soft, letterSpacing: 0.04, textTransform: 'uppercase', display: 'block', marginBottom: 6 }}>Koble til prosjekt</label>
                <select
                  className="ok-input"
                  value={linkedProject}
                  onChange={e => setLinkedProject(e.target.value)}
                >
                  <option value="">Ingen kobling</option>
                  {PROJECTS.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
                </select>
                <div style={{ fontSize: 11, color: SK.soft, marginTop: 6 }}>
                  Du kan koble flere prosjekter etterpå. Tiltak fra protokollen kommer automatisk inn på prosjektets tiltaksliste.
                </div>
              </div>

              {/* Deltakere */}
              <div>
                <label style={{ fontSize: 11.5, fontWeight: 600, color: SK.soft, letterSpacing: 0.04, textTransform: 'uppercase', display: 'block', marginBottom: 8 }}>Deltakere</label>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 6 }}>
                  {Object.entries(TEAM).map(([k, p]) => {
                    const sel = attendees.includes(k);
                    return (
                      <button key={k} onClick={() => toggleAttendee(k)} style={{
                        display: 'flex', alignItems: 'center', gap: 7,
                        padding: '5px 12px 5px 5px', borderRadius: 99,
                        background: sel ? SK.ink : SK.pureWhite, color: sel ? '#fff' : SK.ink,
                        border: `1px solid ${sel ? SK.ink : 'rgba(17,24,61,.15)'}`,
                        cursor: 'pointer', fontSize: 12, fontWeight: 500, fontFamily: 'Poppins, sans-serif',
                      }}>
                        <Avatar initials={p.i} color={sel ? '#fff' : p.c} size={20} style={{ borderColor: sel ? SK.ink : '#fff' }} />
                        {p.n}
                      </button>
                    );
                  })}
                </div>
                <div style={{ fontSize: 11, color: SK.soft, marginTop: 8 }}>
                  {attendees.length} valgt. Eksterne kan inviteres via e-post.
                </div>
              </div>

              {/* Step-spesifikt innhold */}
              {step === 'live' && (
                <Card flat style={{ background: SK.iceBlueLight, border: 0 }}>
                  <div style={{ padding: 14, display: 'flex', alignItems: 'center', gap: 14 }}>
                    <div style={{
                      width: 44, height: 44, borderRadius: '50%', background: SK.coral, color: '#fff',
                      display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                    }}>{I.mic}</div>
                    <div style={{ flex: 1 }}>
                      <div style={{ fontSize: 13, fontWeight: 600 }}>Klar til å spille inn</div>
                      <div style={{ fontSize: 11.5, color: SK.soft, marginTop: 2 }}>
                        Live-transkripsjon på norsk · skiller mellom talere · konfidensielt
                      </div>
                    </div>
                  </div>
                </Card>
              )}
              {step === 'upload' && (
                <Card flat style={{ borderStyle: 'dashed', borderColor: 'rgba(17,24,61,.2)' }}>
                  <div style={{ padding: 30, textAlign: 'center' }}>
                    <div style={{ fontSize: 24, color: SK.soft, marginBottom: 6 }}>⤴</div>
                    <div style={{ fontSize: 13, fontWeight: 600 }}>Dra inn lyd- eller videofil</div>
                    <div style={{ fontSize: 11.5, color: SK.soft, marginTop: 4 }}>
                      eller <span style={{ color: SK.coral, textDecoration: 'underline', cursor: 'pointer' }}>velg fra disken</span> · mp3 / m4a / mp4 / Teams-opptak · maks 2 GB
                    </div>
                  </div>
                </Card>
              )}
              {step === 'manual' && (
                <Card flat>
                  <div style={{ padding: 14 }}>
                    <div style={{ fontSize: 11.5, fontWeight: 600, color: SK.soft, letterSpacing: 0.04, textTransform: 'uppercase', marginBottom: 8 }}>Velg mal</div>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
                      {[
                        { t: 'Ledergruppemøte', d: 'Status portefølje · vedtak · tiltak per avdeling' },
                        { t: 'Teammøte', d: 'Agenda · oppfølging forrige møte · neste steg' },
                        { t: '1:1 / utviklingssamtale', d: 'Mål · status · trivsel · oppfølging' },
                        { t: 'Anbudsmøte', d: 'Status · gjenstående · ansvar' },
                        { t: 'Tom mal', d: 'Bare standardseksjoner: sammendrag, vedtak, tiltak' },
                      ].map((m, i) => (
                        <div key={i} style={{
                          display: 'flex', alignItems: 'center', gap: 10, padding: '8px 10px',
                          borderRadius: 8, border: '1px solid rgba(17,24,61,.08)', cursor: 'pointer',
                        }}>
                          <input type="radio" name="template" defaultChecked={i === 0} style={{ accentColor: SK.coral }} />
                          <div style={{ flex: 1 }}>
                            <div style={{ fontSize: 12.5, fontWeight: 500 }}>{m.t}</div>
                            <div style={{ fontSize: 11, color: SK.soft, marginTop: 2 }}>{m.d}</div>
                          </div>
                        </div>
                      ))}
                    </div>
                  </div>
                </Card>
              )}
            </div>

            <div style={{ marginTop: 26, display: 'flex', justifyContent: 'flex-end', gap: 8 }}>
              <Button size="sm" variant="ghost" onClick={() => setStep('choose')}>Avbryt</Button>
              <Button variant="accent" onClick={() => go({ screen: 'protocol', id: 'ledgr-21-5' })}>
                {step === 'live' ? '● Start opptak' : step === 'upload' ? 'Last opp og transkriber' : 'Åpne mal'}
              </Button>
            </div>
          </div>
        </Card>
      </div>
    );
  }
}
 Object.assign(window, { TaskBoardMock, NewProtocol });
