// tiltaksplan.jsx — Tiltaksplan med ekte Supabase-data
// Erstatter TaskBoard fra prototype-screens-3.jsx

// ── Supabase-kall ─────────────────────────────────────────────

async function hentTiltak() {
  const { data, error } = await window._sb
    .from('tiltak')
    .select('*, ansvarlig:profiles!ansvarlig_id(id,navn,epost,roller(farge)), enhet:enheter!enhet_id(id,navn), avtale:avtaler!avtale_id(id,name)')
    .order('frist', { ascending: true, nullsFirst: false });
  if (error) throw error;
  return data || [];
}

async function hentTiltakProfilerEnheter() {
  const [pRes, eRes, aRes] = await Promise.all([
    window._sb.from('profiles').select('id,navn,epost,enhet_id,roller(navn,farge,nokkel)').order('navn'),
    window._sb.from('enheter').select('id,navn').eq('aktiv',true).order('sortering'),
    window._sb.from('avtaler').select('id,name').eq('status','aktiv').order('name'),
  ]);
  return { profiler: pRes.data||[], enheter: eRes.data||[], avtaler: aRes.data||[] };
}

async function lagreTiltak(felter, brukerId, brukerNavn) {
  const { data, error } = await window._sb
    .from('tiltak')
    .insert([{ ...felter, opprettet_av: brukerId, opprettet_av_navn: brukerNavn }])
    .select('*, ansvarlig:profiles!ansvarlig_id(id,navn,epost,roller(farge)), enhet:enheter!enhet_id(id,navn), avtale:avtaler!avtale_id(id,name)')
    .single();
  if (error) throw error;
  return data;
}

async function oppdaterTiltak(id, felter) {
  // Fjern join-objekter som ikke er ekte kolonner
  const { ansvarlig, enhet, avtale, opprettet_av_navn, ...rene } = felter;
  const { data, error } = await window._sb
    .from('tiltak')
    .update(rene)
    .eq('id', id)
    .select('*, ansvarlig:profiles!ansvarlig_id(id,navn,epost,roller(farge)), enhet:enheter!enhet_id(id,navn), avtale:avtaler!avtale_id(id,name)')
    .single();
  if (error) throw error;
  return data;
}

async function slettTiltak(id) {
  const { error } = await window._sb.from('tiltak').delete().eq('id', id);
  if (error) throw error;
}

// ── Konstanter ────────────────────────────────────────────────

const TILTAK_STATUS = {
  open:        { label: 'Åpen',       bg: '#e9eef7', fg: '#3c4a6b' },
  in_progress: { label: 'Pågår',      bg: '#fdeac8', fg: '#8e5a05' },
  done:        { label: 'Fullført',   bg: '#dbeed8', fg: '#1b6a2e' },
  avvist:      { label: 'Avvist',     bg: '#fcddde', fg: '#8a1620' },
  utsatt:      { label: 'Utsatt',     bg: '#f1effd', fg: '#4a3a7a' },
};

const TILTAK_PRI = {
  lav:     { label: 'Lav',     dot: '#9aa3b8' },
  normal:  { label: 'Normal',  dot: '#586ba4' },
  hoy:     { label: 'Høy',     dot: '#f2cc8f' },
  kritisk: { label: 'Kritisk', dot: '#f2545c' },
};

const KATEGORI_VALG = [
  'generelt','avtale','strategi','hr','it','kvalitet','rapport','okonomi','drift','hms',
];

function dagerTilFrist(frist) {
  if (!frist) return null;
  return Math.ceil((new Date(frist) - new Date()) / 86400000);
}

function fmtFrist(frist) {
  if (!frist) return '—';
  const d = new Date(frist);
  return d.toLocaleDateString('nb-NO', { day:'numeric', month:'short', year:'numeric' });
}

// ── Tiltak-skjema ─────────────────────────────────────────────

function TiltakSkjema({ tiltak, profiler, enheter, avtaler, brukerId, brukerNavn, onLagret, onAvbryt }) {
  const [tittel,      setTittel]      = React.useState(tiltak?.tittel      || '');
  const [beskrivelse, setBesk]        = React.useState(tiltak?.beskrivelse || '');
  const [ansvarligId, setAnsvarligId] = React.useState(tiltak?.ansvarlig_id || '');
  const [enhetId,     setEnhetId]     = React.useState(tiltak?.enhet_id    || '');
  const [avtaleId,    setAvtaleId]    = React.useState(tiltak?.avtale_id   || '');
  const [kategori,    setKategori]    = React.useState(tiltak?.kategori    || 'generelt');
  const [prioritet,   setPrioritet]   = React.useState(tiltak?.prioritet   || 'normal');
  const [status,      setStatus]      = React.useState(tiltak?.status      || 'open');
  const [frist,       setFrist]       = React.useState(tiltak?.frist       || '');
  const [laster,      setLaster]      = React.useState(false);
  const [feil,        setFeil]        = React.useState(null);

  const lagre = async () => {
    if (!tittel.trim()) { setFeil('Tittel er påkrevd.'); return; }
    setLaster(true); setFeil(null);
    const felter = {
      tittel, beskrivelse,
      ansvarlig_id:   ansvarligId || null,
      ansvarlig_navn: profiler.find(p => p.id === ansvarligId)?.navn || null,
      enhet_id:       enhetId  || null,
      avtale_id:      avtaleId || null,
      kategori, prioritet, status,
      frist: frist || null,
      fullfort_dato: status === 'done' && !tiltak?.fullfort_dato ? new Date().toISOString().split('T')[0] : tiltak?.fullfort_dato || null,
    };
    try {
      const res = tiltak
        ? await oppdaterTiltak(tiltak.id, felter)
        : await lagreTiltak(felter, brukerId, brukerNavn);
      onLagret(res);
    } catch(e) { setFeil(e.message); } finally { setLaster(false); }
  };

  const lbl = { fontSize: 11, fontWeight: 600, color: SK.soft, letterSpacing: 0.04, textTransform: 'uppercase', display: 'block', marginBottom: 5 };
  const inp = { padding: '10px 12px', fontSize: 13 };

  return (
    <div style={{ padding:'18px 20px' }}>
      <div style={{ fontSize:13, fontWeight:600, marginBottom:16 }}>
        {tiltak ? 'Rediger tiltak' : 'Nytt tiltak'}
      </div>
      {feil && (
        <div style={{ background:'#fcddde', border:'1px solid #f2545c', borderRadius:8,
          padding:'9px 13px', fontSize:13, color:'#8a1620', marginBottom:14 }}>{feil}</div>
      )}
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:13, marginBottom:18 }}>

        <div style={{ gridColumn:'1/-1', display:'flex', flexDirection:'column', gap:5 }}>
          <label style={lbl}>Tittel *</label>
          <input className="ok-input" value={tittel} onChange={e=>setTittel(e.target.value)}
            autoFocus style={inp} placeholder="Hva skal gjøres?" />
        </div>

        {/* Ansvarlig – fra profiles */}
        <div style={{ display:'flex', flexDirection:'column', gap:5 }}>
          <label style={lbl}>Ansvarlig</label>
          <select className="ok-input" value={ansvarligId} onChange={e=>setAnsvarligId(e.target.value)} style={inp}>
            <option value="">— Ikke satt —</option>
            {profiler.map(p => (
              <option key={p.id} value={p.id}>
                {p.navn || p.epost}{p.roller?.navn ? ` · ${p.roller.navn}` : ''}
              </option>
            ))}
          </select>
        </div>

        {/* Enhet – fra enheter */}
        <div style={{ display:'flex', flexDirection:'column', gap:5 }}>
          <label style={lbl}>Enhet</label>
          <select className="ok-input" value={enhetId} onChange={e=>setEnhetId(e.target.value)} style={inp}>
            <option value="">— Ikke satt —</option>
            {enheter.map(e => <option key={e.id} value={e.id}>{e.navn}</option>)}
          </select>
        </div>

        <div style={{ display:'flex', flexDirection:'column', gap:5 }}>
          <label style={lbl}>Status</label>
          <select className="ok-input" value={status} onChange={e=>setStatus(e.target.value)} style={inp}>
            {Object.entries(TILTAK_STATUS).map(([k,v]) => <option key={k} value={k}>{v.label}</option>)}
          </select>
        </div>

        <div style={{ display:'flex', flexDirection:'column', gap:5 }}>
          <label style={lbl}>Prioritet</label>
          <select className="ok-input" value={prioritet} onChange={e=>setPrioritet(e.target.value)} style={inp}>
            {Object.entries(TILTAK_PRI).map(([k,v]) => <option key={k} value={k}>{v.label}</option>)}
          </select>
        </div>

        <div style={{ display:'flex', flexDirection:'column', gap:5 }}>
          <label style={lbl}>Kategori</label>
          <select className="ok-input" value={kategori} onChange={e=>setKategori(e.target.value)} style={inp}>
            {KATEGORI_VALG.map(k => <option key={k} value={k}>{k[0].toUpperCase()+k.slice(1)}</option>)}
          </select>
        </div>

        <div style={{ display:'flex', flexDirection:'column', gap:5 }}>
          <label style={lbl}>Frist</label>
          <input className="ok-input" type="date" value={frist} onChange={e=>setFrist(e.target.value)} style={inp} />
        </div>

        {/* Koble til avtale */}
        <div style={{ gridColumn:'1/-1', display:'flex', flexDirection:'column', gap:5 }}>
          <label style={lbl}>Koble til avtale (valgfritt)</label>
          <select className="ok-input" value={avtaleId} onChange={e=>setAvtaleId(e.target.value)} style={inp}>
            <option value="">— Ingen —</option>
            {avtaler.map(a => <option key={a.id} value={a.id}>{a.name}</option>)}
          </select>
        </div>

        <div style={{ gridColumn:'1/-1', display:'flex', flexDirection:'column', gap:5 }}>
          <label style={lbl}>Beskrivelse</label>
          <textarea className="ok-input" value={beskrivelse} onChange={e=>setBesk(e.target.value)}
            rows={3} style={{ ...inp, resize:'vertical', fontFamily:'inherit' }}
            placeholder="Utdyp hva som skal gjøres og hvorfor…" />
        </div>
      </div>

      <div style={{ display:'flex', gap:8 }}>
        <Button variant="primary" onClick={lagre} disabled={laster}>
          {laster ? 'Lagrer…' : (tiltak ? 'Lagre endringer' : 'Legg til tiltak')}
        </Button>
        <Button onClick={onAvbryt}>Avbryt</Button>
      </div>
    </div>
  );
}

// ── Tiltak-kort ───────────────────────────────────────────────

function TiltakKort({ t, onStatusBytte, onRediger, erValgt, onClick }) {
  const status   = TILTAK_STATUS[t.status] || TILTAK_STATUS.open;
  const pri      = TILTAK_PRI[t.prioritet] || TILTAK_PRI.normal;
  const dager    = dagerTilFrist(t.frist);
  const erForsen = dager !== null && dager < 0 && t.status !== 'done';
  const haster   = dager !== null && dager >= 0 && dager < 3 && t.status !== 'done';
  const farge    = t.ansvarlig?.roller?.farge || '#9aa3b8';
  const ini      = t.ansvarlig?.navn
    ? t.ansvarlig.navn.split(' ').filter(Boolean).map(n=>n[0]).slice(0,2).join('').toUpperCase()
    : null;

  return (
    <div onClick={onClick} style={{
      background: SK.pureWhite, borderRadius:10, cursor:'pointer',
      border:`1.5px solid ${erValgt ? SK.coral : erForsen ? '#f2545c40' : 'rgba(17,24,61,.08)'}`,
      borderLeft:`4px solid ${erForsen ? SK.coral : pri.dot}`,
      padding:'12px 14px',
      boxShadow: erValgt ? '0 4px 16px rgba(242,84,92,.10)' : '0 1px 3px rgba(17,24,61,.04)',
      transition:'all .12s',
    }}>
      <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start', gap:8 }}>
        <div style={{ flex:1, minWidth:0 }}>
          <div style={{ fontWeight:600, fontSize:12.5, lineHeight:1.35, marginBottom:4 }}>
            {erForsen && <span style={{ color:SK.coral, fontSize:10, fontWeight:700, marginRight:4 }}>⚑</span>}
            {t.tittel}
          </div>
          <div style={{ display:'flex', gap:8, flexWrap:'wrap', alignItems:'center' }}>
            {ini && (
              <div style={{ display:'flex', alignItems:'center', gap:4 }}>
                <div style={{ width:18, height:18, borderRadius:'50%', background:farge, color:'#fff',
                  display:'flex', alignItems:'center', justifyContent:'center', fontSize:8, fontWeight:700 }}>
                  {ini}
                </div>
                <span style={{ fontSize:11, color:SK.soft }}>{t.ansvarlig.navn.split(' ')[0]}</span>
              </div>
            )}
            {t.enhet?.navn && (
              <span style={{ fontSize:10.5, color:SK.soft }}>· {t.enhet.navn}</span>
            )}
            {t.avtale?.name && (
              <span style={{ fontSize:10.5, color:SK.soft, fontStyle:'italic' }}>· {t.avtale.name}</span>
            )}
          </div>
        </div>
        <div style={{ display:'flex', flexDirection:'column', alignItems:'flex-end', gap:4, flexShrink:0 }}>
          <span style={{ fontSize:10, fontWeight:600, padding:'2px 7px', borderRadius:99,
            background:status.bg, color:status.fg }}>
            {status.label}
          </span>
          {t.frist && (
            <span style={{ fontSize:10.5, fontWeight: (erForsen||haster) ? 700 : 400,
              color: erForsen ? SK.coral : haster ? '#8e5a05' : SK.soft }}>
              {erForsen ? `${Math.abs(dager)} dgr over` :
               dager === 0 ? 'i dag' :
               dager === 1 ? 'i morgen' :
               `${dager} dgr`}
            </span>
          )}
        </div>
      </div>

      {erValgt && (
        <div style={{ marginTop:12, paddingTop:10, borderTop:'1px solid rgba(17,24,61,.08)' }}>
          {t.beskrivelse && (
            <div style={{ fontSize:12, color:SK.soft, lineHeight:1.5, marginBottom:10 }}>{t.beskrivelse}</div>
          )}
          <div style={{ display:'flex', gap:6, flexWrap:'wrap' }}>
            <Button size="sm" variant="primary" onClick={e=>{e.stopPropagation();onRediger(t);}}>Rediger</Button>
            {Object.entries(TILTAK_STATUS)
              .filter(([k]) => k !== t.status)
              .map(([k,v]) => (
                <Button key={k} size="sm" onClick={e=>{e.stopPropagation();onStatusBytte(t.id,k);}}>
                  → {v.label}
                </Button>
              ))}
          </div>
        </div>
      )}
    </div>
  );
}

// ── Hoved­komponent ───────────────────────────────────────────

function TaskBoard({ go }) {
  const [tiltak,    setTiltak]    = React.useState([]);
  const [profiler,  setProfiler]  = React.useState([]);
  const [enheter,   setEnheter]   = React.useState([]);
  const [avtaler,   setAvtaler]   = React.useState([]);
  const [laster,    setLaster]    = React.useState(true);
  const [feil,      setFeil]      = React.useState(null);
  const [brukerId,  setBrukerId]  = React.useState(null);
  const [brukerNavn,setBrukerNavn]= React.useState('');
  const [innloggetProfil, setInnloggetProfil] = React.useState(null);
  const [sok,       setSok]       = React.useState('');
  const [pivot,     setPivot]     = React.useState('status');
  const [scope,     setScope]     = React.useState('alle');
  const [statusFilter, setStatusFilter] = React.useState('aktive');
  const [valgtId,   setValgtId]   = React.useState(null);
  const [visSkjema, setVisSkjema] = React.useState(false);
  const [redigerer, setRedigerer] = React.useState(null);

  React.useEffect(() => {
    window._sb.auth.getUser().then(({ data: { user } }) => {
      if (!user) return;
      setBrukerId(user.id);
      window._sb.from('profiles').select('id,navn,epost,roller(navn,farge,nokkel)').eq('id',user.id).single()
        .then(({ data }) => {
          setBrukerNavn(data?.navn || user.email);
          setInnloggetProfil(data);
        });
    });
    lastInn();
  }, []);

  async function lastInn() {
    setLaster(true); setFeil(null);
    try {
      const [t, { profiler, enheter, avtaler }] = await Promise.all([
        hentTiltak(),
        hentTiltakProfilerEnheter(),
      ]);
      setTiltak(t);
      setProfiler(profiler);
      setEnheter(enheter);
      setAvtaler(avtaler);
    } catch(e) { setFeil(e.message); } finally { setLaster(false); }
  }

  const filtrert = React.useMemo(() => {
    let t = tiltak.slice();
    if (scope === 'mine') t = t.filter(x => x.ansvarlig_id === brukerId);
    if (statusFilter === 'aktive') t = t.filter(x => x.status !== 'done' && x.status !== 'avvist');
    if (statusFilter === 'done')   t = t.filter(x => x.status === 'done');
    if (sok) {
      const q = sok.toLowerCase();
      t = t.filter(x => (x.tittel||'').toLowerCase().includes(q) ||
        (x.ansvarlig?.navn||'').toLowerCase().includes(q) ||
        (x.enhet?.navn||'').toLowerCase().includes(q));
    }
    return t;
  }, [tiltak, scope, statusFilter, sok, brukerId]);

  // Grupper etter pivot
  const grupper = React.useMemo(() => {
    const gMap = {};
    filtrert.forEach(t => {
      let key = 'Ingen';
      if (pivot === 'status')   key = TILTAK_STATUS[t.status]?.label || t.status;
      if (pivot === 'ansvarlig') key = t.ansvarlig?.navn || 'Ikke tildelt';
      if (pivot === 'enhet')    key = t.enhet?.navn || 'Ingen enhet';
      if (pivot === 'prioritet') key = TILTAK_PRI[t.prioritet]?.label || t.prioritet;
      if (!gMap[key]) gMap[key] = [];
      gMap[key].push(t);
    });
    return gMap;
  }, [filtrert, pivot]);

  const statusBytte = async (id, nyStatus) => {
    try {
      const oppdatert = await oppdaterTiltak(id, {
        status: nyStatus,
        fullfort_dato: nyStatus === 'done' ? new Date().toISOString().split('T')[0] : null,
      });
      setTiltak(prev => prev.map(t => t.id === oppdatert.id ? oppdatert : t));
      setValgtId(null);
    } catch(e) { alert(e.message); }
  };

  // KPI
  const totalt    = tiltak.length;
  const aktive    = tiltak.filter(t => t.status !== 'done' && t.status !== 'avvist').length;
  const forsinkede = tiltak.filter(t => { const d = dagerTilFrist(t.frist); return d !== null && d < 0 && t.status !== 'done'; }).length;
  const mine      = tiltak.filter(t => t.ansvarlig_id === brukerId && t.status !== 'done').length;

  if (visSkjema || redigerer) {
    return (
      <div className="ok-content__inner" style={{ maxWidth:800 }}>
        <Card padded={false}>
          <TiltakSkjema
            tiltak={redigerer}
            profiler={profiler} enheter={enheter} avtaler={avtaler}
            brukerId={brukerId} brukerNavn={brukerNavn}
            onLagret={res => {
              if (redigerer) setTiltak(prev => prev.map(t => t.id === res.id ? res : t));
              else setTiltak(prev => [res, ...prev]);
              setVisSkjema(false); setRedigerer(null);
            }}
            onAvbryt={() => { setVisSkjema(false); setRedigerer(null); }}
          />
        </Card>
      </div>
    );
  }

  return (
    <div className="ok-content__inner" style={{ maxWidth:1200 }}>
      {/* 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' }}>
            Oppfølging
          </div>
          <h1 style={{ margin:'6px 0 0', fontSize:28, fontWeight:600, letterSpacing:-0.02 }}>Tiltaksplan</h1>
          <div style={{ marginTop:4, color:SK.soft, fontSize:13 }}>
            {aktive} aktive · {forsinkede > 0 && <span style={{ color:SK.coral }}>⚑ {forsinkede} forsinkede · </span>}
            {mine} mine
          </div>
        </div>
        <div style={{ display:'flex', gap:8 }}>
          <EksportKnapp
            data={filtrert}
            kolonner={[
              {label:'Tittel', felt:'tittel'},
              {label:'Ansvarlig', felt:'ansvarlig.navn'},
              {label:'Enhet', felt:'enhet.navn'},
              {label:'Status', felt:'status'},
              {label:'Prioritet', felt:'prioritet'},
              {label:'Frist', felt:'frist'},
              {label:'Kategori', felt:'kategori'},
            ]}
            filnavn="tiltaksplan"
          />
          <Button size="sm" onClick={lastInn}>Oppdater</Button>
          <Button variant="primary" icon={I.plus} onClick={() => setVisSkjema(true)}>Nytt tiltak</Button>
        </div>
      </div>

      {/* KPI */}
      <div style={{ display:'grid', gridTemplateColumns:'repeat(4,1fr)', gap:14, marginBottom:18 }}>
        <Card padded><KPI label="Totalt" value={laster?'…':totalt} sub="registrerte tiltak" /></Card>
        <Card padded><KPI label="Aktive" value={laster?'…':aktive} sub="åpne og pågår" /></Card>
        <Card padded><KPI label="Forsinkede" value={laster?'…':forsinkede} sub="over frist" accent={forsinkede>0} /></Card>
        <Card padded><KPI label="Mine tiltak" value={laster?'…':mine} sub="der jeg er ansvarlig" /></Card>
      </div>

      {feil && (
        <div style={{ background:'#fcddde', border:'1px solid #f2545c', borderRadius:8,
          padding:'10px 14px', fontSize:13, color:'#8a1620', marginBottom:16 }}>{feil}</div>
      )}

      {/* Filter-rad */}
      <div style={{ display:'flex', gap:10, marginBottom:16, flexWrap:'wrap', alignItems:'center' }}>
        <input className="ok-input ok-input--search" placeholder="Søk tiltak, ansvarlig, enhet…"
          value={sok} onChange={e=>setSok(e.target.value)}
          style={{ maxWidth:280, padding:'7px 12px 7px 32px' }} />

        <div style={{ display:'flex', gap:4 }}>
          {[['alle','Alle'],['mine','Mine']].map(([k,l]) => (
            <button key={k} onClick={()=>setScope(k)} className="ok-btn ok-btn--sm" style={{
              background: scope===k ? SK.ink : 'transparent',
              color: scope===k ? '#fff' : SK.ink,
              borderColor: scope===k ? SK.ink : 'rgba(17,24,61,.15)',
            }}>{l}</button>
          ))}
        </div>

        <div style={{ display:'flex', gap:4 }}>
          {[['aktive','Aktive'],['done','Fullførte'],['alle','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={{ display:'flex', gap:4, marginLeft:'auto', alignItems:'center' }}>
          <span style={{ fontSize:11.5, color:SK.soft, marginRight:4 }}>Grupper etter:</span>
          {[['status','Status'],['ansvarlig','Ansvarlig'],['enhet','Enhet'],['prioritet','Prioritet']].map(([k,l]) => (
            <button key={k} onClick={()=>setPivot(k)} className="ok-btn ok-btn--sm" style={{
              background: pivot===k ? SK.ink : 'transparent',
              color: pivot===k ? '#fff' : SK.ink,
              borderColor: pivot===k ? SK.ink : 'rgba(17,24,61,.15)',
            }}>{l}</button>
          ))}
        </div>
      </div>

      {laster ? (
        <Card padded>
          <div style={{ padding:32, textAlign:'center', color:SK.soft, fontSize:13 }}>Laster tiltak…</div>
        </Card>
      ) : filtrert.length === 0 ? (
        <Card padded>
          <div style={{ padding:32, textAlign:'center', color:SK.soft, fontSize:13 }}>
            {tiltak.length === 0 ? 'Ingen tiltak registrert ennå. Klikk «Nytt tiltak» for å starte.' : 'Ingen tiltak matcher filteret.'}
          </div>
        </Card>
      ) : (
        <div style={{ display:'grid', gridTemplateColumns:'repeat(auto-fit, minmax(320px, 1fr))', gap:18, alignItems:'flex-start' }}>
          {Object.entries(grupper).map(([gruppe, items]) => {
            const erForsinket = items.some(t => { const d = dagerTilFrist(t.frist); return d !== null && d < 0 && t.status !== 'done'; });
            return (
              <div key={gruppe}>
                <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center',
                  marginBottom:10, paddingBottom:8,
                  borderBottom:`2px solid ${erForsinket ? SK.coral : SK.ink}` }}>
                  <div style={{ fontSize:13, fontWeight:600 }}>{gruppe}</div>
                  <span style={{ fontSize:11.5, color:SK.soft, background:SK.iceBlueLight,
                    padding:'2px 8px', borderRadius:99 }}>{items.length}</span>
                </div>
                <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
                  {items.map(t => (
                    <TiltakKort key={t.id} t={t}
                      erValgt={valgtId === t.id}
                      onClick={() => setValgtId(valgtId === t.id ? null : t.id)}
                      onStatusBytte={statusBytte}
                      onRediger={t => { setRedigerer(t); setValgtId(null); }}
                    />
                  ))}
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { TaskBoard });
