const {store,calc,fmt,MockSnelStartService}=window.EG;
const {useStore,Pill,PageHead,SectionTitle,Kpi,KpiRow,Table,Tr,Td,EmptyState,Search,FilterRow,Toggle,Modal,SidePanel,FormGroup,Source,DataRow,Avatar,EmployeeCell,label12}=window;
const {Icon,Button,IconButton,Card,Amount,ProgressBar,Tabs,Badge,Alert,FormField,Input,Select,Textarea,Checkbox}=window;

/* ============ FACTURATIE-OVERZICHT ============ */
const INV_TABS=['Te factureren','Concept','Klaar voor SnelStart','Verzonden','Alles'];
function Facturatie({params}){
  useStore();const [tab,setTab]=React.useState((params&&params.tab)||'Te factureren');
  const t=calc.totals();const invs=store.invoices;const ss=store.snelstart;
  const [syncing,setSyncing]=React.useState(false);
  const sync=()=>{setSyncing(true);
    setTimeout(()=>{const r=MockSnelStartService.syncInvoices();setSyncing(false);
      window.EG_TOAST({tone:'info',title:'Synchronisatie voltooid',detail:r.checked+' facturen gecontroleerd · '+r.changed+' betaalstatussen bijgewerkt'})},1400)};
  const filtered=()=>{
    if(tab==='Concept')return invs.filter(i=>i.egStatus==='concept');
    if(tab==='Klaar voor SnelStart')return invs.filter(i=>i.egStatus==='gereed');
    if(tab==='Verzonden')return invs.filter(i=>i.egStatus==='verzonden');
    return invs;
  };
  const teFactureren=store.projects.map(p=>({p,u:calc.unbilled(p.id)})).filter(x=>x.u.total>0.005).sort((a,b)=>b.u.total-a.u.total);
  return <div>
    <PageHead title="Facturatie" sub="Van geschreven uren naar een factuurvoorstel. SnelStart verzorgt de financiële verwerking."
      actions={<div style={{display:'flex',alignItems:'center',gap:16,border:'1px solid var(--border-hairline)',borderRadius:'var(--radius-md)',padding:'10px 16px'}}>
        <div><div style={{display:'flex',alignItems:'center',gap:8}}>
          <span style={{width:7,height:7,borderRadius:'50%',background:'var(--success-600)'}}/>
          <span style={{fontFamily:'var(--font-display)',fontSize:13.5,fontWeight:600}}>SnelStart · Verbonden</span></div>
          <div style={{fontSize:11.5,color:'var(--text-faint)',marginTop:3,fontFamily:'var(--font-mono)'}}>
            {ss.lastSync?'Laatst gesynchroniseerd '+fmt.time(ss.lastSync):'Nog niet gesynchroniseerd'}</div></div>
        <Button size="sm" variant="secondary" icon="refresh-cw" onClick={sync} disabled={syncing}>{syncing?'Synchroniseren...':'Synchroniseren'}</Button></div>}/>
    {syncing?<Alert tone="info" title="SnelStart wordt gesynchroniseerd..." style={{marginBottom:24}}>Betaalstatussen worden opgehaald uit SnelStart.</Alert>:null}
    <KpiRow cols={4} style={{marginBottom:28}}>
      <Kpi label="Nog te factureren" value={fmt.eur0(t.unbilled)} note="Uit Bouwkonsult" onClick={()=>setTab('Te factureren')} accent/>
      <Kpi label="Projecten met uren" value={t.unbilledProjects} onClick={()=>setTab('Te factureren')}/>
      <Kpi label="Concept" value={t.conceptCount} onClick={()=>setTab('Concept')}/>
      <Kpi label="Klaar voor SnelStart" value={t.readyCount} onClick={()=>setTab('Klaar voor SnelStart')}/>
    </KpiRow>
    <Tabs items={INV_TABS} value={tab} onChange={setTab} style={{marginBottom:24}}/>
    {tab==='Te factureren'?<Card padding="0">
      {teFactureren.length?<Table cols={[{label:'Werknr.'},{label:'Project'},{label:'Klant'},{label:'Uren',right:true},{label:'Urenbedrag',right:true},
        {label:'Kosten',right:true},{label:'Totaal',right:true},{label:'',w:150}]}>
        {teFactureren.map(({p,u})=>{const c=calc.customer(p.customerId);
          return <Tr key={p.id}>
            <Td mono muted>{p.ref}</Td>
            <Td onClick={()=>window.EG_NAV('project',{id:p.id})} style={{fontWeight:500,color:'var(--ink-900)',cursor:'pointer'}}>{p.name}</Td>
            <Td muted>{c?c.name:''}</Td>
            <Td right><Amount value={u.hours} unit="uur" size={13.5}/></Td>
            <Td right><Amount value={u.hourValue} size={13.5}/></Td>
            <Td right><Amount value={u.costs} size={13.5} tone="muted"/></Td>
            <Td right><Amount value={u.total} size={14} weight={600}/></Td>
            <Td right><Button size="sm" variant="secondary" onClick={()=>window.EG_NAV('factuur-nieuw',{projectId:p.id})} style={{whiteSpace:'nowrap'}}>Factureren</Button></Td></Tr>})}
      </Table>:<EmptyState icon="check-circle" title="Alles is gefactureerd" >Er zijn geen facturabele uren of doorbelastbare kosten die nog niet aan een factuur zijn gekoppeld.</EmptyState>}
    </Card>:<Card padding="0">
      {filtered().length?<Table cols={[{label:'Factuur'},{label:'Klant'},{label:'Project'},{label:'Datum'},{label:'Bedrag',right:true},
        {label:'Bouwkonsult status'},{label:'SnelStart status'},{label:'',w:44}]}>
        {filtered().map(i=>{const c=calc.customer(i.customerId);const p=calc.project(i.projectId);
          return <Tr key={i.id} onClick={()=>window.EG_NAV('factuur',{id:i.id})}>
            <Td mono>{i.number}</Td><Td style={{color:'var(--ink-900)',fontWeight:500}}>{c?c.name:''}</Td>
            <Td muted>{p?p.ref+' · '+p.name:''}</Td><Td mono>{fmt.date(i.date)}</Td>
            <Td right><Amount value={i.snelstart?i.snelstart.total:calc.invoiceTotals(i.lines).total} size={13.5}/></Td>
            <Td><Pill kind="eg" value={i.egStatus}/></Td>
            <Td><Pill kind="ss" value={i.snelstart?i.snelstart.status:'niet_verzonden'}/></Td>
            <Td><Icon name="chevron-right" size={15} color="var(--ink-400)"/></Td></Tr>})}
      </Table>:<EmptyState icon="file-text" title="Geen facturen in deze status"/>}
    </Card>}</div>;
}

/* ============ FACTUUR SAMENSTELLEN ============ */
function FactuurNieuw({params}){
  useStore();
  const invoice=params.invoiceId?calc.invoice(params.invoiceId):null;
  const p=calc.project(invoice?invoice.projectId:params.projectId);
  const c=p?calc.customer(p.customerId):null;
  const pool=p?calc.entriesOf(p.id).filter(e=>e.billable&&(!e.invoiceId||(invoice&&e.invoiceId===invoice.id))):[];
  const costPool=p?calc.costsOf(p.id).filter(k=>k.rechargeable&&(!k.invoiceId||(invoice&&k.invoiceId===invoice.id))):[];
  const [sel,setSel]=React.useState(()=>new Set(invoice?invoice.entryIds:pool.map(e=>e.id)));
  const [selK,setSelK]=React.useState(()=>new Set(invoice?invoice.costIds:costPool.map(k=>k.id)));
  const tpl=store.invoiceTemplates;
  const [tplSel,setTplSel]=React.useState(()=>{
    const prev=invoice&&invoice.extraLines?invoice.extraLines:null;
    return tpl.map(t=>{const m=prev?prev.find(l=>l.templateId===t.id):null;
      return {id:t.id,on:prev?!!m:!!t.active,qty:m?String(m.qty):String(t.qty)}});
  });
  const [f,setF]=React.useState({date:invoice?invoice.date:window.EG.iso(new Date()),reference:invoice?invoice.reference:'',
    description:invoice?invoice.description:'Calculatiewerkzaamheden '+(p?p.name:''),paymentTerm:invoice?invoice.paymentTerm:(c?c.paymentTerm:30),
    lineLabel:invoice&&invoice.lines[0]?invoice.lines[0].description:'Calculatiewerkzaamheden '+new Date().toLocaleDateString('nl-NL',{month:'long',year:'numeric'})});
  const [confirm,setConfirm]=React.useState(false);const [sending,setSending]=React.useState(false);const [done,setDone]=React.useState(null);
  if(!p)return <EmptyState title="Project niet gevonden"/>;
  const chosen=pool.filter(e=>sel.has(e.id));
  const rawHours=chosen.reduce((a,e)=>a+e.hours,0);
  const perEmp={};chosen.forEach(e=>{perEmp[e.employeeId]=(perEmp[e.employeeId]||0)+e.hours});
  const hourLines=Object.keys(perEmp).sort((a,b)=>perEmp[b]-perEmp[a]).map(eid=>({
    description:f.lineLabel+(calc.employee(eid)?' \u00b7 '+calc.employeeName(eid):''),
    qty:calc.round(perEmp[eid]),unit:'uur',rate:calc.rateFor(p,eid),employeeId:eid,raw:perEmp[eid]}));
  const selHours=hourLines.reduce((a,l)=>a+l.qty,0);
  const rounded=Math.abs(selHours-rawHours)>0.004;
  const selCosts=costPool.filter(k=>selK.has(k.id)).reduce((a,k)=>a+k.qty*k.unitPrice,0);
  const extraLines=tplSel.filter(x=>x.on).map(x=>{const t=tpl.find(y=>y.id===x.id);if(!t)return null;
    const q=parseFloat(String(x.qty).replace(',','.'))||0;
    return {templateId:t.id,description:t.description,qty:q,unit:t.unit,rate:t.rate}}).filter(l=>l&&l.qty>0);
  const lines=hourLines.map(l=>({description:l.description,qty:l.qty,unit:l.unit,rate:l.rate,employeeId:l.employeeId}));
  if(selCosts>0)lines.push({description:'Doorbelaste projectkosten',qty:1,unit:'post',rate:Math.round(selCosts*100)/100,employeeId:null});
  extraLines.forEach(l=>lines.push({description:l.description,qty:l.qty,unit:l.unit,rate:l.rate,employeeId:null}));
  const tot=calc.invoiceTotals(lines);
  const build=(egStatus)=>({id:invoice?invoice.id:'inv-'+MockSnelStartService.nextInvoiceNumber(),
    number:invoice?invoice.number:MockSnelStartService.nextInvoiceNumber(),customerId:c.id,projectId:p.id,date:f.date,reference:f.reference,
    description:f.description,paymentTerm:Number(f.paymentTerm)||30,lines,extraLines,entryIds:[...sel],costIds:[...selK],egStatus,
    createdAt:invoice?invoice.createdAt:new Date().toISOString(),sentAt:null,snelstart:null,
    activity:invoice?invoice.activity:[{ts:new Date().toISOString(),text:'Factuur aangemaakt in Bouwkonsult',detail:'Concept'}]});
  const saveDraft=(status)=>{const inv=build(status);store.upsert('invoices',inv);
    window.EG_TOAST({title:status==='gereed'?'Factuur gereed voor SnelStart':'Concept opgeslagen',detail:inv.number+' · '+fmt.eur(tot.total)});
    window.EG_NAV('factuur',{id:inv.id});};
  const send=()=>{setSending(true);
    setTimeout(()=>{const inv=MockSnelStartService.sendInvoice(build('gereed'));setSending(false);setConfirm(false);setDone(inv)},1100)};
  const rowStyle={display:'flex',alignItems:'center',gap:14,padding:'11px 0',borderBottom:'1px solid var(--border-hairline)',fontSize:13.5};
  return <div>
    <PageHead back={{label:p.ref+' · '+p.name,onClick:()=>window.EG_NAV('project',{id:p.id})}} eyebrow={invoice?invoice.number:'Concept'} title={invoice?'Factuur bewerken':'Nieuwe factuur'}
      sub={<span>{c.name} · {p.ref} · {p.name}</span>}
      actions={<><Button variant="secondary" onClick={()=>saveDraft('concept')}>Opslaan als concept</Button>
        <Button variant="secondary" onClick={()=>saveDraft('gereed')}>Gereed voor SnelStart</Button>
        <Button onClick={()=>setConfirm(true)} disabled={tot.total<=0}>Naar SnelStart sturen</Button></>}/>
    <div style={{display:'grid',gridTemplateColumns:'1fr 340px',gap:28,alignItems:'start'}}>
      <div style={{display:'grid',gap:24}}>
        <Card><SectionTitle>Factuurgegevens</SectionTitle>
          <div style={{display:'grid',gridTemplateColumns:'1fr 1fr',gap:16}}>
            <FormField label="Factuurdatum"><Input type="date" value={f.date} onChange={e=>setF({...f,date:e.target.value})}/></FormField>
            <FormField label="Betaaltermijn" hint="Dagen"><Input type="number" value={f.paymentTerm} onChange={e=>setF({...f,paymentTerm:e.target.value})}/></FormField>
            <FormField label="Referentie opdrachtgever"><Input value={f.reference} onChange={e=>setF({...f,reference:e.target.value})} placeholder="REF-070/1042"/></FormField>
            <FormField label="Factuuromschrijving"><Input value={f.description} onChange={e=>setF({...f,description:e.target.value})}/></FormField>
            <FormField label="Omschrijving urenregels" hint="De naam van de medewerker wordt hierachter gezet" style={{gridColumn:'span 2'}}>
              <Input value={f.lineLabel} onChange={e=>setF({...f,lineLabel:e.target.value})}/></FormField></div></Card>
        <Card padding="0">
          <div style={{padding:'20px 24px 12px',display:'flex',justifyContent:'space-between',alignItems:'center'}}>
            <SectionTitle style={{marginBottom:0}}>Te factureren uren</SectionTitle>
            <button onClick={()=>setSel(sel.size===pool.length?new Set():new Set(pool.map(e=>e.id)))}
              style={{appearance:'none',border:0,background:'none',cursor:'pointer',color:'var(--text-link)',fontSize:13,textDecoration:'underline',fontFamily:'var(--font-body)'}}>
              {sel.size===pool.length?'Selectie wissen':'Alles selecteren'}</button></div>
          <div style={{padding:'0 24px'}}>
            {pool.length?pool.map(e=><div key={e.id} style={rowStyle}>
              <Checkbox checked={sel.has(e.id)} onChange={v=>{const n=new Set(sel);v?n.add(e.id):n.delete(e.id);setSel(n)}}/>
              <span style={{fontFamily:'var(--font-mono)',fontSize:12.5,color:'var(--text-faint)',width:84}}>{fmt.date(e.date)}</span>
              <Avatar employee={calc.employee(e.employeeId)} size={22}/>
              <span style={{flex:1,color:'var(--ink-900)'}}>{e.description}</span>
              <span style={{width:80,textAlign:'right'}}><Amount value={e.hours} unit="uur" size={13}/></span>
              <span style={{width:96,textAlign:'right'}}><Amount value={e.hours*calc.rateFor(p,e.employeeId)} size={13}/></span></div>)
            :<div style={{padding:'8px 0 20px'}}><EmptyState icon="timer" title="Geen facturabele uren beschikbaar">Alle facturabele uren van dit project zijn al aan een factuur gekoppeld.</EmptyState></div>}</div>
          <div style={{padding:'14px 24px',background:'var(--ink-50)',borderTop:'1px solid var(--border-hairline)',display:'flex',justifyContent:'space-between',alignItems:'baseline',fontSize:13.5}}>
            <span style={{color:'var(--text-muted)'}}>{sel.size} registraties geselecteerd</span>
            <span style={{display:'inline-flex',alignItems:'baseline',gap:10}}>
              {rounded?<span style={{fontSize:12.5,color:'var(--text-faint)'}}>{fmt.h(rawHours)} uur geschreven · per medewerker afgerond op {window.EG.roundingLabel(store.settings.rounding)}</span>:null}
              <Amount value={selHours} unit="uur" size={13.5} weight={600}/></span></div></Card>
        {costPool.length?<Card padding="0">
          <div style={{padding:'20px 24px 12px'}}><SectionTitle style={{marginBottom:0}}>Doorbelastbare kosten</SectionTitle></div>
          <div style={{padding:'0 24px'}}>{costPool.map(k=><div key={k.id} style={rowStyle}>
            <Checkbox checked={selK.has(k.id)} onChange={v=>{const n=new Set(selK);v?n.add(k.id):n.delete(k.id);setSelK(n)}}/>
            <span style={{fontFamily:'var(--font-mono)',fontSize:12.5,color:'var(--text-faint)',width:84}}>{fmt.date(k.date)}</span>
            <span style={{flex:1,color:'var(--ink-900)'}}>{k.type} · {k.description}</span>
            <span style={{width:96,textAlign:'right'}}><Amount value={k.qty*k.unitPrice} size={13}/></span></div>)}</div>
          <div style={{padding:'14px 24px',background:'var(--ink-50)',borderTop:'1px solid var(--border-hairline)',display:'flex',justifyContent:'space-between',fontSize:13.5}}>
            <span style={{color:'var(--text-muted)'}}>{selK.size} kostenregels geselecteerd</span><Amount value={selCosts} size={13.5} weight={600}/></div></Card>:null}
        {tpl.length?<Card padding="0">
          <div style={{padding:'20px 24px 12px',display:'flex',justifyContent:'space-between',alignItems:'center'}}>
            <div><SectionTitle style={{marginBottom:0}}>Standaardregels</SectionTitle>
              <div style={{fontSize:12.5,color:'var(--text-faint)',marginTop:4}}>Vink aan wat op deze factuur mee moet.</div></div>
            <button onClick={()=>window.EG_NAV('instellingen',{tab:'Factuurregels'})}
              style={{appearance:'none',border:0,background:'none',cursor:'pointer',color:'var(--text-link)',fontSize:13,textDecoration:'underline',fontFamily:'var(--font-body)'}}>Regels beheren</button></div>
          <div style={{padding:'0 24px 4px'}}>
            {tpl.map(t=>{const x=tplSel.find(y=>y.id===t.id)||{on:false,qty:'1'};
              const q=parseFloat(String(x.qty).replace(',','.'))||0;
              const upd=(patch)=>setTplSel(tplSel.map(y=>y.id===t.id?{...y,...patch}:y));
              return <div key={t.id} style={{...rowStyle,opacity:x.on?1:.6}}>
                <Checkbox checked={!!x.on} onChange={v=>upd({on:v})}/>
                <span style={{flex:1,color:'var(--ink-900)'}}>{t.description}</span>
                <span style={{width:74}}><Input value={x.qty} onChange={e=>upd({qty:e.target.value,on:true})} style={{minHeight:34,fontSize:13,padding:'6px 10px',textAlign:'right'}}/></span>
                <span style={{width:44,fontSize:12.5,color:'var(--text-faint)'}}>{t.unit}</span>
                <span style={{width:80,textAlign:'right'}}><Amount value={t.rate} size={13} tone="muted"/></span>
                <span style={{width:96,textAlign:'right'}}><Amount value={x.on?q*t.rate:0} size={13}/></span></div>})}</div>
          <div style={{padding:'14px 24px',background:'var(--ink-50)',borderTop:'1px solid var(--border-hairline)',display:'flex',justifyContent:'space-between',fontSize:13.5}}>
            <span style={{color:'var(--text-muted)'}}>{extraLines.length===1?'1 standaardregel':extraLines.length+' standaardregels'} op de factuur</span>
            <Amount value={extraLines.reduce((a,l)=>a+l.qty*l.rate,0)} size={13.5} weight={600}/></div></Card>:null}
        <Card padding="0">
          <div style={{padding:'20px 24px 4px'}}><SectionTitle style={{marginBottom:0}}>Factuurregels</SectionTitle></div>
          <Table cols={[{label:'Omschrijving'},{label:'Medewerker'},{label:'Aantal',right:true},{label:'Eenheid'},{label:'Tarief',right:true},{label:'Bedrag',right:true}]} style={{marginTop:8}}>
            {lines.map((l,i)=><Tr key={i}>
              <Td style={{color:'var(--ink-900)'}}>{l.description}</Td>
              <Td>{l.employeeId?<Avatar employee={calc.employee(l.employeeId)} size={22}/>:<span style={{color:'var(--text-faint)'}}>—</span>}</Td>
              <Td right mono>{fmt.num(l.qty,2)}</Td><Td muted>{l.unit}</Td>
              <Td right><Amount value={l.rate} size={13.5}/></Td>
              <Td right><Amount value={l.qty*l.rate} size={13.5} weight={600}/></Td></Tr>)}
          </Table>
          {hourLines.length>1?<div style={{padding:'12px 24px 20px',fontSize:12.5,color:'var(--text-faint)'}}>
            Elke medewerker krijgt een eigen regel met het tarief dat voor deze opdracht geldt.</div>:null}</Card></div>
      <div style={{display:'grid',gap:20,position:'sticky',top:24}}>
        <Card accent>
          <SectionTitle>Totalen</SectionTitle>
          <DataRow label="Subtotaal" value={fmt.eur(tot.sub)}/><DataRow label="BTW 21%" value={fmt.eur(tot.btw)}/>
          <div style={{display:'flex',justifyContent:'space-between',alignItems:'baseline',paddingTop:16,marginTop:6,borderTop:'2px solid var(--ink-900)'}}>
            <span style={{fontFamily:'var(--font-display)',fontSize:14,fontWeight:600}}>Totaal incl. BTW</span><Amount value={tot.total} size={20} weight={600}/></div>
          <div style={{marginTop:22,display:'grid',gap:10}}>
            <Button fullWidth onClick={()=>setConfirm(true)} disabled={tot.total<=0}>Naar SnelStart sturen</Button>
            <Button fullWidth variant="secondary" onClick={()=>saveDraft('concept')}>Opslaan als concept</Button></div></Card>
        <Card>
          <SectionTitle>Twee systemen</SectionTitle>
          <div style={{display:'grid',gap:14,fontSize:13,color:'var(--text-muted)',lineHeight:1.6}}>
            <div><Source from="Bouwkonsult"/><div style={{marginTop:5}}>Bouwkonsult stelt de factuur inhoudelijk samen: project, uren, kosten en factuurregels.</div></div>
            <div style={{paddingTop:12,borderTop:'1px solid var(--border-hairline)'}}><Source/><div style={{marginTop:5}}>SnelStart verwerkt de factuur financieel en bepaalt openstaand saldo, betaling en betaaldatum.</div></div></div></Card></div></div>
    {confirm?<Modal title="Factuur naar SnelStart sturen?" onClose={()=>!sending&&setConfirm(false)} width={480}
      footer={<><Button variant="secondary" onClick={()=>setConfirm(false)} disabled={sending}>Annuleren</Button>
        <Button onClick={send} disabled={sending}>{sending?'Versturen...':'Naar SnelStart sturen'}</Button></>}>
      {sending?<div style={{padding:'26px 0',textAlign:'center'}}>
        <div className="eg-spin" style={{width:26,height:26,border:'2px solid var(--ink-200)',borderTopColor:'var(--teal-600)',borderRadius:'50%',margin:'0 auto 16px'}}/>
        <div style={{fontSize:14,color:'var(--text-muted)'}}>Factuur wordt aangeboden aan SnelStart...</div></div>
      :<div>
        <div style={{border:'1px solid var(--border-hairline)',borderRadius:'var(--radius-sm)',padding:'16px 18px',marginBottom:18}}>
          <DataRow label="Factuur" value={invoice?invoice.number:MockSnelStartService.nextInvoiceNumber()}/>
          <DataRow label="Klant" value={c.name}/><DataRow label="Project" value={p.ref}/>
          <div style={{display:'flex',justifyContent:'space-between',paddingTop:12}}><span style={{fontSize:13.5,color:'var(--text-muted)'}}>Totaal</span><Amount value={tot.total} size={16} weight={600}/></div></div>
        <p style={{margin:0,fontSize:13.5,color:'var(--text-muted)',lineHeight:1.62}}>De factuur wordt definitief gemaakt en aangeboden aan SnelStart voor financiële verwerking. Betaalstatus en betaaldatum worden daarna vanuit SnelStart teruggelezen.</p></div>}</Modal>:null}
    {done?<Modal title="Factuur verwerkt door SnelStart" onClose={()=>window.EG_NAV('factuur',{id:done.id})} width={480}
      footer={<><Button variant="secondary" onClick={()=>window.EG_NAV('facturatie',{tab:'Verzonden'})}>Naar facturatie</Button>
        <Button onClick={()=>window.EG_NAV('factuur',{id:done.id})}>Factuur openen</Button></>}>
      <div style={{display:'flex',alignItems:'center',gap:12,marginBottom:18}}>
        <Icon name="check-circle" size={22} color="var(--success-600)"/>
        <span style={{fontFamily:'var(--font-display)',fontSize:15,fontWeight:600,color:'var(--success-600)'}}>Factuur succesvol verwerkt</span></div>
      <DataRow label="Bouwkonsult factuurnummer" value={done.number}/>
      <DataRow label="SnelStart-referentie" value={done.snelstart.reference}/>
      <DataRow label="Verzonden op" value={fmt.date(done.sentAt)+' · '+fmt.time(done.sentAt)}/>
      <DataRow label="Totaalbedrag" value={fmt.eur(done.snelstart.total)}/>
      <DataRow label="Vervaldatum" value={fmt.date(done.snelstart.dueDate)}/>
      <p style={{marginTop:18,marginBottom:0,fontSize:13,color:'var(--text-faint)'}}>De financiële status van deze factuur wordt vanaf nu vanuit SnelStart teruggelezen.</p></Modal>:null}
  </div>;
}

/* ============ FACTUURDETAIL ============ */
function Factuurdetail({params}){
  useStore();const i=calc.invoice(params.id);
  const [confirm,setConfirm]=React.useState(false);const [sending,setSending]=React.useState(false);
  if(!i)return <EmptyState title="Factuur niet gevonden"/>;
  const c=calc.customer(i.customerId);const p=calc.project(i.projectId);const tot=calc.invoiceTotals(i.lines);
  const entries=store.timeEntries.filter(e=>i.entryIds.includes(e.id));
  const costs=store.projectCosts.filter(k=>i.costIds.includes(k.id));
  const send=()=>{setSending(true);setTimeout(()=>{MockSnelStartService.sendInvoice(i);setSending(false);setConfirm(false);
    window.EG_TOAST({title:'Factuur verwerkt door SnelStart',detail:'SS-'+i.number})},1100)};
  return <div>
    <PageHead back={{label:'Facturatie',onClick:()=>window.EG_NAV('facturatie',{tab:'Alles'})}} eyebrow={'Factuur '+i.number} title={c?c.name:''}
      sub={p?p.ref+' · '+p.name:''}
      actions={<>{i.egStatus!=='verzonden'?<Button onClick={()=>setConfirm(true)}>Naar SnelStart sturen</Button>:null}
        {i.egStatus!=='verzonden'?<Button variant="secondary" onClick={()=>window.EG_NAV('factuur-nieuw',{invoiceId:i.id})}>Bewerken</Button>:null}</>}/>
    <div style={{display:'flex',gap:28,marginBottom:26,alignItems:'center'}}>
      <div><div style={{...label12,fontSize:10,marginBottom:7}}>Bouwkonsult status</div><Pill kind="eg" value={i.egStatus}/></div>
      <div style={{width:1,height:38,background:'var(--border-hairline)'}}/>
      <div><div style={{...label12,fontSize:10,marginBottom:7}}>SnelStart status</div><Pill kind="ss" value={i.snelstart?i.snelstart.status:'niet_verzonden'}/></div></div>
    <div style={{display:'grid',gridTemplateColumns:'1.5fr 1fr',gap:28,alignItems:'start'}}>
      <div style={{display:'grid',gap:24}}>
        <Card padding="0">
          <div style={{padding:'20px 24px 6px',display:'flex',justifyContent:'space-between',alignItems:'center'}}>
            <SectionTitle style={{marginBottom:0}}>Factuurgegevens Bouwkonsult</SectionTitle><Source from="Bouwkonsult"/></div>
          <div style={{padding:'8px 24px 20px'}}>
            <DataRow label="Klant" value={c?c.name:''}/><DataRow label="Project" value={p?p.ref+' · '+p.name:''}/>
            <DataRow label="Factuurdatum" value={fmt.date(i.date)}/><DataRow label="Referentie opdrachtgever" value={i.reference||'—'}/>
            <DataRow label="Betaaltermijn" value={i.paymentTerm+' dagen'}/>
            <DataRow label="Aangemaakt op" value={fmt.date(i.createdAt)+' · '+fmt.time(i.createdAt)}/>
            <DataRow label="Naar SnelStart gestuurd op" value={i.sentAt?fmt.date(i.sentAt)+' · '+fmt.time(i.sentAt):'Nog niet verzonden'}/></div>
          <Table cols={[{label:'Omschrijving'},{label:'Aantal',right:true},{label:'Eenheid'},{label:'Tarief',right:true},{label:'Bedrag',right:true}]}>
            {i.lines.map((l,ix)=><Tr key={ix}><Td style={{color:'var(--ink-900)'}}>{l.description}</Td>
              <Td right mono>{fmt.num(l.qty,2)}</Td><Td muted>{l.unit}</Td>
              <Td right><Amount value={l.rate} size={13.5}/></Td><Td right><Amount value={l.qty*l.rate} size={13.5}/></Td></Tr>)}
          </Table>
          <div style={{padding:'16px 24px 22px',display:'grid',gap:2,justifyItems:'end'}}>
            <div style={{width:280}}><DataRow label="Subtotaal" value={fmt.eur(tot.sub)}/><DataRow label="BTW 21%" value={fmt.eur(tot.btw)}/>
              <div style={{display:'flex',justifyContent:'space-between',paddingTop:12,borderTop:'2px solid var(--ink-900)',marginTop:4}}>
                <span style={{fontFamily:'var(--font-display)',fontSize:14,fontWeight:600}}>Totaal</span><Amount value={tot.total} size={16} weight={600}/></div></div></div></Card>
        <Card padding="0">
          <div style={{padding:'20px 24px 8px'}}><SectionTitle style={{marginBottom:0}}>Gekoppelde uren en kosten</SectionTitle></div>
          <Table cols={[{label:'Datum'},{label:'Medewerker'},{label:'Omschrijving'},{label:'Soort'},{label:'Aantal',right:true},{label:'Bedrag',right:true}]}>
            {entries.map(e=><Tr key={e.id}><Td mono>{fmt.date(e.date)}</Td>
              <Td><EmployeeCell id={e.employeeId}/></Td><Td>{e.description}</Td>
              <Td><Badge tone="neutral">Uren</Badge></Td>
              <Td right><Amount value={e.hours} unit="uur" size={13}/></Td>
              <Td right><Amount value={e.hours*calc.rateFor(p,e.employeeId)} size={13}/></Td></Tr>)}
            {costs.map(k=><Tr key={k.id}><Td mono>{fmt.date(k.date)}</Td>
              <Td>{k.employeeId?<EmployeeCell id={k.employeeId}/>:<span style={{color:'var(--text-faint)'}}>—</span>}</Td><Td>{k.description}</Td>
              <Td><Badge>{k.type}</Badge></Td><Td right mono>{fmt.num(k.qty,k.qty%1?2:0)}</Td>
              <Td right><Amount value={k.qty*k.unitPrice} size={13}/></Td></Tr>)}
          </Table></Card></div>
      <div style={{display:'grid',gap:24}}>
        <Card style={{borderTop:'3px solid var(--staal-500)'}}>
          <div style={{display:'flex',justifyContent:'space-between',alignItems:'center',marginBottom:14}}>
            <h3 style={{fontSize:15.5,margin:0}}>SnelStart</h3><Source/></div>
          {i.snelstart?<>
            <DataRow label="Financiële status" value={window.EG.SS_STATUS[i.snelstart.status].label}/>
            <DataRow label="SnelStart-referentie" value={i.snelstart.reference}/>
            <DataRow label="Factuurbedrag" value={fmt.eur(i.snelstart.total)}/>
            <DataRow label="Ontvangen" value={fmt.eur(i.snelstart.paid)}/>
            <DataRow label="Openstaand" value={fmt.eur(i.snelstart.outstanding)}/>
            <DataRow label="Vervaldatum" value={fmt.date(i.snelstart.dueDate)}/>
            <DataRow label="Betaaldatum" value={i.snelstart.paidDate?fmt.date(i.snelstart.paidDate):'—'}/>
            <DataRow label="Laatste synchronisatie" value={fmt.date(i.snelstart.lastSync)+' · '+fmt.time(i.snelstart.lastSync)}/>
            <p style={{marginTop:16,marginBottom:0,fontSize:12.5,color:'var(--text-faint)',lineHeight:1.6}}>Deze financiële informatie is afkomstig uit SnelStart en kan niet in Bouwkonsult worden gewijzigd.</p></>
          :<div style={{padding:'8px 0'}}><Alert tone="info" title="Nog niet verzonden">Deze factuur is nog niet aangeboden aan SnelStart. Er is daarom geen financiële status beschikbaar.</Alert></div>}</Card>
        <Card><SectionTitle>Activiteit</SectionTitle>
          <div style={{display:'grid',gap:0}}>{(i.activity||[]).map((a,ix)=>
            <div key={ix} style={{display:'flex',gap:14,paddingBottom:18}}>
              <div style={{display:'flex',flexDirection:'column',alignItems:'center',flex:'none'}}>
                <span style={{width:7,height:7,borderRadius:'50%',background:ix===0?'var(--teal-600)':'var(--ink-300)',marginTop:5}}/>
                {ix<i.activity.length-1?<span style={{flex:1,width:1,background:'var(--border-hairline)',marginTop:4}}/>:null}</div>
              <div><div style={{fontFamily:'var(--font-mono)',fontSize:11,color:'var(--text-faint)',letterSpacing:'.04em'}}>{fmt.date(a.ts)} · {fmt.time(a.ts)}</div>
                <div style={{fontSize:13.5,color:'var(--ink-900)',marginTop:3}}>{a.text}</div>
                {a.detail?<div style={{fontSize:12.5,color:'var(--text-muted)',marginTop:2}}>{a.detail}</div>:null}</div></div>)}</div></Card></div></div>
    {confirm?<Modal title="Factuur naar SnelStart sturen?" onClose={()=>!sending&&setConfirm(false)} width={460}
      footer={<><Button variant="secondary" onClick={()=>setConfirm(false)} disabled={sending}>Annuleren</Button>
        <Button onClick={send} disabled={sending}>{sending?'Versturen...':'Naar SnelStart sturen'}</Button></>}>
      {sending?<div style={{padding:'24px 0',textAlign:'center'}}>
        <div className="eg-spin" style={{width:26,height:26,border:'2px solid var(--ink-200)',borderTopColor:'var(--teal-600)',borderRadius:'50%',margin:'0 auto 16px'}}/>
        <div style={{fontSize:14,color:'var(--text-muted)'}}>Factuur wordt aangeboden aan SnelStart...</div></div>
      :<><DataRow label="Factuur" value={i.number}/><DataRow label="Klant" value={c?c.name:''}/><DataRow label="Totaal" value={fmt.eur(tot.total)}/>
        <p style={{marginTop:16,marginBottom:0,fontSize:13.5,color:'var(--text-muted)',lineHeight:1.62}}>De factuur wordt definitief gemaakt en aangeboden aan SnelStart voor financiële verwerking.</p></>}</Modal>:null}
  </div>;
}

Object.assign(window,{Facturatie,FactuurNieuw,Factuurdetail});
