// budsjett-screens-3.jsx — Lønnsbudsjett + Deltakermatrise + CSV-import/eksport
// Eksporterer: BudLonnsbudsjett, BudDeltakerMatrise, BudMappingCSV

// ════════════════════════════════════════════════════════════
// LØNNSBUDSJETT
// ════════════════════════════════════════════════════════════
function BudLonnsbudsjett({ data, versjonId, enhById, laast, onEndret }) {
  const [filterAvd, setFilterAvd] = React.useState('alle');
  const [rediger, setRediger]     = React.useState(null);
  const rader = data.lonn.filter(l => l.versjon_id===versjonId).filter(l => filterAvd==='alle'||l.avdeling_id===filterAvd);
  const avdMed = [...new Set(data.lonn.filter(l=>l.versjon_id===versjonId).map(l=>l.avdeling_id))];

  // Sum
  let sumGrunn=0, sumSosial=0;
  rader.forEach(l => { const b=window.budLonnAarlig(l); sumGrunn+=b.grunnlonn; sumSosial+=b.sosial; });

  return (
    <div>
      <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:14, marginBottom:18 }}>
        <Card padded><KPI label="Grunnlønn (år)" value={window.budFmtKr(sumGrunn)} sub="kr" /></Card>
        <Card padded><KPI label="Sosiale kostnader" value={window.budFmtKr(sumSosial)} sub="AGA + pensjon + sosialt" /></Card>
        <Card padded><KPI label="Total lønnskostnad" value={window.budFmtKr(sumGrunn+sumSosial)} sub="kr" /></Card>
      </div>
      <div style={{ display:'flex', justifyContent:'space-between', marginBottom:14, gap:12, flexWrap:'wrap' }}>
        <select className="ok-input" value={filterAvd} onChange={e=>setFilterAvd(e.target.value)} style={{ maxWidth:240, padding:'7px 10px', fontSize:13 }}>
          <option value="alle">Alle avdelinger</option>
          {data.enheter.filter(e=>avdMed.includes(e.id)).map(e=><option key={e.id} value={e.id}>{e.avd_nr} {e.navn}</option>)}
        </select>
        {!laast && <Button variant="primary" size="sm" icon={I.plus} onClick={()=>setRediger({ ny:true })}>Ny lønnslinje</Button>}
      </div>
      <Card padded={false}>
        <table className="ok-table" style={{ width:'100%' }}>
          <thead><tr>
            <th style={{ paddingLeft:20 }}>Stilling</th><th>Avdeling</th><th>Type</th>
            <th style={{ textAlign:'right' }}>Antall × %</th><th style={{ textAlign:'right' }}>Mnd.lønn</th>
            <th style={{ textAlign:'right' }}>Mnd</th><th style={{ textAlign:'right' }}>Sosialt</th>
            <th style={{ textAlign:'right', paddingRight:laast?20:8 }}>Årlig total</th>{!laast && <th style={{ width:80 }}></th>}
          </tr></thead>
          <tbody>
            {rader.length===0 && <tr><td colSpan={9} style={{ padding:24, textAlign:'center', color:SK.soft }}>Ingen lønnslinjer ennå.</td></tr>}
            {rader.map(l => { const b=window.budLonnAarlig(l); const mnd=Math.max(0,(l.mnd_til||12)-(l.mnd_fra||1)+1);
              return (<tr key={l.id}>
                <td style={{ paddingLeft:20 }}><div style={{ fontWeight:500 }}>{l.stilling}</div>{l.navn && <div style={{ fontSize:11.5, color:SK.soft }}>{l.navn}</div>}</td>
                <td style={{ fontSize:12.5 }}>{enhById[l.avdeling_id]?.navn}</td>
                <td><span style={{ fontSize:11, padding:'2px 8px', borderRadius:99, background:SK.iceBlueLight }}>{l.type}</span></td>
                <td style={{ textAlign:'right' }}>{l.antall} × {l.stillingspct}%</td>
                <td style={{ textAlign:'right' }}>{window.budFmtKr(l.manedslonn)}</td>
                <td style={{ textAlign:'right', color:SK.soft }}>{mnd}</td>
                <td style={{ textAlign:'right', color:SK.soft }}>{(Number(l.aga_pct||0)+Number(l.pensjon_pct||0)+Number(l.sosial_pct||0)).toFixed(1)}%</td>
                <td style={{ textAlign:'right', paddingRight:laast?20:8, fontWeight:600 }}>{window.budFmtKr(b.total)}</td>
                {!laast && <td><div style={{ display:'flex', gap:4 }}>
                  <button onClick={()=>setRediger(l)} style={budIkonKnapp}>✎</button>
                  <button onClick={async()=>{ if(confirm('Slette lønnslinjen?')){ await window.budDB.slett('bud_lonn', l.id); onEndret(); }}} style={budIkonKnapp}>🗑</button>
                </div></td>}
              </tr>); })}
          </tbody>
        </table>
      </Card>
      {rediger && <BudLonnModal rad={rediger} data={data} versjonId={versjonId} onLukk={()=>setRediger(null)} onLagret={()=>{ setRediger(null); onEndret(); }} />}
    </div>
  );
}

function BudLonnModal({ rad, data, versjonId, onLukk, onLagret }) {
  const ny = rad.ny;
  const [f, setF] = React.useState({
    avdeling_id: rad.avdeling_id||'', stilling: rad.stilling||'', navn: rad.navn||'',
    type: rad.type||'fast', antall: rad.antall??1, stillingspct: rad.stillingspct??100,
    manedslonn: rad.manedslonn??'', mnd_fra: rad.mnd_fra??1, mnd_til: rad.mnd_til??12,
    konto: rad.konto??5000, aga_pct: rad.aga_pct??14.1, pensjon_pct: rad.pensjon_pct??2.0, sosial_pct: rad.sosial_pct??0,
  });
  const [sosiale, setSosiale] = React.useState(Array.isArray(rad.sosiale_poster)?rad.sosiale_poster:[]);
  const [feil, setFeil] = React.useState(null);
  const [lagrer, setLagrer] = React.useState(false);
  const set = (k,v) => setF(s=>({...s,[k]:v}));
  const forhaand = window.budLonnAarlig({ ...f, sosiale_poster: sosiale });
  const lonnKontoer = data.kontoplan.filter(k => k.klasse===5);

  const lagre = async () => {
    if (!f.avdeling_id || !f.stilling.trim()) { setFeil('Avdeling og stilling er påkrevd.'); return; }
    setLagrer(true); setFeil(null);
    try {
      const felt = { ...f, antall:Number(f.antall), stillingspct:Number(f.stillingspct), manedslonn:Math.round(Number(f.manedslonn)||0),
        mnd_fra:Number(f.mnd_fra), mnd_til:Number(f.mnd_til), konto:Number(f.konto),
        aga_pct:Number(f.aga_pct), pensjon_pct:Number(f.pensjon_pct), sosial_pct:Number(f.sosial_pct),
        sosiale_poster: sosiale.filter(p=>p.navn && (p.pct||p.belop)) };
      if (ny) await window.budDB.lagre('bud_lonn', { versjon_id:versjonId, ...felt });
      else await window.budDB.oppdater('bud_lonn', rad.id, felt);
      onLagret();
    } catch(e){ setFeil(e.message); setLagrer(false); }
  };
  return (
    <BudModal tittel={ny?'Ny lønnslinje':'Rediger lønnslinje'} onLukk={onLukk} bred>
      {feil && <div style={budFeil}>{feil}</div>}
      <div style={{ display:'grid', gridTemplateColumns:'1fr 1fr', gap:'12px 16px' }}>
        <div><label style={budLBL}>Avdeling *</label>
          <select className="ok-input" value={f.avdeling_id} onChange={e=>set('avdeling_id',e.target.value)} style={budINP}>
            <option value="">— Velg —</option>{data.enheter.slice().sort((a,b)=>(a.avd_nr||'').localeCompare(b.avd_nr||'')).map(e=><option key={e.id} value={e.id}>{e.avd_nr} {e.navn}</option>)}
          </select></div>
        <div><label style={budLBL}>Type</label>
          <select className="ok-input" value={f.type} onChange={e=>set('type',e.target.value)} style={budINP}>
            {['fast','deltaker','vikar','midlertidig','laerling'].map(t=><option key={t} value={t}>{t}</option>)}
          </select></div>
        <div><label style={budLBL}>Stilling *</label><input className="ok-input" value={f.stilling} onChange={e=>set('stilling',e.target.value)} style={budINP} placeholder="f.eks. Jobbspesialist" /></div>
        <div><label style={budLBL}>Navn (valgfritt)</label><input className="ok-input" value={f.navn} onChange={e=>set('navn',e.target.value)} style={budINP} placeholder="Vakant hvis tom" /></div>
        <div><label style={budLBL}>Antall stillinger</label><input className="ok-input" type="number" value={f.antall} onChange={e=>set('antall',e.target.value)} style={budINP} /></div>
        <div><label style={budLBL}>Stillingsprosent</label><input className="ok-input" type="number" value={f.stillingspct} onChange={e=>set('stillingspct',e.target.value)} style={budINP} /></div>
        <div><label style={budLBL}>Månedslønn (100 %)</label><input className="ok-input" type="number" value={f.manedslonn} onChange={e=>set('manedslonn',e.target.value)} style={budINP} /></div>
        <div><label style={budLBL}>Lønnskonto</label>
          <select className="ok-input" value={f.konto} onChange={e=>set('konto',e.target.value)} style={budINP}>
            {lonnKontoer.map(k=><option key={k.konto} value={k.konto}>{k.konto} {k.navn}</option>)}
          </select></div>
        <div><label style={budLBL}>Fra måned</label><input className="ok-input" type="number" min="1" max="12" value={f.mnd_fra} onChange={e=>set('mnd_fra',e.target.value)} style={budINP} /></div>
        <div><label style={budLBL}>Til måned</label><input className="ok-input" type="number" min="1" max="12" value={f.mnd_til} onChange={e=>set('mnd_til',e.target.value)} style={budINP} /></div>
        <div><label style={budLBL}>AGA %</label><input className="ok-input" type="number" step="0.1" value={f.aga_pct} onChange={e=>set('aga_pct',e.target.value)} style={budINP} /></div>
        <div><label style={budLBL}>Pensjon %</label><input className="ok-input" type="number" step="0.1" value={f.pensjon_pct} onChange={e=>set('pensjon_pct',e.target.value)} style={budINP} /></div>
      </div>
      <div style={{ marginTop:16 }}>
        <label style={budLBL}>Flere sosiale kostnader (valgfritt)</label>
        <div style={{ display:'flex', flexDirection:'column', gap:6 }}>
          {sosiale.map((p,i)=>(
            <div key={i} style={{ display:'flex', gap:8, alignItems:'center' }}>
              <input className="ok-input" value={p.navn||''} onChange={e=>setSosiale(s=>s.map((x,j)=>j===i?{...x,navn:e.target.value}:x))} style={{ ...budINP, flex:1 }} placeholder="f.eks. OTP, forsikring, fagforeningstrekk" />
              <input className="ok-input" type="number" step="0.1" value={p.pct??''} onChange={e=>setSosiale(s=>s.map((x,j)=>j===i?{...x,pct:e.target.value,belop:''}:x))} style={{ ...budINP, width:70 }} placeholder="%" />
              <span style={{ fontSize:11, color:SK.soft }}>eller</span>
              <input className="ok-input" type="number" value={p.belop??''} onChange={e=>setSosiale(s=>s.map((x,j)=>j===i?{...x,belop:e.target.value,pct:''}:x))} style={{ ...budINP, width:90 }} placeholder="kr/år" />
              <button onClick={()=>setSosiale(s=>s.filter((_,j)=>j!==i))} style={budIkonKnapp}>🗑</button>
            </div>
          ))}
          <button onClick={()=>setSosiale(s=>[...s,{navn:'',pct:'',belop:''}])} style={{ ...budIkonKnapp, width:'auto', padding:'6px 12px', fontSize:12 }}>+ Legg til sosial kostnad</button>
        </div>
        <div style={{ fontSize:11, color:SK.soft, marginTop:6 }}>Angi enten prosent av grunnlønn eller fast kronebeløp per post.</div>
      </div>
      <div style={{ marginTop:14, padding:'12px 16px', background:SK.iceBlueLight, borderRadius:8, fontSize:12.5 }}>
        Beregnet årlig: <b>{window.budFmtKrFull(forhaand.grunnlonn)}</b> grunnlønn + <b>{window.budFmtKrFull(forhaand.sosial)}</b> sosialt = <b style={{ color:SK.ink }}>{window.budFmtKrFull(forhaand.total)}</b>
      </div>
      <div style={{ display:'flex', gap:10, marginTop:18 }}>
        <Button variant="primary" onClick={lagre} disabled={lagrer}>{lagrer?'Lagrer…':'Lagre'}</Button>
        <Button onClick={onLukk}>Avbryt</Button>
      </div>
    </BudModal>
  );
}

// ════════════════════════════════════════════════════════════
// DELTAKERMATRISE — antall deltakere per avdeling × kategori
// ════════════════════════════════════════════════════════════
function BudDeltakerMatrise({ data, versjonId, enhById, laast, onEndret }) {
  const kategorier = ['VTA','AFT','IPS','annet'];
  const [lagrer, setLagrer] = React.useState(null);
  // Bygg lookup: avd|kategori -> rad
  const matrise = {};
  data.deltakere.filter(d=>d.versjon_id===versjonId).forEach(d => { matrise[d.avdeling_id+'|'+d.kategori]=d; });
  // Avdelinger som er relevante (drift/entreprise/avdeling)
  const avd = data.enheter.filter(e=>['avdeling','entreprise'].includes(e.type)).sort((a,b)=>(a.avd_nr||'').localeCompare(b.avd_nr||''));

  const settAntall = async (avdId, kategori, verdi) => {
    const key = avdId+'|'+kategori; setLagrer(key);
    try {
      const eks = matrise[key];
      if (eks) await window.budDB.oppdater('bud_deltaker_matrise', eks.id, { antall:Number(verdi)||0, manuelt:true });
      else await window.budDB.lagre('bud_deltaker_matrise', { versjon_id:versjonId, avdeling_id:avdId, kategori, antall:Number(verdi)||0, manuelt:true });
      await onEndret();
    } catch(e){ alert('Feil: '+e.message); }
    setLagrer(null);
  };

  // Kolonnesum
  const kolSum = {}; kategorier.forEach(k=>kolSum[k]=0);
  let totalSum = 0;
  avd.forEach(e => kategorier.forEach(k => { const v=Number(matrise[e.id+'|'+k]?.antall||0); kolSum[k]+=v; totalSum+=v; }));

  return (
    <div>
      <div style={{ background:SK.iceBlueLight, borderRadius:10, padding:'14px 18px', marginBottom:16, fontSize:12.5, color:SK.ink, lineHeight:1.6 }}>
        <b>Deltakermatrise.</b> Antall deltakere per avdeling og kategori. Settes manuelt nå, og kan kobles
        til ekstern kilde senere. Matrisen brukes som <b>fordelingsnøkkel</b> (driver «deltakere») i kostnadsfordelingen —
        avdelinger med flere deltakere får større andel av felleskostnader.
      </div>
      <Card padded={false}>
        <table className="ok-table" style={{ width:'100%' }}>
          <thead><tr><th style={{ paddingLeft:20 }}>Avd.nr</th><th>Avdeling</th>
            {kategorier.map(k=><th key={k} style={{ textAlign:'right' }}>{k}</th>)}
            <th style={{ textAlign:'right', paddingRight:20 }}>Sum</th></tr></thead>
          <tbody>
            {avd.map(e => { let rsum=0;
              return (<tr key={e.id}>
                <td style={{ paddingLeft:20, color:SK.soft }}>{e.avd_nr}</td>
                <td style={{ fontWeight:500 }}>{e.navn}</td>
                {kategorier.map(k => { const v=Number(matrise[e.id+'|'+k]?.antall||0); rsum+=v; const key=e.id+'|'+k;
                  return (<td key={k} style={{ textAlign:'right' }}>
                    {laast ? (v||'—') : (
                      <input type="number" defaultValue={v||''} disabled={lagrer===key}
                        onBlur={ev=>{ if(ev.target.value!==String(v)) settAntall(e.id,k,ev.target.value); }}
                        style={{ width:64, padding:'4px 6px', fontSize:12.5, textAlign:'right', border:'1px solid rgba(17,24,61,.12)', borderRadius:6 }} placeholder="0" />
                    )}
                  </td>); })}
                <td style={{ textAlign:'right', paddingRight:20, fontWeight:600 }}>{rsum||'—'}</td>
              </tr>); })}
            <tr style={{ fontWeight:700, background:SK.iceBlueLight }}>
              <td style={{ paddingLeft:20 }} colSpan={2}>Sum alle</td>
              {kategorier.map(k=><td key={k} style={{ textAlign:'right' }}>{kolSum[k]||'—'}</td>)}
              <td style={{ textAlign:'right', paddingRight:20 }}>{totalSum||'—'}</td>
            </tr>
          </tbody>
        </table>
      </Card>
    </div>
  );
}

Object.assign(window, { BudLonnsbudsjett, BudDeltakerMatrise });
