/* ui/werkverdeling.jsx — v7.20
 *
 * Werkverdeling: elk dossier gaat naar een outsourcer (Srijith, Rajeshwaran,
 * …) of naar Enerveco zelf, met een deadline voor het opleveren.
 *
 *   window.ToewijzenKeuze    — deadline + één klik op de persoon = bewaard.
 *                              Ook inline bruikbaar (vangnet).
 *   window.ToewijzenVenster  — dezelfde keuze als zwevend venster; de eerste
 *                              stap na elke goedkeuring.
 *   window.WerkverdelingTabel— overzicht van alle lopende, toegewezen
 *                              dossiers: wie, deadline, verstuurd, opgeleverd.
 *   window.WerkverdelingPopup— dat overzicht één keer per sessie bij het
 *                              openen van het portaal (beheerder én Mustapha).
 *   window.ToewijzingBadge   — knopje op de projectfiche: wie + deadline,
 *                              klik om te wijzigen.
 *   window.OutsourcersBeheer — lijst van outsourcers (naam + e-mail) in de
 *                              instellingen.
 *
 * Server: /api/outsourcers, /api/projects/:id/toewijzing, /api/werkverdeling.
 */
(function () {
  const K = { tekst:'#1a202c', zacht:'#718096', licht:'#a0aec0', rand:'#e2e8f0',
              groen:'#2b4f26', groenZacht:'#e9f0e7', rood:'#991b1b', roodZacht:'#fee2e2',
              oker:'#92400e', okerZacht:'#fef3c7', paars:'#5b21b6', paarsZacht:'#ede9fe',
              blauw:'#1e40af', blauwZacht:'#eff6ff' };

  const haal = (url) => fetch(url, { credentials:'include' }).then(r => r.json());
  const zend = (url, methode, body) => fetch(url, {
    method: methode, credentials:'include', headers:{'Content-Type':'application/json'},
    body: JSON.stringify(body || {}),
  }).then(r => r.json());

  const vandaagPlus = (dagen) => {
    const d = new Date(); d.setDate(d.getDate() + dagen);
    return d.getFullYear() + '-' + String(d.getMonth() + 1).padStart(2, '0') + '-' + String(d.getDate()).padStart(2, '0');
  };
  const datum = (iso) => {
    if (!iso) return '';
    const d = new Date(String(iso).slice(0, 10) + 'T12:00:00');
    return isNaN(d) ? String(iso) : d.toLocaleDateString('nl-BE', { day:'2-digit', month:'2-digit', year:'numeric' });
  };
  const dagenTot = (iso) => {
    if (!iso) return null;
    const nu = new Date(); nu.setHours(12, 0, 0, 0);
    const d = new Date(String(iso).slice(0, 10) + 'T12:00:00');
    return Math.round((d - nu) / 86400000);
  };

  const KEUZES_DEADLINE = [
    { label:'+1 week',  dagen:7 },
    { label:'+2 weken', dagen:14 },
    { label:'+3 weken', dagen:21 },
    { label:'+1 maand', dagen:30 },
  ];

  /* ── De keuze zelf ─────────────────────────────────────────────────────── */
  function ToewijzenKeuze({ project, onGekozen, compact }) {
    const [personen, setPersonen] = React.useState(null);
    const [huidig, setHuidig] = React.useState(null);
    const [deadline, setDeadline] = React.useState(vandaagPlus(14));
    const [bezig, setBezig] = React.useState(null);
    const [err, setErr] = React.useState('');

    React.useEffect(() => {
      Promise.all([
        haal('/api/outsourcers').catch(() => []),
        haal('/api/projects/' + project.id + '/toewijzing').catch(() => null),
      ]).then(([outs, tw]) => {
        setPersonen((Array.isArray(outs) ? outs : []).concat([{ key:'enerveco', naam:'Enerveco', email:null }]));
        if (tw && !tw.error) {
          setHuidig(tw.toegewezen_aan || null);
          if (tw.deadline_outsourcing) setDeadline(tw.deadline_outsourcing);
        }
      });
    }, [project.id]);

    const kies = async (key) => {
      setBezig(key); setErr('');
      try {
        const r = await zend('/api/projects/' + project.id + '/toewijzing', 'PUT',
          { toegewezen_aan: key, deadline: deadline || null });
        if (!r || !r.ok) throw new Error((r && r.error) || 'Bewaren mislukt');
        setHuidig(key);
        if (onGekozen) onGekozen(r);
      } catch (e) { setErr(e.message); }
      setBezig(null);
    };

    if (!personen) return <div style={{fontSize:12,color:K.zacht,padding:'6px 0'}}>⏳ Laden…</div>;

    return (
      <div>
        <div style={{display:'flex',alignItems:'center',gap:8,flexWrap:'wrap',marginBottom: compact ? 8 : 14}}>
          <span style={{fontSize:12,fontWeight:600,color:K.zacht}}>⏰ Deadline</span>
          <input type="date" value={deadline} onChange={e=>setDeadline(e.target.value)}
            style={{padding:'5px 8px',border:'1.5px solid '+K.rand,borderRadius:6,fontSize:13}} />
          {KEUZES_DEADLINE.map(k => {
            const waarde = vandaagPlus(k.dagen);
            return (
              <button key={k.label} type="button" onClick={()=>setDeadline(waarde)}
                style={{padding:'3px 9px',borderRadius:12,fontSize:11,cursor:'pointer',
                        border:'1px solid '+(deadline === waarde ? K.groen : K.rand),
                        background: deadline === waarde ? K.groenZacht : '#fff',
                        color: deadline === waarde ? K.groen : K.zacht}}>
                {k.label}
              </button>
            );
          })}
        </div>
        <div style={{display:'flex',gap:8,flexWrap:'wrap'}}>
          {personen.map(pp => {
            const isHuidig = huidig === pp.key;
            return (
              <button key={pp.key} type="button" disabled={!!bezig} onClick={()=>kies(pp.key)}
                title={pp.email ? pp.email : 'Enerveco doet dit dossier zelf'}
                style={{flex: compact ? '0 0 auto' : '1 1 140px', textAlign:'left', cursor: bezig ? 'wait' : 'pointer',
                        padding: compact ? '7px 12px' : '12px 14px', borderRadius:8,
                        border:'2px solid ' + (isHuidig ? K.groen : K.rand),
                        background: isHuidig ? K.groenZacht : '#fff'}}>
                <div style={{fontSize: compact ? 13 : 15, fontWeight:700, color:K.tekst}}>
                  {bezig === pp.key ? '⏳ ' : (isHuidig ? '✓ ' : '')}{pp.naam}
                </div>
                {!compact && (
                  <div style={{fontSize:11,color:K.zacht,marginTop:2}}>
                    {pp.email || 'in eigen huis'}
                  </div>
                )}
              </button>
            );
          })}
        </div>
        {err && <div style={{marginTop:8,fontSize:12,color:K.rood}}>{err}</div>}
        {!compact && (
          <div style={{marginTop:10,fontSize:11,color:K.licht}}>
            Eén klik op de persoon bewaart de toewijzing met deze deadline. De deadline gaat mee in de mail naar outsourcing.
          </div>
        )}
      </div>
    );
  }

  /* ── Als zwevend venster ───────────────────────────────────────────────── */
  function ToewijzenVenster({ project, onClose }) {
    const [klaar, setKlaar] = React.useState(null);
    return (
      <div style={{position:'fixed',inset:0,background:'rgba(0,0,0,.5)',zIndex:7100,
                   display:'flex',alignItems:'center',justifyContent:'center',padding:16}}>
        <div style={{background:'#fff',borderRadius:12,width:'min(560px,100%)',maxHeight:'90vh',overflow:'auto',
                     padding:22,boxShadow:'0 20px 60px rgba(0,0,0,.4)'}}>
          <div style={{fontSize:17,fontWeight:700,color:K.tekst}}>👷 Voor wie is dit dossier?</div>
          <div style={{fontSize:12,color:K.zacht,marginTop:3,marginBottom:16}}>
            {project.dossier_nr ? <>Dossier <b>{project.dossier_nr}</b> · </> : null}{project.werfadres || ''}
          </div>
          {klaar ? (
            <div style={{padding:'14px 16px',background:K.groenZacht,color:K.groen,borderRadius:8,fontSize:14,fontWeight:600}}>
              ✓ Toegewezen aan {klaar.persoon ? klaar.persoon.naam : '—'}
              {klaar.deadline_outsourcing ? ' · deadline ' + datum(klaar.deadline_outsourcing) : ''}
            </div>
          ) : (
            <ToewijzenKeuze project={project}
              onGekozen={(r) => { setKlaar(r); setTimeout(onClose, 900); }} />
          )}
          <div style={{display:'flex',justifyContent:'flex-end',marginTop:16}}>
            <button type="button" onClick={onClose}
              style={{padding:'7px 14px',background:'#fff',border:'1px solid '+K.rand,borderRadius:6,fontSize:13,cursor:'pointer'}}>
              {klaar ? 'Verder' : 'Later'}
            </button>
          </div>
        </div>
      </div>
    );
  }

  /* ── Overzicht ─────────────────────────────────────────────────────────── */
  function standVan(r, isEnerveco) {
    switch (r.status) {
      case 'outsourcing_nakijken':  return { tekst:'📥 Opgeleverd — nakijken', kleur:K.paars, bg:K.paarsZacht };
      case 'outsourcing_nagekeken': return { tekst:'✓ Nagekeken', kleur:K.groen, bg:K.groenZacht };
      case 'opgestart_outsourcing':
      case 'opgestart_enerveco':    return { tekst:'⏳ Bezig', kleur:K.blauw, bg:K.blauwZacht };
      default:
        if (isEnerveco) return { tekst:'Nog te starten', kleur:K.zacht, bg:'#f7fafc' };
        /* oudere dossiers: verstuurd vóór de status automatisch meeschoof */
        if (r.outsourcing_verstuurd_op) return { tekst:'⏳ Bezig', kleur:K.blauw, bg:K.blauwZacht };
        return { tekst:'📨 Nog niet verstuurd', kleur:K.oker, bg:K.okerZacht };
    }
  }

  function WerkverdelingTabel({ onAantal }) {
    const [data, setData] = React.useState(null);
    const [err, setErr] = React.useState('');
    React.useEffect(() => {
      haal('/api/werkverdeling')
        .then(d => {
          if (d && d.error) throw new Error(d.error);
          setData(d);
          if (onAantal) onAantal(((d && d.rijen) || []).length);
        })
        .catch(e => setErr(e.message));
    }, []);

    if (err) return <div style={{fontSize:13,color:K.rood}}>Laden mislukt: {err}</div>;
    if (!data) return <div style={{fontSize:13,color:K.zacht}}>⏳ Laden…</div>;
    if (!data.rijen.length) {
      return <div style={{fontSize:13,color:K.zacht}}>Nog geen toegewezen dossiers. Bij elke goedkeuring vraagt het portaal voor wie het dossier is.</div>;
    }

    const groepen = {};
    data.rijen.forEach(r => { (groepen[r.toegewezen_aan] = groepen[r.toegewezen_aan] || []).push(r); });
    const volgorde = (data.volgorde || []).filter(k => groepen[k])
      .concat(Object.keys(groepen).filter(k => !(data.volgorde || []).includes(k)));

    const th = { textAlign:'left', padding:'6px 10px', fontSize:11, fontWeight:600, color:K.zacht,
                 textTransform:'uppercase', borderBottom:'1px solid '+K.rand, whiteSpace:'nowrap' };
    const td = { padding:'8px 10px', fontSize:13, borderBottom:'1px solid #f1f5f9', verticalAlign:'top' };

    return (
      <div>
        {volgorde.map(key => {
          const rijen = groepen[key];
          const isEnerveco = key === 'enerveco';
          return (
            <div key={key} style={{marginBottom:18}}>
              <div style={{fontSize:14,fontWeight:700,color:K.tekst,marginBottom:6}}>
                {isEnerveco ? '🏢' : '👷'} {(data.personen && data.personen[key]) || key}
                <span style={{fontWeight:400,color:K.zacht,fontSize:12}}> · {rijen.length} dossier{rijen.length === 1 ? '' : 's'}</span>
              </div>
              <div style={{overflowX:'auto'}}>
                <table style={{width:'100%',borderCollapse:'collapse',minWidth:560}}>
                  <thead>
                    <tr>
                      <th style={th}>Dossier</th>
                      <th style={th}>Werfadres</th>
                      <th style={th}>Deadline</th>
                      {!isEnerveco && <th style={th}>Verstuurd</th>}
                      <th style={th}>Stand</th>
                    </tr>
                  </thead>
                  <tbody>
                    {rijen.map(r => {
                      const stand = standVan(r, isEnerveco);
                      const opgeleverd = ['outsourcing_nakijken', 'outsourcing_nagekeken'].includes(r.status);
                      const dt = dagenTot(r.deadline_outsourcing);
                      let dlBadge = null;
                      if (dt !== null && !opgeleverd) {
                        if (dt < 0) dlBadge = { t: Math.abs(dt) + ' d te laat', k: K.rood, b: K.roodZacht };
                        else if (dt === 0) dlBadge = { t: 'vandaag', k: K.rood, b: K.roodZacht };
                        else if (dt <= 3) dlBadge = { t: 'nog ' + dt + ' d', k: K.oker, b: K.okerZacht };
                      }
                      return (
                        <tr key={r.id} style={{cursor:'pointer'}}
                          onClick={() => { window.location.href = '/?open_project=' + r.id; }}
                          title="Open het dossier">
                          <td style={{...td, fontWeight:700, whiteSpace:'nowrap'}}>{r.dossier_nr}</td>
                          <td style={td}>
                            {r.werfadres}
                            {r.bouwheer ? <div style={{fontSize:11,color:K.zacht}}>{r.bouwheer}</div> : null}
                          </td>
                          <td style={{...td, whiteSpace:'nowrap'}}>
                            {r.deadline_outsourcing ? datum(r.deadline_outsourcing) : <span style={{color:K.licht}}>—</span>}
                            {dlBadge && (
                              <span style={{marginLeft:6,fontSize:10,fontWeight:700,padding:'1px 6px',borderRadius:8,
                                            color:dlBadge.k,background:dlBadge.b}}>{dlBadge.t}</span>
                            )}
                          </td>
                          {!isEnerveco && (
                            <td style={{...td, whiteSpace:'nowrap', color: r.outsourcing_verstuurd_op ? K.tekst : K.licht}}>
                              {r.outsourcing_verstuurd_op ? datum(r.outsourcing_verstuurd_op) : '—'}
                            </td>
                          )}
                          <td style={td}>
                            <span style={{fontSize:12,fontWeight:600,padding:'2px 8px',borderRadius:10,
                                          color:stand.kleur,background:stand.bg,whiteSpace:'nowrap'}}>{stand.tekst}</span>
                            {opgeleverd && r.outsourcing_opgeleverd_op && (
                              <div style={{fontSize:11,color:K.zacht,marginTop:3}}>op {datum(r.outsourcing_opgeleverd_op)}</div>
                            )}
                          </td>
                        </tr>
                      );
                    })}
                  </tbody>
                </table>
              </div>
            </div>
          );
        })}
      </div>
    );
  }

  /* ── Eén keer per sessie bij het openen van het portaal ────────────────── */
  function WerkverdelingPopup() {
    const [open, setOpen] = React.useState(false);
    React.useEffect(() => {
      let getoond = false;
      try { getoond = sessionStorage.getItem('werkverdeling-getoond') === '1'; } catch (e) {}
      if (getoond) return;
      /* kwam men via een knop naar een dossier (?open_project=…), dan niet storen */
      if (new URLSearchParams(window.location.search).get('open_project')) return;
      haal('/api/werkverdeling').then(d => {
        if (d && Array.isArray(d.rijen) && d.rijen.length) {
          setOpen(true);
          try { sessionStorage.setItem('werkverdeling-getoond', '1'); } catch (e) {}
        }
      }).catch(() => {});
    }, []);
    if (!open) return null;
    return (
      <div style={{position:'fixed',inset:0,background:'rgba(0,0,0,.45)',zIndex:6300,
                   display:'flex',alignItems:'center',justifyContent:'center',padding:16}}>
        <div style={{background:'#fff',borderRadius:12,width:'min(860px,100%)',maxHeight:'88vh',overflow:'auto',
                     padding:22,boxShadow:'0 20px 60px rgba(0,0,0,.4)'}}>
          <div style={{display:'flex',alignItems:'center',justifyContent:'space-between',marginBottom:4}}>
            <div style={{fontSize:16,fontWeight:700}}>📊 Werkverdeling — lopende dossiers</div>
            <button type="button" onClick={() => setOpen(false)}
              style={{padding:'6px 14px',background:'#fff',border:'1px solid '+K.rand,borderRadius:6,fontSize:12,cursor:'pointer'}}>
              Sluiten
            </button>
          </div>
          <div style={{fontSize:12,color:K.zacht,marginBottom:14}}>
            Wie heeft welk dossier, tegen wanneer, en wat werd al opgeleverd om na te kijken. Klik op een dossier om het te openen.
          </div>
          <WerkverdelingTabel />
        </div>
      </div>
    );
  }

  /* ── Knopje op de projectfiche ─────────────────────────────────────────── */
  function ToewijzingBadge({ project }) {
    const [tw, setTw] = React.useState(null);
    const [open, setOpen] = React.useState(false);
    const laad = () => { haal('/api/projects/' + project.id + '/toewijzing').then(d => { if (d && !d.error) setTw(d); }).catch(() => {}); };
    React.useEffect(laad, [project.id]);
    const dt = tw ? dagenTot(tw.deadline_outsourcing) : null;
    const laat = dt !== null && dt < 0 && !['outsourcing_nakijken', 'outsourcing_nagekeken'].includes(tw && tw.status);
    return (
      <>
        <button type="button" onClick={() => setOpen(true)}
          title="Voor wie is dit dossier, en tegen wanneer? Klik om te wijzigen."
          style={{padding:'6px 12px',borderRadius:6,fontSize:13,fontWeight:600,cursor:'pointer',
                  border:'1.5px solid ' + (tw && tw.persoon ? K.groen : '#d69e2e'),
                  background: tw && tw.persoon ? K.groenZacht : K.okerZacht,
                  color: tw && tw.persoon ? K.groen : K.oker}}>
          👷 {tw && tw.persoon ? tw.persoon.naam : 'Nog niet toegewezen'}
          {tw && tw.deadline_outsourcing ? (
            <span style={{fontWeight:400, color: laat ? K.rood : 'inherit'}}> · deadline {datum(tw.deadline_outsourcing)}</span>
          ) : null}
        </button>
        {open && <ToewijzenVenster project={project} onClose={() => { setOpen(false); laad(); }} />}
      </>
    );
  }

  /* ── Instellingen: wie zijn de outsourcers ─────────────────────────────── */
  function OutsourcersBeheer() {
    const [lijst, setLijst] = React.useState(null);
    const [msg, setMsg] = React.useState('');
    const [err, setErr] = React.useState('');
    const [bezig, setBezig] = React.useState(false);
    React.useEffect(() => {
      haal('/api/outsourcers').then(l => setLijst(Array.isArray(l) ? l : [])).catch(e => setErr(e.message));
    }, []);
    const wijzig = (i, veld, waarde) => setLijst(l => l.map((o, j) => j === i ? { ...o, [veld]: waarde } : o));
    const bewaar = async () => {
      setBezig(true); setErr(''); setMsg('');
      try {
        const r = await zend('/api/outsourcers', 'PUT', { outsourcers: lijst });
        if (!r || !r.ok) throw new Error((r && r.error) || 'Bewaren mislukt');
        setLijst(r.outsourcers);
        setMsg('✓ Bewaard');
        setTimeout(() => setMsg(''), 2500);
      } catch (e) { setErr(e.message); }
      setBezig(false);
    };
    if (!lijst) return <div style={{fontSize:13,color:K.zacht}}>⏳ Laden…</div>;
    const veld = { padding:'7px 10px', border:'1.5px solid '+K.rand, borderRadius:6, fontSize:13, boxSizing:'border-box' };
    return (
      <div>
        <div style={{fontSize:13,color:K.tekst,marginBottom:12,lineHeight:1.5}}>
          De mensen aan wie een dossier toegewezen kan worden. Hun e-mailadres vult het verzendvenster naar outsourcing
          vanzelf in; <b>Enerveco</b> staat er altijd als extra keuze bij.
        </div>
        {lijst.map((o, i) => (
          <div key={o.key || i} style={{display:'flex',gap:8,marginBottom:8,flexWrap:'wrap',alignItems:'center'}}>
            <input value={o.naam || ''} onChange={e=>wijzig(i,'naam',e.target.value)} placeholder="Naam"
              style={{...veld, flex:'1 1 140px'}} />
            <input value={o.email || ''} onChange={e=>wijzig(i,'email',e.target.value)} placeholder="e-mailadres"
              style={{...veld, flex:'2 1 220px'}} />
            <button type="button" onClick={() => setLijst(l => l.filter((_, j) => j !== i))}
              title="Verwijderen"
              style={{padding:'6px 10px',background:'#fff',border:'1px solid '+K.rand,borderRadius:6,cursor:'pointer'}}>🗑️</button>
          </div>
        ))}
        <div style={{display:'flex',gap:8,alignItems:'center',marginTop:10,flexWrap:'wrap'}}>
          <button type="button" onClick={() => setLijst(l => l.concat([{ naam:'', email:'' }]))}
            style={{padding:'6px 12px',background:'#fff',border:'1px dashed '+K.rand,borderRadius:6,fontSize:12,color:K.zacht,cursor:'pointer'}}>
            ➕ Persoon toevoegen
          </button>
          <span style={{flex:1}} />
          {msg && <span style={{fontSize:12,color:K.groen,fontWeight:600}}>{msg}</span>}
          {err && <span style={{fontSize:12,color:K.rood}}>{err}</span>}
          <button type="button" onClick={bewaar} disabled={bezig}
            style={{padding:'7px 16px',background:K.groen,color:'#fff',border:'none',borderRadius:6,fontSize:13,fontWeight:600,cursor:'pointer'}}>
            {bezig ? '⏳ Bewaren…' : '💾 Bewaren'}
          </button>
        </div>
      </div>
    );
  }

  window.ToewijzenKeuze = ToewijzenKeuze;
  window.ToewijzenVenster = ToewijzenVenster;
  window.WerkverdelingTabel = WerkverdelingTabel;
  window.WerkverdelingPopup = WerkverdelingPopup;
  window.ToewijzingBadge = ToewijzingBadge;
  window.OutsourcersBeheer = OutsourcersBeheer;
})();
