import{a as Jl,bb as rn,h as g,j as n,$ as nn,F as kt,G as Y,x as we,y as We,z as $e,B as Ye,D as te,E as Oe,bc as ln,bd as on,be as sn,bf as dn,bg as cn,bh as un,bi as Bl,bj as Ql,bk as Zl,bl as Kl,bm as Xl,bn as eo,bo as to,bp as ao,bq as ro,br as io,bs as no,ag as lo,bt as oo,bu as so,bv as co,bw as uo,as as ho,bx as mo,A as Ui,J as fo,by as go,bz as po,av as ia,aw as yo,bA as Vi}from"./index-Da-VPv7f.js";import{r as S,b5 as hn,b6 as bo,aQ as mn,b7 as xo,b8 as fn,b9 as vo,ba as _o,bb as Do,bc as So,bd as Po,be as Gi,bf as No,bg as Mo,bh as Ro}from"./mui-icons-CVqIXJUc.js";import{D as gn,c as pn,L as lr,A as or,e as sr,d as it}from"./mui-x-pickers-BflNfF54.js";import"./html2canvas.esm-CBrSDip1.js";import{l as j,I as Zt,y as st,P as Se,p as c,C as xr,D as Co,t as ko,u as To,q as wo,c as me,A as Ee,k as je,x as vr,S as Hi,m as qi,H as Wo}from"./mui-x-datagrid-D42xrz8e.js";import{T as P}from"./mui-x-charts-CP3e2jhe.js";const $o=Jl.injectEndpoints({endpoints:e=>({getTopSellerPagination:e.mutation({query:({page:t,size:a,payload:i})=>({url:`job-order/top-seller/pagination?page=${t}&size=${a}`,method:"POST",body:i})}),getTopSellerPaginationForPrint:e.mutation({query:({page:t,size:a,payload:i})=>({url:`job-order/top-seller/pagination?page=${t}&size=${a}$type=print`,method:"POST",body:i})}),getSalesReportPagination:e.mutation({query:({page:t,size:a,payload:i})=>({url:`job-order/sales-report/pagination?page=${t}&size=${a}`,method:"POST",body:i})}),getSalesReportPaginationForPrint:e.mutation({query:({page:t,size:a,payload:i})=>({url:`job-order/sales-report/pagination?page=${t}&size=${a}&type=print`,method:"POST",body:i})}),getPurchaseMaterialPagination:e.mutation({query:({page:t,size:a,payload:i})=>({url:`material-receive-note/purchase/pagination?page=${t}&size=${a}`,method:"POST",body:i})}),getPurchaseMaterialPaginationForPrint:e.mutation({query:({page:t,size:a,payload:i})=>({url:`material-receive-note/purchase/pagination?page=${t}&size=${a}&type=print`,method:"POST",body:i})}),getTopBuyersPagination:e.mutation({query:({page:t,size:a,payload:i})=>({url:`material-receive-note/top-buyers/pagination?page=${t}&size=${a}`,method:"POST",body:i})}),getTopBuyersPaginationForPrint:e.mutation({query:({page:t,size:a,payload:i})=>({url:`material-receive-note/top-buyers/pagination?page=${t}&size=${a}&type=print`,method:"POST",body:i})})})}),{useGetTopSellerPaginationMutation:Yo,useGetTopSellerPaginationForPrintMutation:Oo,useGetSalesReportPaginationMutation:Io,useGetPurchaseMaterialPaginationMutation:Fo,useGetPurchaseMaterialPaginationForPrintMutation:Lo,useGetSalesReportPaginationForPrintMutation:Ao,useGetTopBuyersPaginationForPrintMutation:Eo,useGetTopBuyersPaginationMutation:jo}=$o,ze=e=>`₹ ${Number(e??0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,Rt=e=>Number(e??0).toLocaleString("en-IN"),zo=e=>e!=null&&e!=="",Tr=(e,t)=>{for(const a of t){const i=e==null?void 0:e[a];if(zo(i)&&!Number.isNaN(Number(i)))return Number(i)}return null},_r=e=>Tr(e,["avg_landed_cost","avgLandedCost","averageLandedCost","landed_cost_per_kg","landedCostPerKg","landed_cost","landedCost"]),Dr=e=>Tr(e,["total_usage_quantity","totalUsageQuantity","totalUsageQty","totalUsage","usageQuantity","usedQty"])??0,Ji=e=>{const t=Tr(e,["material_usage_cost","materialUsageCost","material_cost","materialCost","totalMaterialCost","totalCost"]);if(t!==null&&t>0)return t;const a=_r(e);return a!==null?Dr(e)*a:t??0},jt=e=>{if(!e)return"-";const t=new Date(e);return isNaN(t.getTime())?"-":t.toLocaleDateString("en-IN",{day:"2-digit",month:"2-digit",year:"numeric"})},Uo=({open:e,jobCardId:t,jobCardNo:a,onClose:i})=>{const[l,{isLoading:s}]=rn(),[u,D]=S.useState(null),[M,p]=S.useState(null);S.useEffect(()=>{if(!e||t==null)return;let w=!1;return(async()=>{var T;p(null),D(null);try{const K=await l({jobCardId:t}).unwrap();w||D(K)}catch(K){w||p(((T=K==null?void 0:K.data)==null?void 0:T.error)||(K==null?void 0:K.error)||"Failed to load cost detail")}})(),()=>{w=!0}},[e,t,l]);const b=(u==null?void 0:u.summary)??{},z=(u==null?void 0:u.utilities)??[],ne=(u==null?void 0:u.materials)??[],N=(u==null?void 0:u.processes)??[],v=N.reduce((w,T)=>w+Number(T.production_cost??0),0),V=[{label:"Material Cost",value:ze(b.material_cost),color:"info.main"},{label:"Utility Charges",value:ze(b.utility_charges),color:"warning.main"},{label:"Production Cost",value:ze(b.total_cost),color:"secondary.main"},{label:"Cost / Unit",value:ze(b.cost_per_unit),color:"primary.main"}],ye=()=>{if(!u)return;const w=window.open("","_blank","width=1100,height=800");if(!w)return;const T=(m,Ie)=>m.length===0?`<tr><td colspan="${Ie.length}" style="text-align:center;color:#999;padding:12px">No records</td></tr>`:m.map(be=>`<tr>${Ie.map((Be,Fe)=>`<td style="${Fe===0?"":"text-align:right"}">${Be(be)}</td>`).join("")}</tr>`).join(""),K=`${a||b.job_card_no||"#"+t}${b.product_name?" · "+b.product_name:""}`;w.document.write(`
      <!DOCTYPE html><html><head><title>Job Card Cost Detail - ${K}</title>
      <style>
        @media print { @page { size: A4 portrait; margin: 1cm; } }
        * { box-sizing: border-box; }
        body { font-family: 'Segoe UI', Tahoma, sans-serif; color: #333; padding: 16px; }
        h1 { color: #1976d2; font-size: 20px; margin: 0 0 4px; }
        .sub { color: #666; font-size: 13px; margin-bottom: 16px; }
        .kpis { display: flex; flex-wrap: wrap; gap: 10px; margin-bottom: 18px; }
        .kpi { border: 1px solid #e0e0e0; border-left: 4px solid #1976d2; border-radius: 6px; padding: 8px 12px; min-width: 140px; }
        .kpi .l { font-size: 11px; color: #666; }
        .kpi .v { font-size: 15px; font-weight: 700; }
        h2 { font-size: 13px; text-transform: uppercase; letter-spacing: .04em; color: #1976d2; margin: 18px 0 6px; }
        table { width: 100%; border-collapse: collapse; font-size: 12px; }
        th, td { border: 1px solid #e0e0e0; padding: 6px 8px; text-align: left; }
        th { background: #f5f5f5; font-weight: 700; }
        tfoot td { font-weight: 700; }
      </style></head><body>
        <h1>Job Card Cost Detail</h1>
        <div class="sub">${K}${b.production_date?" · "+jt(b.production_date):""}
          &nbsp;|&nbsp; Net produced: ${Rt(b.net_produced_qty)} &nbsp;·&nbsp; Total produced: ${Rt(b.total_produced_qty)}</div>
        <div class="kpis">
          ${V.map(m=>`<div class="kpi"><div class="l">${m.label}</div><div class="v">${m.value}</div></div>`).join("")}
        </div>

        <h2>Material Consumption</h2>
        <table>
          <thead><tr><th>Grade</th><th>Product</th><th>Shift</th><th>Date</th>
            <th style="text-align:right">Usage Qty</th><th style="text-align:right">Avg Landed Cost</th><th style="text-align:right">Material Cost</th></tr></thead>
          <tbody>${T(ne,[m=>m.grade_name??"-",m=>m.product_name??"-",m=>m.shift_name??"-",m=>jt(m.production_date),m=>`${Rt(Dr(m))} ${m.unit??""}`,m=>ze(_r(m)),m=>ze(Ji(m))])}</tbody>
        </table>

        <h2>Utility Charges</h2>
        <table>
          <thead><tr><th>Utility</th><th>Shift</th><th>Date</th>
            <th style="text-align:right">Quantity</th><th>UOM</th><th style="text-align:right">Unit Rate</th><th style="text-align:right">Amount</th></tr></thead>
          <tbody>${T(z,[m=>m.utility_type??"-",m=>m.shift_name??"-",m=>jt(m.production_date),m=>Rt(m.quantity),m=>m.uom??"-",m=>ze(m.unit_rate),m=>ze(m.total_amount)])}</tbody>
        </table>

        <h2>Process Production Cost</h2>
        <table>
          <thead><tr><th>Process</th><th>Grade</th></tr></thead>
          <tbody>${T(N,[m=>m.operation_name??"-",m=>m.grade_name??"-"])}</tbody>
        </table>
      </body></html>
    `),w.document.close(),w.focus(),setTimeout(()=>w.print(),300)};return g(pn,{open:e,onClose:i,maxWidth:"lg",fullWidth:!0,children:[g(nn,{sx:{background:"linear-gradient(135deg, #1565c0 0%, #1976d2 45%, #42a5f5 100%)",color:"common.white",display:"flex",alignItems:"center",gap:1.5,pr:6},children:[n(hn,{}),g(j,{children:[n(P,{variant:"h6",fontWeight:800,lineHeight:1.1,children:"Job Card Cost Detail"}),g(P,{variant:"caption",sx:{opacity:.9},children:[a||b.job_card_no||`#${t}`,b.product_name?` · ${b.product_name}`:"",b.production_date?` · ${jt(b.production_date)}`:""]})]}),n(Zt,{onClick:ye,disabled:!u||s,title:"Print detail",sx:{position:"absolute",right:48,top:8,color:"common.white"},children:n(bo,{})}),n(Zt,{onClick:i,sx:{position:"absolute",right:8,top:8,color:"common.white"},children:n(mn,{})})]}),n(gn,{dividers:!0,sx:{bgcolor:"grey.50"},children:s?n(j,{display:"flex",justifyContent:"center",alignItems:"center",py:6,children:n(st,{})}):M?n(P,{color:"error",sx:{py:4,textAlign:"center"},children:M}):g(kt,{children:[n(Y,{container:!0,spacing:2,sx:{mb:1},children:V.map(w=>n(Y,{item:!0,xs:6,sm:4,md:2.4,children:g(we,{variant:"outlined",sx:{p:1.5,borderLeft:3,borderLeftColor:w.color,borderRadius:2},children:[n(P,{variant:"caption",color:"text.secondary",sx:{fontWeight:500},children:w.label}),n(P,{variant:"subtitle1",fontWeight:700,sx:{color:w.color,lineHeight:1.3},children:w.value})]})},w.label))}),g(P,{variant:"caption",color:"text.secondary",sx:{display:"block",mb:2},children:["Net produced: ",Rt(b.net_produced_qty)," · Total produced: ",Rt(b.total_produced_qty)]}),n(dr,{title:"Material Consumption",subtitle:`${ne.length} grade line(s)`}),n(We,{component:Se,variant:"outlined",sx:{mb:3,borderRadius:2},children:g($e,{size:"small",children:[n(Ye,{children:g(te,{sx:{"& th":{fontWeight:700,bgcolor:"action.hover"}},children:[n(c,{children:"Grade"}),n(c,{children:"Product"}),n(c,{children:"Shift"}),n(c,{children:"Date"}),n(c,{align:"right",children:"Usage Qty"}),n(c,{align:"right",children:"Landed Cost"}),n(c,{align:"right",children:"Material Cost"})]})}),n(Oe,{children:ne.length===0?n(cr,{span:7}):ne.map((w,T)=>g(te,{hover:!0,children:[n(c,{children:w.grade_name??"-"}),n(c,{children:w.product_name??"-"}),n(c,{children:w.shift_name??"-"}),n(c,{children:jt(w.production_date)}),g(c,{align:"right",children:[Rt(Dr(w))," ",w.unit??""]}),n(c,{align:"right",children:ze(_r(w))}),n(c,{align:"right",children:ze(Ji(w))})]},T))})]})}),n(dr,{title:"Utility Charges",subtitle:`${z.length} charge line(s)`}),n(We,{component:Se,variant:"outlined",sx:{mb:3,borderRadius:2},children:g($e,{size:"small",children:[n(Ye,{children:g(te,{sx:{"& th":{fontWeight:700,bgcolor:"action.hover"}},children:[n(c,{children:"Utility"}),n(c,{children:"Shift"}),n(c,{children:"Date"}),n(c,{align:"right",children:"Quantity"}),n(c,{children:"UOM"}),n(c,{align:"right",children:"Unit Rate"}),n(c,{align:"right",children:"Amount"})]})}),n(Oe,{children:z.length===0?n(cr,{span:7}):z.map((w,T)=>g(te,{hover:!0,children:[n(c,{children:w.utility_type??"-"}),n(c,{children:w.shift_name??"-"}),n(c,{children:jt(w.production_date)}),n(c,{align:"right",children:Rt(w.quantity)}),n(c,{children:w.uom??"-"}),n(c,{align:"right",children:ze(w.unit_rate)}),n(c,{align:"right",children:ze(w.total_amount)})]},T))})]})}),n(dr,{title:"Process",subtitle:`${N.length} process(es) · ${ze(v)} / unit`}),n(We,{component:Se,variant:"outlined",sx:{mb:1,borderRadius:2},children:g($e,{size:"small",children:[n(Ye,{children:g(te,{sx:{"& th":{fontWeight:700,bgcolor:"action.hover"}},children:[n(c,{children:"Process"}),n(c,{children:"Grade"})]})}),n(Oe,{children:N.length===0?n(cr,{span:4}):N.map((w,T)=>g(te,{hover:!0,children:[n(c,{children:w.operation_name??"-"}),n(c,{children:w.grade_name??"-"})]},T))})]})})]})})]})},dr=({title:e,subtitle:t})=>g(j,{display:"flex",alignItems:"baseline",gap:1.5,mb:1,children:[n(P,{variant:"subtitle2",fontWeight:700,color:"primary.main",sx:{textTransform:"uppercase",letterSpacing:"0.04em"},children:e}),t&&n(P,{variant:"caption",color:"text.secondary",children:t})]}),cr=({span:e})=>n(te,{children:n(c,{colSpan:e,align:"center",sx:{color:"text.disabled",py:3},children:"No records"})}),Ce=e=>`₹ ${Number(e??0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,_e=e=>Number(e??0).toLocaleString("en-IN"),U=e=>e==null||e===""?"-":e,nt=e=>{if(!e)return"-";const t=new Date(e);return isNaN(t.getTime())?"-":t.toLocaleDateString("en-IN",{day:"2-digit",month:"2-digit",year:"numeric"})},yn=S.forwardRef(({jobCardNo:e,fromDate:t,toDate:a,plantId:i,reloadKey:l,onReadyChange:s},u)=>{const[D]=ln(),[M]=rn(),[p,b]=S.useState(null),[z,ne]=S.useState(!1),[N,v]=S.useState(null);S.useEffect(()=>{if(!e)return;let f=!1;return(async()=>{var y,E;ne(!0),v(null),b(null);try{const G=await D({page:0,size:5,payload:{fromDate:t||null,toDate:a||null,jobCardNo:e,plantId:i??null}}).unwrap(),F=(y=(Array.isArray(G==null?void 0:G.data)?G.data:G!=null&&G.data?[G.data]:[])[0])==null?void 0:y.job_card_id;if(F==null){f||v("No cost data found for this job card.");return}const L=await M({jobCardId:F}).unwrap();f||b(L)}catch(G){f||v(((E=G==null?void 0:G.data)==null?void 0:E.error)||(G==null?void 0:G.error)||"Failed to load job card report")}finally{f||ne(!1)}})(),()=>{f=!0}},[l]);const V=(p==null?void 0:p.summary)??{},ye=(p==null?void 0:p.utilities)??[],w=(p==null?void 0:p.materials)??[],T=(p==null?void 0:p.processes)??[],K=(p==null?void 0:p.products)??[],m=(p==null?void 0:p.hourlyRecords)??[],Ie=S.useMemo(()=>{const f={};return K.forEach(y=>{const E=(y==null?void 0:y.product_id)??(y==null?void 0:y.productId);if(E==null)return;const G=String(E);f[G]=(f[G]??0)+1}),f},[K]),be=f=>(f==null?void 0:f.job_card_product_id)??(f==null?void 0:f.jobCardProductId)??(f==null?void 0:f.jobCardProductID),Be=f=>(f==null?void 0:f.product_id)??(f==null?void 0:f.productId),Fe=(f,y)=>{const E=(y==null?void 0:y.id)??(y==null?void 0:y.job_card_product_id)??(y==null?void 0:y.jobCardProductId),G=be(f);if(G!=null)return E!=null&&String(G)===String(E);const H=Be(y),F=Be(f);return H!=null&&F!=null&&Ie[String(H)]===1&&String(F)===String(H)},ve=(f,y)=>f.filter(E=>Fe(E,y)),X=S.useMemo(()=>w.filter(f=>!K.some(y=>Fe(f,y))),[w,K,Ie]);T.reduce((f,y)=>f+Number(y.production_cost??0),0);const Le=[{label:"Material Cost",value:Ce(V.material_cost),color:"#0288d1"},{label:"Utility Charges",value:Ce(V.utility_charges),color:"#ed6c02"},{label:"Production Cost",value:Ce(V.total_cost),color:"#c62828"}];S.useEffect(()=>{s==null||s(!!p&&!z)},[p,z,s]);const at=()=>{const f=W=>String(W??"-").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),y=Le.map(W=>`
          <div class="kpi" style="border-left-color:${W.color}">
            <div class="kpi-label">${f(W.label)}</div>
            <div class="kpi-value" style="color:${W.color}">${f(W.value)}</div>
          </div>`).join(""),E=K.length>0?K.map(W=>W.product_variant?`${U(W.product_name)} ${W.product_variant}`:U(W.product_name)).join(", "):V.product_variant?`${U(V.product_name)} ${V.product_variant}`:U(V.product_name),G=[{label:"Job Card No",value:U(e||V.job_card_no)},{label:"Products",value:E},{label:"Production Date",value:nt(V.production_date)},{label:"Net Produced",value:_e(V.net_produced_qty)},{label:"Total Produced",value:_e(V.total_produced_qty)}].map(W=>`
          <div class="info-cell">
            <div class="info-label">${f(W.label)}</div>
            <div class="info-value">${f(W.value)}</div>
          </div>`).join(""),H=(W,Ve,rt,ht)=>`
      <h2 class="section-title">${f(W)} <span class="section-sub">${f(Ve)}</span></h2>
      <table>
        <thead>
          <tr>${rt.map(Nt=>`<th class="${Nt.align==="right"?"text-right":""}">${f(Nt.label)}</th>`).join("")}</tr>
        </thead>
        <tbody>
          ${ht.length>0?ht.join(""):`<tr><td colspan="${rt.length}" class="empty">No records</td></tr>`}
        </tbody>
      </table>`,F=K.map(W=>{const Ve=ve(m,W),rt=ve(w,W),ht=W.product_variant?`${U(W.product_name)} · ${W.product_variant}`:U(W.product_name),Nt=rt.length===0?'<tr><td colspan="6" class="empty">No material records</td></tr>':rt.map(O=>`
          <tr>
            <td>${f(U(O.grade_name))}</td>
            <td>${f(U(O.shift_name))}</td>
            <td>${f(nt(O.production_date))}</td>
            <td class="text-right">${f(`${_e(O.total_usage_quantity)} ${O.unit??""}`.trim())}</td>
            <td class="text-right">${f(Ce(O.avg_landed_cost))}</td>
            <td class="text-right">${f(Ce(O.material_usage_cost))}</td>
          </tr>`).join(""),h=Ve.length===0?'<tr><td colspan="7" class="empty">No hourly records</td></tr>':Ve.map(O=>`
          <tr>
            <td>${f(U(O.shift_name))}</td>
            <td>${f(nt(O.production_date))}</td>
            <td>${f(U(O.hour_slot))}</td>
            <td class="text-right">${f(_e(O.produced_quantity))}</td>
            <td class="text-right">${f(_e(O.rejected_quantity))}</td>
            <td>${f(U(O.machine_name))}</td>
            <td>${f(U(O.remarks))}</td>
          </tr>`).join("");return`
        <div style="margin-bottom:16px;border-left:3px solid #1976d2;padding-left:12px">
          <div style="display:flex;align-items:center;gap:8px;margin-bottom:8px">
            <span style="background:#1976d2;color:#fff;padding:2px 10px;border-radius:12px;font-size:11px;font-weight:700">${f(ht)}</span>
            <span style="font-size:11px;color:#666">Planned: ${f(_e(W.planned_quantity))} &middot; Completed: ${f(_e(W.completed_quantity))}</span>
          </div>
          <div style="font-size:10px;font-weight:700;color:#666;text-transform:uppercase;letter-spacing:0.04em;margin-bottom:4px">Material Consumption</div>
          <table style="margin-bottom:10px">
            <thead>
              <tr>
                <th>Grade</th><th>Shift</th><th>Date</th>
                <th class="text-right">Usage Qty</th><th class="text-right">Avg Landed Cost</th>
                <th class="text-right">Material Cost</th>
              </tr>
            </thead>
            <tbody>${Nt}</tbody>
          </table>
          <div style="font-size:10px;font-weight:700;color:#666;text-transform:uppercase;letter-spacing:0.04em;margin-bottom:4px">Hourly Production Records</div>
          <table>
            <thead>
              <tr>
                <th>Shift</th><th>Date</th><th>Hour Slot</th>
                <th class="text-right">Produced Qty</th><th class="text-right">Rejected Qty</th>
                <th>Machine</th><th>Remarks</th>
              </tr>
            </thead>
            <tbody>${h}</tbody>
          </table>
        </div>`}).join("");X.map(W=>`
      <tr>
        <td>${f(U(W.grade_name))}</td>
        <td>${f(U(W.product_name))}</td>
        <td>${f(U(W.shift_name))}</td>
        <td>${f(nt(W.production_date))}</td>
        <td class="text-right">${f(`${_e(W.total_usage_quantity)} ${W.unit??""}`.trim())}</td>
        <td class="text-right">${f(Ce(W.avg_landed_cost))}</td>
        <td class="text-right">${f(Ce(W.material_usage_cost))}</td>
      </tr>`).join("");const L=ye.map(W=>`
        <tr>
          <td>${f(U(W.utility_type))}</td>
          <td>${f(U(W.shift_name))}</td>
          <td>${f(nt(W.production_date))}</td>
          <td class="text-right">${f(_e(W.quantity))}</td>
          <td>${f(U(W.uom))}</td>
          <td class="text-right">${f(Ce(W.unit_rate))}</td>
          <td class="text-right">${f(Ce(W.total_amount))}</td>
        </tr>`);return T.map(W=>`
        <tr>
          <td>${f(U(W.operation_name))}</td>
          <td>${f(U(W.grade_name))}</td>
          <td>${f(U(W.unit_of_measure))}</td>
          <td class="text-right">${f(Ce(W.production_cost))}</td>
        </tr>`),`
      <!DOCTYPE html>
      <html>
        <head>
          <title>Job Card Consolidated Report - ${f(U(e||V.job_card_no))}</title>
          <style>
            @media print { @page { size: A4 portrait; margin: 1cm; } .no-print { display:none; } }
            * { margin: 0; padding: 0; box-sizing: border-box; }
            body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; padding: 20px; color: #333; background: #fff; }
            .print-header { display:flex; align-items:center; justify-content:space-between; margin-bottom:20px; border-bottom:3px solid #1976d2; padding-bottom:12px; }
            .company-name { font-size:22px; font-weight:700; color:#1976d2; text-transform:uppercase; }
            .print-header-center { flex:1; text-align:center; }
            .print-header h1 { font-size:22px; color:#1976d2; font-weight:700; }
            .print-header .meta { font-size:13px; color:#666; margin-top:4px; }
            .kpi-grid { display:flex; flex-wrap:wrap; gap:8px; margin-bottom:20px; }
            .kpi { flex:1 1 140px; min-width:140px; border:1px solid #e0e0e0; border-left:4px solid #1976d2; border-radius:6px; padding:8px 10px; }
            .kpi-label { font-size:11px; color:#666; }
            .kpi-value { font-size:15px; font-weight:800; line-height:1.3; }
            .section-title { font-size:14px; color:#1976d2; text-transform:uppercase; letter-spacing:0.04em; margin:18px 0 8px; }
            .section-sub { font-size:11px; color:#888; font-weight:400; text-transform:none; letter-spacing:0; }
            .info-card { display:flex; flex-wrap:wrap; gap:16px; border:1px solid #e0e0e0; border-radius:6px; padding:12px; margin-bottom:6px; }
            .info-cell { flex:1 1 140px; }
            .info-label { font-size:11px; color:#666; }
            .info-value { font-size:13px; font-weight:700; }
            table { width:100%; border-collapse:collapse; font-size:11px; }
            thead { background-color:#1976d2; color:#fff; }
            th { padding:8px 6px; text-align:left; font-weight:600; border:1px solid #1565c0; }
            td { padding:6px; border:1px solid #e0e0e0; }
            tbody tr:nth-child(even) { background-color:#f9f9f9; }
            .text-right { text-align:right; }
            .empty { text-align:center; color:#999; padding:16px; }
            .note { font-size:11px; color:#888; margin-top:8px; }
            .print-footer { margin-top:24px; padding-top:12px; border-top:2px solid #e0e0e0; text-align:center; font-size:11px; color:#666; }
          </style>
        </head>
        <body>
          <div class="print-header">
            <div class="company-name">PR BLOCKS</div>
            <div class="print-header-center">
              <h1>Job Card Consolidated Report</h1>
              <div class="meta"><strong>Job Card:</strong> ${f(U(e||V.job_card_no))}${E&&E!=="-"?` · ${f(E)}`:""}</div>
              <div class="meta"><strong>Production Date:</strong> ${f(nt(V.production_date))}</div>
              <div class="meta"><strong>Generated:</strong> ${f(new Date().toLocaleString("en-IN",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"}))}</div>
            </div>
          </div>

          <div class="kpi-grid">${y}</div>

          <h2 class="section-title">Job Card Information</h2>
          <div class="info-card">${G}</div>

          ${K.length>0?`
          <h2 class="section-title">Production by Product <span class="section-sub">${K.length} product(s)</span></h2>
          ${F}
          `:""}

        

          ${H("Utility Charges",`${ye.length} charge line(s)`,[{label:"Utility"},{label:"Shift"},{label:"Date"},{label:"Quantity",align:"right"},{label:"UOM"},{label:"Unit Rate",align:"right"},{label:"Amount",align:"right"}],L)}

         
          <div class="note">Production cost = (sum of per-unit process rates) × net produced qty.</div>

          <div class="print-footer">
            <p>PR BLOCKS — Job Card Consolidated Report</p>
          </div>
        </body>
      </html>`};return S.useImperativeHandle(u,()=>({print:()=>{if(!p)return;const f=window.open("","_blank","width=1100,height=800");f&&(f.document.write(at()),f.document.close(),f.focus(),setTimeout(()=>f.print(),300))}})),z?n(j,{display:"flex",justifyContent:"center",alignItems:"center",py:8,children:n(st,{})}):N?n(P,{color:"error",sx:{py:4,textAlign:"center"},children:N}):p?g(j,{children:[n(Y,{container:!0,spacing:1.5,sx:{mb:3},children:Le.map(f=>n(Y,{item:!0,xs:6,sm:4,md:2.4,children:g(we,{variant:"outlined",sx:{p:1.5,borderLeft:4,borderLeftColor:f.color,borderRadius:2,height:"100%"},children:[n(P,{variant:"caption",color:"text.secondary",sx:{fontWeight:500},children:f.label}),n(P,{variant:"subtitle1",fontWeight:800,sx:{color:f.color,lineHeight:1.25},children:f.value})]})},f.label))}),n(ur,{title:"Job Card Information"}),n(we,{variant:"outlined",sx:{p:2,mb:3,borderRadius:2},children:g(j,{sx:{display:"flex",alignItems:"flex-start",gap:2},children:[n(j,{sx:{width:56,height:56,borderRadius:2,bgcolor:"primary.50",color:"primary.main",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:n(hn,{fontSize:"large"})}),g(Y,{container:!0,spacing:2,sx:{flex:1},children:[[{label:"Job Card No",value:U(e||V.job_card_no)},{label:"Production Date",value:nt(V.production_date)},{label:"Net Produced",value:_e(V.net_produced_qty)},{label:"Total Produced",value:_e(V.total_produced_qty)}].map(f=>g(Y,{item:!0,xs:6,sm:3,children:[n(P,{variant:"caption",color:"text.secondary",sx:{fontWeight:500},children:f.label}),n(P,{variant:"body2",fontWeight:700,children:f.value})]},f.label)),g(Y,{item:!0,xs:12,children:[n(P,{variant:"caption",color:"text.secondary",sx:{fontWeight:500},children:"Products"}),n(j,{sx:{display:"flex",flexWrap:"wrap",gap:.75,mt:.5},children:K.length>0?K.map((f,y)=>n(xr,{size:"small",label:f.product_variant?`${U(f.product_name)} ${f.product_variant}`:U(f.product_name),variant:"outlined",color:"primary",sx:{fontWeight:600}},y)):n(P,{variant:"body2",fontWeight:700,children:V.product_variant?`${U(V.product_name)} ${V.product_variant}`:U(V.product_name)})})]})]})]})}),n(ur,{title:"Production by Product",subtitle:`${K.length} product(s)`}),K.map((f,y)=>{const E=ve(m,f),G=ve(w,f),H=f.product_variant?`${U(f.product_name)} · ${f.product_variant}`:U(f.product_name);return g(j,{mb:3,sx:{borderLeft:3,borderLeftColor:"primary.main",pl:2},children:[g(j,{display:"flex",alignItems:"center",gap:1,mb:1,children:[n(xr,{size:"small",label:H,color:"primary",sx:{fontWeight:700}}),g(P,{variant:"caption",color:"text.secondary",children:["Planned: ",_e(f.planned_quantity)," · Completed: ",_e(f.completed_quantity)]})]}),n(P,{variant:"caption",color:"text.secondary",fontWeight:700,sx:{textTransform:"uppercase",letterSpacing:"0.04em",mb:.5,display:"block"},children:"Material Consumption"}),n(We,{component:Se,variant:"outlined",sx:{borderRadius:2,mb:1.5},children:g($e,{size:"small",children:[n(Ye,{children:g(te,{sx:{"& th":{fontWeight:700,bgcolor:"action.hover"}},children:[n(c,{children:"Grade"}),n(c,{children:"Shift"}),n(c,{children:"Date"}),n(c,{align:"right",children:"Usage Qty"}),n(c,{align:"right",children:"Landed Cost"}),n(c,{align:"right",children:"Material Cost"})]})}),n(Oe,{children:G.length===0?n(hr,{span:6}):G.map((F,L)=>g(te,{hover:!0,children:[n(c,{children:U(F.grade_name)}),n(c,{children:U(F.shift_name)}),n(c,{children:nt(F.production_date)}),g(c,{align:"right",children:[_e(F.total_usage_quantity)," ",F.unit??""]}),n(c,{align:"right",children:Ce(F.avg_landed_cost)}),n(c,{align:"right",children:Ce(F.material_usage_cost)})]},L))})]})}),n(P,{variant:"caption",color:"text.secondary",fontWeight:700,sx:{textTransform:"uppercase",letterSpacing:"0.04em",mb:.5,display:"block"},children:"Hourly Production Records"}),n(We,{component:Se,variant:"outlined",sx:{borderRadius:2},children:g($e,{size:"small",children:[n(Ye,{children:g(te,{sx:{"& th":{fontWeight:700,bgcolor:"action.hover"}},children:[n(c,{children:"Shift"}),n(c,{children:"Date"}),n(c,{children:"Produced Qty"}),n(c,{children:"Rejected Qty"}),n(c,{children:"Machine"}),n(c,{children:"Remarks"})]})}),n(Oe,{children:E.length===0?n(hr,{span:7}):E.map((F,L)=>g(te,{hover:!0,children:[n(c,{children:U(F.shift_name)}),n(c,{children:nt(F.production_date)}),n(c,{children:_e(F.produced_quantity)}),n(c,{children:_e(F.rejected_quantity)}),n(c,{children:U(F.machine_name)}),n(c,{children:U(F.remarks)})]},L))})]})})]},f.id??y)}),n(ur,{title:"Utility Charges",subtitle:`${ye.length} charge line(s)`}),n(We,{component:Se,variant:"outlined",sx:{mb:3,borderRadius:2},children:g($e,{size:"small",children:[n(Ye,{children:g(te,{sx:{"& th":{fontWeight:700,bgcolor:"action.hover"}},children:[n(c,{children:"Utility"}),n(c,{children:"Shift"}),n(c,{children:"Date"}),n(c,{align:"right",children:"Quantity"}),n(c,{children:"UOM"}),n(c,{align:"right",children:"Unit Rate"}),n(c,{align:"right",children:"Amount"})]})}),n(Oe,{children:ye.length===0?n(hr,{span:7}):ye.map((f,y)=>g(te,{hover:!0,children:[n(c,{children:U(f.utility_type)}),n(c,{children:U(f.shift_name)}),n(c,{children:nt(f.production_date)}),n(c,{align:"right",children:_e(f.quantity)}),n(c,{children:U(f.uom)}),n(c,{align:"right",children:Ce(f.unit_rate)}),n(c,{align:"right",children:Ce(f.total_amount)})]},y))})]})})]}):n(P,{color:"text.secondary",sx:{py:4,textAlign:"center"},children:"Select a Job Card and click Run to view its consolidated report."})});yn.displayName="JobCardConsolidatedReport";const ur=({title:e,subtitle:t})=>g(j,{display:"flex",alignItems:"baseline",gap:1.5,mb:1,mt:1,children:[n(P,{variant:"subtitle2",fontWeight:700,color:"primary.main",sx:{textTransform:"uppercase",letterSpacing:"0.04em"},children:e}),t&&n(P,{variant:"caption",color:"text.secondary",children:t})]}),hr=({span:e})=>n(te,{children:n(c,{colSpan:e,align:"center",sx:{color:"text.disabled",py:3},children:"No records"})}),Na=e=>`₹ ${Number(e??0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,Ze=e=>Number(e??0).toLocaleString("en-IN"),ke=e=>e==null||e===""?"-":e,lt=e=>{const t=Number(e);return isNaN(t)?0:t},Ma=e=>{if(!e)return"-";const t=new Date(e);return isNaN(t.getTime())?"-":t.toLocaleDateString("en-IN",{day:"2-digit",month:"2-digit",year:"numeric"})},bn=S.forwardRef(({vehicleId:e,vehicleLabel:t,fromDate:a,toDate:i,reloadKey:l,onReadyChange:s},u)=>{const[D]=on(),[M]=sn(),[p,b]=S.useState(null),[z,ne]=S.useState([]),[N,v]=S.useState(!1),[V,ye]=S.useState(!1),[w,T]=S.useState(null);S.useEffect(()=>{if(e==null)return;let y=!1;return(async()=>{var G;ye(!0),T(null),v(!1),b(null),ne([]);const E={vehicleId:e,fromDate:a||null,toDate:i||null};try{const[H,F]=await Promise.all([D({page:0,size:5,payload:E}).unwrap(),M({page:0,size:1e3,payload:E}).unwrap()]);if(y)return;const L=Array.isArray(H==null?void 0:H.data)?H.data:H!=null&&H.data?[H.data]:[],W=Array.isArray(F==null?void 0:F.data)?F.data:F!=null&&F.data?[F.data]:[];b(L[0]??null),ne(W),v(!0)}catch(H){y||T(((G=H==null?void 0:H.data)==null?void 0:G.error)||(H==null?void 0:H.error)||"Failed to load vehicle fuel report")}finally{y||ye(!1)}})(),()=>{y=!0}},[l]);const K=(p==null?void 0:p.trip_count)!=null?lt(p.trip_count):z.length,m=(p==null?void 0:p.total_distance)!=null?lt(p.total_distance):z.reduce((y,E)=>y+lt(E.distance),0),Ie=(p==null?void 0:p.total_fuel)!=null?lt(p.total_fuel):z.reduce((y,E)=>y+lt(E.fuel_added),0),be=(p==null?void 0:p.total_fuel_cost)!=null?lt(p.total_fuel_cost):z.reduce((y,E)=>y+lt(E.fuel_cost),0),Be=(p==null?void 0:p.avg_mileage)!=null?lt(p.avg_mileage):Ie>0?m/Ie:0,Fe=m>0?be/m:0,ve=(p==null?void 0:p.vehicle_number)||t||"-",X=p==null?void 0:p.make_model,Le=p==null?void 0:p.driver_name,at=[{label:"Total Trips",value:Ze(K),color:"#1565c0"},{label:"Total Distance (km)",value:Ze(m),color:"#2e7d32"},{label:"Total Fuel (L)",value:Ze(Ie),color:"#ed6c02"},{label:"Total Fuel Cost",value:Na(be),color:"#c62828"},{label:"Avg Mileage (km/L)",value:Be.toFixed(2),color:"#0288d1"},{label:"Fuel Cost / km",value:Na(Fe),color:"#7b1fa2"}];S.useEffect(()=>{s==null||s(N&&!V)},[N,V,s]);const f=()=>{const y=L=>String(L??"-").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),E=at.map(L=>`
          <div class="kpi" style="border-left-color:${L.color}">
            <div class="kpi-label">${y(L.label)}</div>
            <div class="kpi-value" style="color:${L.color}">${y(L.value)}</div>
          </div>`).join(""),G=[{label:"Vehicle No",value:ke(ve)},{label:"Make / Model",value:ke(X)},{label:"Driver(s)",value:ke(Le)}].map(L=>`
          <div class="info-cell">
            <div class="info-label">${y(L.label)}</div>
            <div class="info-value">${y(L.value)}</div>
          </div>`).join(""),H=z.map(L=>`
        <tr>
          <td>${y(Ma(L.trip_date))}</td>
          <td>${y(`${ke(L.from_location)} → ${ke(L.to_location)}`)}</td>
          <td>${y(ke(L.driver_name))}</td>
          <td class="text-right">${y(L.start_km!=null?Ze(L.start_km):"-")}</td>
          <td class="text-right">${y(L.end_km!=null?Ze(L.end_km):"-")}</td>
          <td class="text-right">${y(Ze(L.distance))}</td>
          <td class="text-right">${y(Ze(L.fuel_added))}</td>
          <td class="text-right">${y(Na(L.fuel_cost))}</td>
          <td class="text-right">${y(lt(L.mileage).toFixed(2))}</td>
          <td>${y(ke(L.status))}</td>
        </tr>`),F=H.length>0?H.join(""):'<tr><td colspan="10" class="empty">No records</td></tr>';return`
      <!DOCTYPE html>
      <html>
        <head>
          <title>Vehicle Fuel Report - ${y(ke(ve))}</title>
          <style>
            @media print { @page { size: A4 landscape; margin: 1cm; } .no-print { display:none; } }
            * { margin: 0; padding: 0; box-sizing: border-box; }
            body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; padding: 20px; color: #333; background: #fff; }
            .print-header { display:flex; align-items:center; justify-content:space-between; margin-bottom:20px; border-bottom:3px solid #1976d2; padding-bottom:12px; }
            .company-name { font-size:22px; font-weight:700; color:#1976d2; text-transform:uppercase; }
            .print-header-center { flex:1; text-align:center; }
            .print-header h1 { font-size:22px; color:#1976d2; font-weight:700; }
            .print-header .meta { font-size:13px; color:#666; margin-top:4px; }
            .kpi-grid { display:flex; flex-wrap:wrap; gap:8px; margin-bottom:20px; }
            .kpi { flex:1 1 140px; min-width:140px; border:1px solid #e0e0e0; border-left:4px solid #1976d2; border-radius:6px; padding:8px 10px; }
            .kpi-label { font-size:11px; color:#666; }
            .kpi-value { font-size:15px; font-weight:800; line-height:1.3; }
            .section-title { font-size:14px; color:#1976d2; text-transform:uppercase; letter-spacing:0.04em; margin:18px 0 8px; }
            .section-sub { font-size:11px; color:#888; font-weight:400; text-transform:none; letter-spacing:0; }
            .info-card { display:flex; flex-wrap:wrap; gap:16px; border:1px solid #e0e0e0; border-radius:6px; padding:12px; margin-bottom:6px; }
            .info-cell { flex:1 1 160px; }
            .info-label { font-size:11px; color:#666; }
            .info-value { font-size:13px; font-weight:700; }
            table { width:100%; border-collapse:collapse; font-size:11px; }
            thead { background-color:#1976d2; color:#fff; }
            th { padding:8px 6px; text-align:left; font-weight:600; border:1px solid #1565c0; }
            td { padding:6px; border:1px solid #e0e0e0; }
            tbody tr:nth-child(even) { background-color:#f9f9f9; }
            .text-right { text-align:right; }
            .empty { text-align:center; color:#999; padding:16px; }
            .print-footer { margin-top:24px; padding-top:12px; border-top:2px solid #e0e0e0; text-align:center; font-size:11px; color:#666; }
          </style>
        </head>
        <body>
          <div class="print-header">
            <div class="company-name">PR BLOCKS</div>
            <div class="print-header-center">
              <h1>Vehicle Fuel Report</h1>
              <div class="meta"><strong>Vehicle:</strong> ${y(ke(ve))}${X?` · ${y(X)}`:""}</div>
              <div class="meta"><strong>Period:</strong> ${y(Ma(a))} to ${y(Ma(i))}</div>
              <div class="meta"><strong>Generated:</strong> ${y(new Date().toLocaleString("en-IN",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"}))}</div>
            </div>
          </div>

          <div class="kpi-grid">${E}</div>

          <h2 class="section-title">Vehicle Information</h2>
          <div class="info-card">${G}</div>

          <h2 class="section-title">Fuel &amp; Trip Records <span class="section-sub">${z.length} record(s)</span></h2>
          <table>
            <thead>
              <tr>
                <th>Date</th>
                <th>Route</th>
                <th>Driver</th>
                <th class="text-right">Start KM</th>
                <th class="text-right">End KM</th>
                <th class="text-right">Distance</th>
                <th class="text-right">Fuel (L)</th>
                <th class="text-right">Fuel Cost</th>
                <th class="text-right">Mileage</th>
                <th>Status</th>
              </tr>
            </thead>
            <tbody>${F}</tbody>
          </table>

          <div class="print-footer">
            <p>PR BLOCKS — Vehicle Fuel Report</p>
          </div>
        </body>
      </html>`};return S.useImperativeHandle(u,()=>({print:()=>{if(!N)return;const y=window.open("","_blank","width=1200,height=800");y&&(y.document.write(f()),y.document.close(),y.focus(),setTimeout(()=>y.print(),300))}})),V?n(j,{display:"flex",justifyContent:"center",alignItems:"center",py:8,children:n(st,{})}):w?n(P,{color:"error",sx:{py:4,textAlign:"center"},children:w}):N?g(j,{children:[n(Y,{container:!0,spacing:1.5,sx:{mb:3},children:at.map(y=>n(Y,{item:!0,xs:6,sm:4,md:2,children:g(we,{variant:"outlined",sx:{p:1.5,borderLeft:4,borderLeftColor:y.color,borderRadius:2,height:"100%"},children:[n(P,{variant:"caption",color:"text.secondary",sx:{fontWeight:500},children:y.label}),n(P,{variant:"subtitle1",fontWeight:800,sx:{color:y.color,lineHeight:1.25},children:y.value})]})},y.label))}),n(Bi,{title:"Vehicle Information"}),g(we,{variant:"outlined",sx:{p:2,mb:3,borderRadius:2,display:"flex",alignItems:"center",gap:2},children:[n(j,{sx:{width:56,height:56,borderRadius:2,bgcolor:"primary.50",color:"primary.main",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:n(xo,{fontSize:"large"})}),n(Y,{container:!0,spacing:2,children:[{label:"Vehicle No",value:ke(ve)},{label:"Make / Model",value:ke(X)},{label:"Driver(s)",value:ke(Le)}].map(y=>g(Y,{item:!0,xs:6,sm:4,children:[n(P,{variant:"caption",color:"text.secondary",sx:{fontWeight:500},children:y.label}),n(P,{variant:"body2",fontWeight:700,children:y.value})]},y.label))})]}),n(Bi,{title:"Fuel & Trip Records",subtitle:`${z.length} record(s)`}),n(We,{component:Se,variant:"outlined",sx:{mb:1,borderRadius:2},children:g($e,{size:"small",children:[n(Ye,{children:g(te,{sx:{"& th":{fontWeight:700,bgcolor:"action.hover"}},children:[n(c,{children:"Date"}),n(c,{children:"Driver"}),n(c,{align:"right",children:"Start KM"}),n(c,{align:"right",children:"End KM"}),n(c,{align:"right",children:"Distance"}),n(c,{align:"right",children:"Fuel (L)"}),n(c,{align:"right",children:"Fuel Cost"}),n(c,{align:"right",children:"Mileage"}),n(c,{children:"Status"})]})}),n(Oe,{children:z.length===0?n(Vo,{span:10}):z.map((y,E)=>g(te,{hover:!0,children:[n(c,{children:Ma(y.trip_date)}),n(c,{children:ke(y.driver_name)}),n(c,{align:"right",children:y.start_km!=null?Ze(y.start_km):"-"}),n(c,{align:"right",children:y.end_km!=null?Ze(y.end_km):"-"}),n(c,{align:"right",children:Ze(y.distance)}),n(c,{align:"right",children:Ze(y.fuel_added)}),n(c,{align:"right",children:Na(y.fuel_cost)}),n(c,{align:"right",children:lt(y.mileage).toFixed(2)}),n(c,{children:ke(y.status)})]},E))})]})})]}):n(P,{color:"text.secondary",sx:{py:4,textAlign:"center"},children:"Select a vehicle and click Run to view its fuel report."})});bn.displayName="VehicleFuelReport";const Bi=({title:e,subtitle:t})=>g(j,{display:"flex",alignItems:"baseline",gap:1.5,mb:1,mt:1,children:[n(P,{variant:"subtitle2",fontWeight:700,color:"primary.main",sx:{textTransform:"uppercase",letterSpacing:"0.04em"},children:e}),t&&n(P,{variant:"caption",color:"text.secondary",children:t})]}),Vo=({span:e})=>n(te,{children:n(c,{colSpan:e,align:"center",sx:{color:"text.disabled",py:3},children:"No records"})}),Ra=e=>`₹ ${Number(e??0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,mr=e=>Number(e??0).toLocaleString("en-IN"),zt=e=>{if(!e)return"-";const t=new Date(e);return isNaN(t.getTime())?"-":t.toLocaleDateString("en-IN",{day:"2-digit",month:"2-digit",year:"numeric"})},fe=e=>e==null||e===""?"-":e,Go=({open:e,machine:t,onClose:a})=>{const i=t==null?void 0:t.machineId,l=!e||i==null,{data:s=[],isFetching:u}=dn({machineId:i},{skip:l}),{data:D=[],isFetching:M}=cn({machineId:i},{skip:l}),{data:p=[],isFetching:b}=un({machineId:i},{skip:l}),z=[{label:"Machine Code",value:fe(t==null?void 0:t.machineCode)},{label:"Type",value:fe(t==null?void 0:t.machineType)},{label:"Capacity",value:fe(t==null?void 0:t.capacity)},{label:"Condition",value:fe(t==null?void 0:t.condition)},{label:"Location",value:fe(t==null?void 0:t.location)},{label:"Operation",value:fe(t==null?void 0:t.operation)},{label:"Cyclic Time",value:fe(t==null?void 0:t.cyclicTime)},{label:"Purchase Date",value:zt(t==null?void 0:t.purchaseDate)},{label:"Status",value:fe(t==null?void 0:t.status)}],ne=[{label:"Total Produced",value:mr(t==null?void 0:t.totalProduced),color:"success.main"},{label:"Total Rejected",value:mr(t==null?void 0:t.totalRejected),color:"error.main"},{label:"Net Produced",value:mr(t==null?void 0:t.netProduced),color:"primary.main"}];return g(pn,{open:e,onClose:a,maxWidth:"lg",fullWidth:!0,children:[g(nn,{sx:{background:"linear-gradient(135deg, #1565c0 0%, #1976d2 45%, #42a5f5 100%)",color:"common.white",display:"flex",alignItems:"center",gap:1.5,pr:6},children:[n(fn,{}),g(j,{children:[n(P,{variant:"h6",fontWeight:800,lineHeight:1.1,children:(t==null?void 0:t.machineName)||"Machine Detail"}),g(P,{variant:"caption",sx:{opacity:.9},children:[t!=null&&t.machineCode?`${t.machineCode}`:"",t!=null&&t.machineType?` · ${t.machineType}`:""]})]}),n(Zt,{onClick:a,sx:{position:"absolute",right:8,top:8,color:"common.white"},children:n(mn,{})})]}),g(gn,{dividers:!0,sx:{bgcolor:"grey.50"},children:[n(Y,{container:!0,spacing:2,sx:{mb:2},children:ne.map(N=>n(Y,{item:!0,xs:4,children:g(we,{variant:"outlined",sx:{p:1.5,borderLeft:3,borderLeftColor:N.color,borderRadius:2},children:[n(P,{variant:"caption",color:"text.secondary",sx:{fontWeight:500},children:N.label}),n(P,{variant:"subtitle1",fontWeight:700,sx:{color:N.color,lineHeight:1.3},children:N.value})]})},N.label))}),n(Ca,{title:"Machine Details"}),n(we,{variant:"outlined",sx:{p:2,mb:3,borderRadius:2},children:n(Y,{container:!0,spacing:2,children:z.map(N=>g(Y,{item:!0,xs:6,sm:4,md:3,children:[n(P,{variant:"caption",color:"text.secondary",sx:{fontWeight:500},children:N.label}),n(P,{variant:"body2",fontWeight:600,children:N.value})]},N.label))})}),n(Ca,{title:"Service Records",subtitle:`${s.length} record(s)`,loading:u}),n(We,{component:Se,variant:"outlined",sx:{mb:3,borderRadius:2},children:g($e,{size:"small",children:[n(Ye,{children:g(te,{sx:{"& th":{fontWeight:700,bgcolor:"action.hover"}},children:[n(c,{children:"Service Type"}),n(c,{children:"Service Date"}),n(c,{children:"Next Service"}),n(c,{children:"Technician / Engineer"}),n(c,{children:"Problem"}),n(c,{align:"right",children:"Cost"}),n(c,{children:"Remarks"})]})}),n(Oe,{children:s.length===0?n(fr,{span:7}):s.map((N,v)=>g(te,{hover:!0,children:[n(c,{children:fe(N.serviceType)}),n(c,{children:zt(N.serviceDate)}),n(c,{children:zt(N.nextServiceDate)}),n(c,{children:fe(N.technicianName??N.engineerName)}),n(c,{children:fe(N.problemDescription??N.issueDescription??N.description)}),n(c,{align:"right",children:Ra(N.serviceCost)}),n(c,{children:fe(N.remarks)})]},N.id??v))})]})}),n(Ca,{title:"Parts Replaced",subtitle:`${D.length} part(s)`,loading:M}),n(We,{component:Se,variant:"outlined",sx:{mb:3,borderRadius:2},children:g($e,{size:"small",children:[n(Ye,{children:g(te,{sx:{"& th":{fontWeight:700,bgcolor:"action.hover"}},children:[n(c,{children:"Date"}),n(c,{children:"Part Name"}),n(c,{children:"Part No"}),n(c,{align:"right",children:"Qty"}),n(c,{align:"right",children:"Unit Cost"}),n(c,{align:"right",children:"Total Cost"}),n(c,{children:"Vendor"}),n(c,{children:"Technician"})]})}),n(Oe,{children:D.length===0?n(fr,{span:8}):D.map((N,v)=>g(te,{hover:!0,children:[n(c,{children:zt(N.issueDate)}),n(c,{children:fe(N.partName)}),n(c,{children:fe(N.partNumber)}),n(c,{align:"right",children:fe(N.quantity)}),n(c,{align:"right",children:Ra(N.unitCost)}),n(c,{align:"right",children:Ra(N.totalCost)}),n(c,{children:fe(N.vendor)}),n(c,{children:fe(N.technicianName)})]},N.id??v))})]})}),n(Ca,{title:"Insurance Policies",subtitle:`${p.length} polic(ies)`,loading:b}),n(We,{component:Se,variant:"outlined",sx:{mb:1,borderRadius:2},children:g($e,{size:"small",children:[n(Ye,{children:g(te,{sx:{"& th":{fontWeight:700,bgcolor:"action.hover"}},children:[n(c,{children:"Policy No"}),n(c,{children:"Provider"}),n(c,{children:"Valid From"}),n(c,{children:"Valid Upto"}),n(c,{align:"right",children:"Premium"}),n(c,{children:"Coverage"}),n(c,{children:"Remarks"})]})}),n(Oe,{children:p.length===0?n(fr,{span:7}):p.map((N,v)=>g(te,{hover:!0,children:[n(c,{children:fe(N.policyNumber)}),n(c,{children:fe(N.provider)}),n(c,{children:zt(N.validFrom)}),n(c,{children:zt(N.validUpto)}),n(c,{align:"right",children:Ra(N.premium)}),n(c,{children:fe(N.coverage)}),n(c,{children:fe(N.remarks)})]},N.id??v))})]})})]})]})},Ca=({title:e,subtitle:t,loading:a})=>g(j,{display:"flex",alignItems:"baseline",gap:1.5,mb:1,children:[n(P,{variant:"subtitle2",fontWeight:700,color:"primary.main",sx:{textTransform:"uppercase",letterSpacing:"0.04em"},children:e}),t&&n(P,{variant:"caption",color:"text.secondary",children:t}),a&&n(st,{size:14})]}),fr=({span:e})=>n(te,{children:n(c,{colSpan:e,align:"center",sx:{color:"text.disabled",py:3},children:"No records"})}),le=e=>`₹ ${Number(e??0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,De=e=>Number(e??0).toLocaleString("en-IN"),B=e=>e==null||e===""?"-":e,Ct=e=>{const t=Number(e);return isNaN(t)?0:t},Gt=e=>{if(!e)return null;const t=new Date(e);return isNaN(t.getTime())?null:t},ge=e=>{const t=Gt(e);return t?t.toLocaleDateString("en-IN",{day:"2-digit",month:"2-digit",year:"numeric"}):"-"},xn=S.forwardRef(({machineName:e,fromDate:t,toDate:a,plantId:i,reloadKey:l,onReadyChange:s},u)=>{const[D,{isLoading:M}]=Bl(),[p,b]=S.useState(null),[z,ne]=S.useState(null);S.useEffect(()=>{if(!e)return;let h=!1;return(async()=>{var O;ne(null);try{const Re=await D({payload:{machineName:e,fromDate:t||null,toDate:a||null,plantId:i??null}}).unwrap();h||b(Re)}catch(Re){h||ne(((O=Re==null?void 0:Re.data)==null?void 0:O.error)||(Re==null?void 0:Re.error)||"Failed to load machine report")}})(),()=>{h=!0}},[l]);const N=(p==null?void 0:p.machine)??{},v=N==null?void 0:N.machineId,V=(p==null?void 0:p.production)??[],ye=(p==null?void 0:p.productionSummary)??{},w=v==null,{data:T=[],isFetching:K}=dn({machineId:v},{skip:w}),{data:m=[],isFetching:Ie}=cn({machineId:v},{skip:w}),{data:be=[],isFetching:Be}=un({machineId:v},{skip:w}),Fe=T.reduce((h,O)=>h+Ct(O.serviceCost),0),ve=T.length,X=T.map(h=>Gt(h.serviceDate)).filter(Boolean).sort((h,O)=>O.getTime()-h.getTime())[0],Le=new Date,at=T.map(h=>Gt(h.nextServiceDate)).filter(h=>h&&h.getTime()>=Le.getTime()),f=T.map(h=>Gt(h.nextServiceDate)).filter(Boolean),y=at.sort((h,O)=>h.getTime()-O.getTime())[0]??f.sort((h,O)=>O.getTime()-h.getTime())[0],E=m.reduce((h,O)=>h+Ct(O.totalCost),0),G=m.reduce((h,O)=>h+Ct(O.quantity),0),H=be.reduce((h,O)=>h+Ct(O.premium),0),F=be.map(h=>Gt(h.validUpto)).filter(Boolean).sort((h,O)=>O.getTime()-h.getTime())[0],L=!!F&&F.getTime()>=Le.getTime(),W=Ct(ye.totalProductionCost),Ve=W+Fe+E+H,rt=h=>{const O=Gt(h);return O?O.getTime()>=Le.getTime()?{label:"Active",color:"success"}:{label:"Expired",color:"error"}:{label:"-",color:"default"}},ht=[{label:"Total Produced",value:De(ye.totalProduced),color:"#2e7d32"},{label:"Total Rejected",value:De(ye.totalRejected),color:"#d32f2f"},{label:"Efficiency %",value:`${Ct(ye.efficiency).toFixed(2)}%`,color:"#0288d1"},{label:"Production Cost",value:le(W),color:"#7b1fa2"},{label:"Maintenance Cost",value:le(Fe),color:"#ed6c02"},{label:"Spare Parts Cost",value:le(E),color:"#5d4037"},{label:"Insurance Cost",value:le(H),color:"#00838f"},{label:"Grand Total Cost",value:le(Ve),color:"#c62828"},{label:"Last Service",value:X?ge(X):"-",color:"#1565c0"},{label:"Next Service Due",value:y?ge(y):"-",color:"#1565c0"},{label:"Insurance Expiry",value:F?ge(F):"-",color:L?"#2e7d32":"#d32f2f"}];S.useEffect(()=>{s==null||s(!!p&&!M)},[p,M,s]);const Nt=()=>{const h=k=>String(k??"-").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),O=ht.map(k=>`
          <div class="kpi" style="border-left-color:${k.color}">
            <div class="kpi-label">${h(k.label)}</div>
            <div class="kpi-value" style="color:${k.color}">${h(k.value)}</div>
          </div>`).join(""),Re=[{label:"Machine Code",value:B(N.machineCode)},{label:"Machine Name",value:B(N.machineName)},{label:"Machine Type",value:B(N.machineType)},{label:"Capacity",value:B(N.capacity)},{label:"Location",value:B(N.location)},{label:"Status",value:B(N.status)}].map(k=>`
          <div class="info-cell">
            <div class="info-label">${h(k.label)}</div>
            <div class="info-value">${h(k.value)}</div>
          </div>`).join(""),Et=(k,Mt,er,pa)=>`
      <h2 class="section-title">${h(k)} <span class="section-sub">${h(Mt)}</span></h2>
      <table>
        <thead>
          <tr>${er.map(tr=>`<th class="${tr.align==="right"?"text-right":""}">${h(tr.label)}</th>`).join("")}</tr>
        </thead>
        <tbody>
          ${pa.length>0?pa.join(""):`<tr><td colspan="${er.length}" class="empty">No records</td></tr>`}
        </tbody>
      </table>`,Xr=V.map(k=>`
        <tr>
          <td>${h(B(k.jobCardNo))}</td>
          <td>${h(ge(k.productionDate))}</td>
          <td>${h(B(k.shiftName))}</td>
          <td>${h(k.productVariant?`${B(k.productName)} (${k.productVariant})`:B(k.productName))}</td>
          <td class="text-right">${h(De(k.plannedQty))}</td>
          <td class="text-right">${h(De(k.producedQty))}</td>
          <td class="text-right">${h(De(k.rejectedQty))}</td>
          <td class="text-right">${h(De(k.balanceQty))}</td>
          <td class="text-right">${h(le(k.productionCost))}</td>
          <td class="text-right">${h(Ct(k.runningHours).toFixed(2))}</td>
        </tr>`),Za=T.map(k=>`
        <tr>
          <td>${h(ge(k.serviceDate))}</td>
          <td>${h(B(k.serviceType))}</td>
          <td>${h(B(k.serviceDescription??k.problemDescription??k.issueDescription??k.description))}</td>
          <td>${h(B(k.serviceProvider??k.technicianName??k.engineerName))}</td>
          <td class="text-right">${h(le(k.serviceCost))}</td>
          <td>${h(ge(k.nextServiceDate))}</td>
        </tr>`),ei=m.map(k=>`
        <tr>
          <td>${h(ge(k.issueDate??k.replacementDate))}</td>
          <td>${h(B(k.partName))}</td>
          <td>${h(B(k.partNumber))}</td>
          <td class="text-right">${h(De(k.quantity))}</td>
          <td class="text-right">${h(le(k.unitCost))}</td>
          <td class="text-right">${h(le(k.totalCost))}</td>
          <td>${h(B(k.reason??k.remarks))}</td>
        </tr>`),Ka=be.map(k=>{const Mt=rt(k.validUpto);return`
        <tr>
          <td>${h(B(k.policyNumber))}</td>
          <td>${h(B(k.provider))}</td>
          <td>${h(ge(k.validFrom))}</td>
          <td>${h(ge(k.validUpto))}</td>
          <td class="text-right">${h(le(k.premium))}</td>
          <td>${h(Mt.label)}</td>
        </tr>`}),ta=k=>`
      <div class="summary-strip">
        ${k.map(Mt=>`
          <div class="summary-cell">
            <div class="summary-label">${h(Mt.label)}</div>
            <div class="summary-value">${h(Mt.value)}</div>
          </div>`).join("")}
      </div>`,Xa=[{label:"Total Production Cost",value:W,color:"#7b1fa2"},{label:"Total Maintenance Cost",value:Fe,color:"#ed6c02"},{label:"Total Spare Parts Cost",value:E,color:"#5d4037"},{label:"Total Insurance Cost",value:H,color:"#00838f"}].map(k=>`
          <div class="cost-cell">
            <div class="info-label">${h(k.label)}</div>
            <div class="cost-value" style="color:${k.color}">${h(le(k.value))}</div>
          </div>`).join("");return`
      <!DOCTYPE html>
      <html>
        <head>
          <title>Machine Consolidated Report - ${h(B(N.machineName))}</title>
          <style>
            @media print { @page { size: A4 landscape; margin: 1cm; } .no-print { display:none; } }
            * { margin: 0; padding: 0; box-sizing: border-box; }
            body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; padding: 20px; color: #333; background: #fff; }
            .print-header { display:flex; align-items:center; justify-content:space-between; margin-bottom:20px; border-bottom:3px solid #1976d2; padding-bottom:12px; }
            .company-name { font-size:22px; font-weight:700; color:#1976d2; text-transform:uppercase; }
            .print-header-center { flex:1; text-align:center; }
            .print-header h1 { font-size:22px; color:#1976d2; font-weight:700; }
            .print-header .meta { font-size:13px; color:#666; margin-top:4px; }
            .kpi-grid { display:flex; flex-wrap:wrap; gap:8px; margin-bottom:20px; }
            .kpi { flex:1 1 140px; min-width:140px; border:1px solid #e0e0e0; border-left:4px solid #1976d2; border-radius:6px; padding:8px 10px; }
            .kpi-label { font-size:11px; color:#666; }
            .kpi-value { font-size:15px; font-weight:800; line-height:1.3; }
            .section-title { font-size:14px; color:#1976d2; text-transform:uppercase; letter-spacing:0.04em; margin:18px 0 8px; }
            .section-sub { font-size:11px; color:#888; font-weight:400; text-transform:none; letter-spacing:0; }
            .info-card { display:flex; flex-wrap:wrap; gap:16px; border:1px solid #e0e0e0; border-radius:6px; padding:12px; }
            .info-cell { flex:1 1 140px; }
            .info-label { font-size:11px; color:#666; }
            .info-value { font-size:13px; font-weight:700; }
            table { width:100%; border-collapse:collapse; font-size:11px; }
            thead { background-color:#1976d2; color:#fff; }
            th { padding:8px 6px; text-align:left; font-weight:600; border:1px solid #1565c0; }
            td { padding:6px; border:1px solid #e0e0e0; }
            tbody tr:nth-child(even) { background-color:#f9f9f9; }
            .text-right { text-align:right; }
            .empty { text-align:center; color:#999; padding:16px; }
            .summary-strip { display:flex; flex-wrap:wrap; gap:24px; padding:10px 14px; margin-top:8px; background:#f5f5f5; border:1px solid #e0e0e0; border-radius:6px; }
            .summary-label { font-size:11px; color:#666; }
            .summary-value { font-size:13px; font-weight:700; }
            .cost-card { border:1px solid #e0e0e0; border-radius:6px; padding:14px; }
            .cost-grid { display:flex; flex-wrap:wrap; gap:24px; }
            .cost-cell { flex:1 1 160px; }
            .cost-value { font-size:15px; font-weight:700; }
            .grand-total { display:flex; align-items:center; justify-content:space-between; margin-top:14px; padding-top:12px; border-top:1px solid #e0e0e0; }
            .grand-total .label { font-size:15px; font-weight:700; color:#555; }
            .grand-total .value { font-size:22px; font-weight:800; color:#c62828; }
            .print-footer { margin-top:24px; padding-top:12px; border-top:2px solid #e0e0e0; text-align:center; font-size:11px; color:#666; }
          </style>
        </head>
        <body>
          <div class="print-header">
            <div class="company-name">PR BLOCKS</div>
            <div class="print-header-center">
              <h1>Machine Consolidated Report</h1>
              <div class="meta"><strong>Machine:</strong> ${h(B(N.machineName))}${N.machineCode?` (${h(N.machineCode)})`:""}</div>
              <div class="meta"><strong>Period:</strong> ${h(ge(t))} to ${h(ge(a))}</div>
              <div class="meta"><strong>Generated:</strong> ${h(new Date().toLocaleString("en-IN",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"}))}</div>
            </div>
          </div>

          <div class="kpi-grid">${O}</div>

          <h2 class="section-title">Machine Information</h2>
          <div class="info-card">${Re}</div>

          ${Et("Production Details",`${V.length} shift record(s)`,[{label:"Job Card No"},{label:"Production Date"},{label:"Shift"},{label:"Product"},{label:"Planned",align:"right"},{label:"Produced",align:"right"},{label:"Rejected",align:"right"},{label:"Balance",align:"right"},{label:"Production Cost",align:"right"},{label:"Running Hrs",align:"right"}],Xr)}
          ${ta([{label:"Total Planned",value:De(ye.totalPlanned)},{label:"Total Produced",value:De(ye.totalProduced)},{label:"Total Rejected",value:De(ye.totalRejected)},{label:"Efficiency %",value:`${Ct(ye.efficiency).toFixed(2)}%`},{label:"Total Production Cost",value:le(W)}])}

          ${Et("Service & Maintenance",`${ve} record(s)`,[{label:"Service Date"},{label:"Service Type"},{label:"Description"},{label:"Service Provider"},{label:"Service Cost",align:"right"},{label:"Next Service Date"}],Za)}
          ${ta([{label:"Total Maintenance Count",value:De(ve)},{label:"Total Maintenance Cost",value:le(Fe)},{label:"Last Service Date",value:X?ge(X):"-"},{label:"Next Service Due",value:y?ge(y):"-"}])}

          ${Et("Spare Parts Replacement",`${m.length} part(s)`,[{label:"Replacement Date"},{label:"Part Name"},{label:"Part Number"},{label:"Qty Replaced",align:"right"},{label:"Unit Cost",align:"right"},{label:"Total Cost",align:"right"},{label:"Replacement Reason"}],ei)}
          ${ta([{label:"Total Parts Replaced",value:De(G)},{label:"Total Spare Parts Cost",value:le(E)}])}

          ${Et("Insurance Details",`${be.length} polic(ies)`,[{label:"Policy Number"},{label:"Insurance Provider"},{label:"Start Date"},{label:"Expiry Date"},{label:"Premium",align:"right"},{label:"Status"}],Ka)}
          ${ta([{label:"Total Insurance Cost",value:le(H)},{label:"Insurance Expiry",value:F?ge(F):"-"},{label:"Insurance Status",value:be.length===0?"-":L?"Active":"Expired"}])}

          <h2 class="section-title">Cost Analysis</h2>
          <div class="cost-card">
            <div class="cost-grid">${Xa}</div>
            <div class="grand-total">
              <span class="label">Grand Total Machine Cost</span>
              <span class="value">${h(le(Ve))}</span>
            </div>
            <div class="meta" style="font-size:11px;color:#888;margin-top:6px;">
              Grand Total = Production Cost + Maintenance Cost + Spare Parts Cost + Insurance Cost.
            </div>
          </div>

          <div class="print-footer">
            <p>PR BLOCKS — Machine Consolidated Report</p>
          </div>
        </body>
      </html>`};return S.useImperativeHandle(u,()=>({print:()=>{if(!p)return;const h=window.open("","_blank","width=1200,height=800");h&&(h.document.write(Nt()),h.document.close(),setTimeout(()=>h.print(),300))}})),M?n(j,{display:"flex",justifyContent:"center",alignItems:"center",py:8,children:n(st,{})}):z?n(P,{color:"error",sx:{py:4,textAlign:"center"},children:z}):p?g(j,{children:[n(Y,{container:!0,spacing:1.5,sx:{mb:3},children:ht.map(h=>n(Y,{item:!0,xs:6,sm:4,md:2.4,lg:12/6,children:g(we,{variant:"outlined",sx:{p:1.5,borderLeft:4,borderLeftColor:h.color,borderRadius:2,height:"100%"},children:[n(P,{variant:"caption",color:"text.secondary",sx:{fontWeight:500},children:h.label}),n(P,{variant:"subtitle1",fontWeight:800,sx:{color:h.color,lineHeight:1.25},children:h.value})]})},h.label))}),n(Ut,{title:"Machine Information"}),g(we,{variant:"outlined",sx:{p:2,mb:3,borderRadius:2,display:"flex",alignItems:"center",gap:2},children:[n(j,{sx:{width:56,height:56,borderRadius:2,bgcolor:"primary.50",color:"primary.main",display:"flex",alignItems:"center",justifyContent:"center",flexShrink:0},children:n(fn,{fontSize:"large"})}),n(Y,{container:!0,spacing:2,children:[{label:"Machine Code",value:B(N.machineCode)},{label:"Machine Name",value:B(N.machineName)},{label:"Machine Type",value:B(N.machineType)},{label:"Capacity",value:B(N.capacity)},{label:"Location",value:B(N.location)},{label:"Status",value:B(N.status)}].map(h=>g(Y,{item:!0,xs:6,sm:4,md:2,children:[n(P,{variant:"caption",color:"text.secondary",sx:{fontWeight:500},children:h.label}),n(P,{variant:"body2",fontWeight:700,children:h.value})]},h.label))})]}),n(Ut,{title:"Production Details",subtitle:`${V.length} shift record(s)`}),n(We,{component:Se,variant:"outlined",sx:{mb:1.5,borderRadius:2},children:g($e,{size:"small",children:[n(Ye,{children:g(te,{sx:{"& th":{fontWeight:700,bgcolor:"action.hover"}},children:[n(c,{children:"Job Card No"}),n(c,{children:"Production Date"}),n(c,{children:"Shift"}),n(c,{children:"Product"}),n(c,{align:"right",children:"Planned"}),n(c,{align:"right",children:"Produced"}),n(c,{align:"right",children:"Rejected"}),n(c,{align:"right",children:"Production Cost"})]})}),n(Oe,{children:V.length===0?n(ka,{span:10}):V.map((h,O)=>g(te,{hover:!0,children:[n(c,{children:B(h.jobCardNo)}),n(c,{children:ge(h.productionDate)}),n(c,{children:B(h.shiftName)}),g(c,{children:[B(h.productName),h.productVariant?n(P,{variant:"caption",color:"text.secondary",display:"block",children:h.productVariant}):null]}),n(c,{align:"right",children:De(h.plannedQty)}),n(c,{align:"right",children:De(h.producedQty)}),n(c,{align:"right",children:De(h.rejectedQty)}),n(c,{align:"right",children:le(h.productionCost)})]},O))})]})}),n(Ut,{title:"Service & Maintenance",subtitle:`${ve} record(s)`,loading:K}),n(We,{component:Se,variant:"outlined",sx:{mb:1.5,borderRadius:2},children:g($e,{size:"small",children:[n(Ye,{children:g(te,{sx:{"& th":{fontWeight:700,bgcolor:"action.hover"}},children:[n(c,{children:"Service Date"}),n(c,{children:"Service Type"}),n(c,{children:"Description"}),n(c,{children:"Service Provider"}),n(c,{align:"right",children:"Service Cost"}),n(c,{children:"Next Service Date"})]})}),n(Oe,{children:T.length===0?n(ka,{span:6}):T.map((h,O)=>g(te,{hover:!0,children:[n(c,{children:ge(h.serviceDate)}),n(c,{children:B(h.serviceType)}),n(c,{children:B(h.serviceDescription??h.problemDescription??h.issueDescription??h.description)}),n(c,{children:B(h.serviceProvider??h.technicianName??h.engineerName)}),n(c,{align:"right",children:le(h.serviceCost)}),n(c,{children:ge(h.nextServiceDate)})]},h.id??O))})]})}),n(Ut,{title:"Spare Parts Replacement",subtitle:`${m.length} part(s)`,loading:Ie}),n(We,{component:Se,variant:"outlined",sx:{mb:1.5,borderRadius:2},children:g($e,{size:"small",children:[n(Ye,{children:g(te,{sx:{"& th":{fontWeight:700,bgcolor:"action.hover"}},children:[n(c,{children:"Replacement Date"}),n(c,{children:"Part Name"}),n(c,{children:"Part Number"}),n(c,{align:"right",children:"Qty Replaced"}),n(c,{align:"right",children:"Unit Cost"}),n(c,{align:"right",children:"Total Cost"}),n(c,{children:"Replacement Reason"})]})}),n(Oe,{children:m.length===0?n(ka,{span:7}):m.map((h,O)=>g(te,{hover:!0,children:[n(c,{children:ge(h.issueDate??h.replacementDate)}),n(c,{children:B(h.partName)}),n(c,{children:B(h.partNumber)}),n(c,{align:"right",children:De(h.quantity)}),n(c,{align:"right",children:le(h.unitCost)}),n(c,{align:"right",children:le(h.totalCost)}),n(c,{children:B(h.reason??h.remarks)})]},h.id??O))})]})}),n(Qi,{items:[{label:"Total Parts Replaced",value:De(G)},{label:"Total Spare Parts Cost",value:le(E)}]}),n(Ut,{title:"Insurance Details",subtitle:`${be.length} polic(ies)`,loading:Be}),n(We,{component:Se,variant:"outlined",sx:{mb:1.5,borderRadius:2},children:g($e,{size:"small",children:[n(Ye,{children:g(te,{sx:{"& th":{fontWeight:700,bgcolor:"action.hover"}},children:[n(c,{children:"Policy Number"}),n(c,{children:"Insurance Provider"}),n(c,{children:"Start Date"}),n(c,{children:"Expiry Date"}),n(c,{align:"right",children:"Premium"}),n(c,{children:"Status"})]})}),n(Oe,{children:be.length===0?n(ka,{span:6}):be.map((h,O)=>{const Re=rt(h.validUpto);return g(te,{hover:!0,children:[n(c,{children:B(h.policyNumber)}),n(c,{children:B(h.provider)}),n(c,{children:ge(h.validFrom)}),n(c,{children:ge(h.validUpto)}),n(c,{align:"right",children:le(h.premium)}),n(c,{children:n(xr,{size:"small",label:Re.label,color:Re.color,variant:"outlined"})})]},h.id??O)})})]})}),n(Qi,{items:[{label:"Total Insurance Cost",value:le(H)},{label:"Insurance Expiry",value:F?ge(F):"-"},{label:"Insurance Status",value:be.length===0?"-":L?"Active":"Expired"}]}),n(Ut,{title:"Cost Analysis"}),g(we,{variant:"outlined",sx:{p:2,mb:1,borderRadius:2},children:[n(Y,{container:!0,spacing:2,children:[{label:"Total Production Cost",value:W,color:"#7b1fa2"},{label:"Total Maintenance Cost",value:Fe,color:"#ed6c02"},{label:"Total Spare Parts Cost",value:E,color:"#5d4037"},{label:"Total Insurance Cost",value:H,color:"#00838f"}].map(h=>g(Y,{item:!0,xs:6,md:3,children:[n(P,{variant:"caption",color:"text.secondary",sx:{fontWeight:500},children:h.label}),n(P,{variant:"subtitle1",fontWeight:700,sx:{color:h.color},children:le(h.value)})]},h.label))}),n(Co,{sx:{my:2}}),g(j,{display:"flex",alignItems:"center",justifyContent:"space-between",flexWrap:"wrap",gap:1,children:[n(P,{variant:"subtitle1",fontWeight:700,color:"text.secondary",children:"Grand Total Machine Cost"}),n(P,{variant:"h5",fontWeight:800,sx:{color:"#c62828"},children:le(Ve)})]}),n(P,{variant:"caption",color:"text.secondary",sx:{display:"block",mt:1},children:"Grand Total = Production Cost + Maintenance Cost + Spare Parts Cost + Insurance Cost."})]})]}):n(P,{color:"text.secondary",sx:{py:4,textAlign:"center"},children:"Select a machine and click Generate to view its consolidated report."})});xn.displayName="MachineConsolidatedReport";const Ut=({title:e,subtitle:t,loading:a})=>g(j,{display:"flex",alignItems:"baseline",gap:1.5,mb:1,mt:1,children:[n(P,{variant:"subtitle2",fontWeight:700,color:"primary.main",sx:{textTransform:"uppercase",letterSpacing:"0.04em"},children:e}),t&&n(P,{variant:"caption",color:"text.secondary",children:t}),a&&n(st,{size:14})]}),Qi=({items:e})=>n(j,{sx:{display:"flex",flexWrap:"wrap",gap:3,px:2,py:1.5,mb:3,bgcolor:"grey.50",border:"1px solid",borderColor:"divider",borderRadius:2},children:e.map(t=>g(j,{children:[n(P,{variant:"caption",color:"text.secondary",sx:{fontWeight:500,display:"block"},children:t.label}),n(P,{variant:"subtitle2",fontWeight:700,children:t.value})]},t.label))}),ka=({span:e})=>n(te,{children:n(c,{colSpan:e,align:"center",sx:{color:"text.disabled",py:3},children:"No records"})});function Ho(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}//! moment.js
//! version : 2.30.1
//! authors : Tim Wood, Iskren Chernev, Moment.js contributors
//! license : MIT
//! momentjs.com
var vn;function R(){return vn.apply(null,arguments)}function qo(e){vn=e}function Xe(e){return e instanceof Array||Object.prototype.toString.call(e)==="[object Array]"}function Lt(e){return e!=null&&Object.prototype.toString.call(e)==="[object Object]"}function ae(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function wr(e){if(Object.getOwnPropertyNames)return Object.getOwnPropertyNames(e).length===0;var t;for(t in e)if(ae(e,t))return!1;return!0}function Te(e){return e===void 0}function Dt(e){return typeof e=="number"||Object.prototype.toString.call(e)==="[object Number]"}function ha(e){return e instanceof Date||Object.prototype.toString.call(e)==="[object Date]"}function _n(e,t){var a=[],i,l=e.length;for(i=0;i<l;++i)a.push(t(e[i],i));return a}function Tt(e,t){for(var a in t)ae(t,a)&&(e[a]=t[a]);return ae(t,"toString")&&(e.toString=t.toString),ae(t,"valueOf")&&(e.valueOf=t.valueOf),e}function ct(e,t,a,i){return Vn(e,t,a,i,!0).utc()}function Jo(){return{empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidEra:null,invalidMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1,parsedDateParts:[],era:null,meridiem:null,rfc2822:!1,weekdayMismatch:!1}}function A(e){return e._pf==null&&(e._pf=Jo()),e._pf}var Sr;Array.prototype.some?Sr=Array.prototype.some:Sr=function(e){var t=Object(this),a=t.length>>>0,i;for(i=0;i<a;i++)if(i in t&&e.call(this,t[i],i,t))return!0;return!1};function Wr(e){var t=null,a=!1,i=e._d&&!isNaN(e._d.getTime());if(i&&(t=A(e),a=Sr.call(t.parsedDateParts,function(l){return l!=null}),i=t.overflow<0&&!t.empty&&!t.invalidEra&&!t.invalidMonth&&!t.invalidWeekday&&!t.weekdayMismatch&&!t.nullInput&&!t.invalidFormat&&!t.userInvalidated&&(!t.meridiem||t.meridiem&&a),e._strict&&(i=i&&t.charsLeftOver===0&&t.unusedTokens.length===0&&t.bigHour===void 0)),Object.isFrozen==null||!Object.isFrozen(e))e._isValid=i;else return i;return e._isValid}function Ea(e){var t=ct(NaN);return e!=null?Tt(A(t),e):A(t).userInvalidated=!0,t}var Zi=R.momentProperties=[],gr=!1;function $r(e,t){var a,i,l,s=Zi.length;if(Te(t._isAMomentObject)||(e._isAMomentObject=t._isAMomentObject),Te(t._i)||(e._i=t._i),Te(t._f)||(e._f=t._f),Te(t._l)||(e._l=t._l),Te(t._strict)||(e._strict=t._strict),Te(t._tzm)||(e._tzm=t._tzm),Te(t._isUTC)||(e._isUTC=t._isUTC),Te(t._offset)||(e._offset=t._offset),Te(t._pf)||(e._pf=A(t)),Te(t._locale)||(e._locale=t._locale),s>0)for(a=0;a<s;a++)i=Zi[a],l=t[i],Te(l)||(e[i]=l);return e}function ma(e){$r(this,e),this._d=new Date(e._d!=null?e._d.getTime():NaN),this.isValid()||(this._d=new Date(NaN)),gr===!1&&(gr=!0,R.updateOffset(this),gr=!1)}function et(e){return e instanceof ma||e!=null&&e._isAMomentObject!=null}function Dn(e){R.suppressDeprecationWarnings===!1&&typeof console<"u"&&console.warn&&console.warn("Deprecation warning: "+e)}function qe(e,t){var a=!0;return Tt(function(){if(R.deprecationHandler!=null&&R.deprecationHandler(null,e),a){var i=[],l,s,u,D=arguments.length;for(s=0;s<D;s++){if(l="",typeof arguments[s]=="object"){l+=`
[`+s+"] ";for(u in arguments[0])ae(arguments[0],u)&&(l+=u+": "+arguments[0][u]+", ");l=l.slice(0,-2)}else l=arguments[s];i.push(l)}Dn(e+`
Arguments: `+Array.prototype.slice.call(i).join("")+`
`+new Error().stack),a=!1}return t.apply(this,arguments)},t)}var Ki={};function Sn(e,t){R.deprecationHandler!=null&&R.deprecationHandler(e,t),Ki[e]||(Dn(t),Ki[e]=!0)}R.suppressDeprecationWarnings=!1;R.deprecationHandler=null;function ut(e){return typeof Function<"u"&&e instanceof Function||Object.prototype.toString.call(e)==="[object Function]"}function Bo(e){var t,a;for(a in e)ae(e,a)&&(t=e[a],ut(t)?this[a]=t:this["_"+a]=t);this._config=e,this._dayOfMonthOrdinalParseLenient=new RegExp((this._dayOfMonthOrdinalParse.source||this._ordinalParse.source)+"|"+/\d{1,2}/.source)}function Pr(e,t){var a=Tt({},e),i;for(i in t)ae(t,i)&&(Lt(e[i])&&Lt(t[i])?(a[i]={},Tt(a[i],e[i]),Tt(a[i],t[i])):t[i]!=null?a[i]=t[i]:delete a[i]);for(i in e)ae(e,i)&&!ae(t,i)&&Lt(e[i])&&(a[i]=Tt({},a[i]));return a}function Yr(e){e!=null&&this.set(e)}var Nr;Object.keys?Nr=Object.keys:Nr=function(e){var t,a=[];for(t in e)ae(e,t)&&a.push(t);return a};var Qo={sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"};function Zo(e,t,a){var i=this._calendar[e]||this._calendar.sameElse;return ut(i)?i.call(t,a):i}function dt(e,t,a){var i=""+Math.abs(e),l=t-i.length,s=e>=0;return(s?a?"+":"":"-")+Math.pow(10,Math.max(0,l)).toString().substr(1)+i}var Or=/(\[[^\[]*\])|(\\)?([Hh]mm(ss)?|Mo|MM?M?M?|Do|DDDo|DD?D?D?|ddd?d?|do?|w[o|w]?|W[o|W]?|Qo?|N{1,5}|YYYYYY|YYYYY|YYYY|YY|y{2,4}|yo?|gg(ggg?)?|GG(GGG?)?|e|E|a|A|hh?|HH?|kk?|mm?|ss?|S{1,9}|x|X|zz?|ZZ?|.)/g,Ta=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,pr={},Jt={};function $(e,t,a,i){var l=i;typeof i=="string"&&(l=function(){return this[i]()}),e&&(Jt[e]=l),t&&(Jt[t[0]]=function(){return dt(l.apply(this,arguments),t[1],t[2])}),a&&(Jt[a]=function(){return this.localeData().ordinal(l.apply(this,arguments),e)})}function Ko(e){return e.match(/\[[\s\S]/)?e.replace(/^\[|\]$/g,""):e.replace(/\\/g,"")}function Xo(e){var t=e.match(Or),a,i;for(a=0,i=t.length;a<i;a++)Jt[t[a]]?t[a]=Jt[t[a]]:t[a]=Ko(t[a]);return function(l){var s="",u;for(u=0;u<i;u++)s+=ut(t[u])?t[u].call(l,e):t[u];return s}}function Wa(e,t){return e.isValid()?(t=Pn(t,e.localeData()),pr[t]=pr[t]||Xo(t),pr[t](e)):e.localeData().invalidDate()}function Pn(e,t){var a=5;function i(l){return t.longDateFormat(l)||l}for(Ta.lastIndex=0;a>=0&&Ta.test(e);)e=e.replace(Ta,i),Ta.lastIndex=0,a-=1;return e}var es={LTS:"h:mm:ss A",LT:"h:mm A",L:"MM/DD/YYYY",LL:"MMMM D, YYYY",LLL:"MMMM D, YYYY h:mm A",LLLL:"dddd, MMMM D, YYYY h:mm A"};function ts(e){var t=this._longDateFormat[e],a=this._longDateFormat[e.toUpperCase()];return t||!a?t:(this._longDateFormat[e]=a.match(Or).map(function(i){return i==="MMMM"||i==="MM"||i==="DD"||i==="dddd"?i.slice(1):i}).join(""),this._longDateFormat[e])}var as="Invalid date";function rs(){return this._invalidDate}var is="%d",ns=/\d{1,2}/;function ls(e){return this._ordinal.replace("%d",e)}var os={future:"in %s",past:"%s ago",s:"a few seconds",ss:"%d seconds",m:"a minute",mm:"%d minutes",h:"an hour",hh:"%d hours",d:"a day",dd:"%d days",w:"a week",ww:"%d weeks",M:"a month",MM:"%d months",y:"a year",yy:"%d years"};function ss(e,t,a,i){var l=this._relativeTime[a];return ut(l)?l(e,t,a,i):l.replace(/%d/i,e)}function ds(e,t){var a=this._relativeTime[e>0?"future":"past"];return ut(a)?a(t):a.replace(/%s/i,t)}var Xi={D:"date",dates:"date",date:"date",d:"day",days:"day",day:"day",e:"weekday",weekdays:"weekday",weekday:"weekday",E:"isoWeekday",isoweekdays:"isoWeekday",isoweekday:"isoWeekday",DDD:"dayOfYear",dayofyears:"dayOfYear",dayofyear:"dayOfYear",h:"hour",hours:"hour",hour:"hour",ms:"millisecond",milliseconds:"millisecond",millisecond:"millisecond",m:"minute",minutes:"minute",minute:"minute",M:"month",months:"month",month:"month",Q:"quarter",quarters:"quarter",quarter:"quarter",s:"second",seconds:"second",second:"second",gg:"weekYear",weekyears:"weekYear",weekyear:"weekYear",GG:"isoWeekYear",isoweekyears:"isoWeekYear",isoweekyear:"isoWeekYear",w:"week",weeks:"week",week:"week",W:"isoWeek",isoweeks:"isoWeek",isoweek:"isoWeek",y:"year",years:"year",year:"year"};function Je(e){return typeof e=="string"?Xi[e]||Xi[e.toLowerCase()]:void 0}function Ir(e){var t={},a,i;for(i in e)ae(e,i)&&(a=Je(i),a&&(t[a]=e[i]));return t}var cs={date:9,day:11,weekday:11,isoWeekday:11,dayOfYear:4,hour:13,millisecond:16,minute:14,month:8,quarter:7,second:15,weekYear:1,isoWeekYear:1,week:5,isoWeek:5,year:1};function us(e){var t=[],a;for(a in e)ae(e,a)&&t.push({unit:a,priority:cs[a]});return t.sort(function(i,l){return i.priority-l.priority}),t}var Nn=/\d/,Ue=/\d\d/,Mn=/\d{3}/,Fr=/\d{4}/,ja=/[+-]?\d{6}/,se=/\d\d?/,Rn=/\d\d\d\d?/,Cn=/\d\d\d\d\d\d?/,za=/\d{1,3}/,Lr=/\d{1,4}/,Ua=/[+-]?\d{1,6}/,Kt=/\d+/,Va=/[+-]?\d+/,hs=/Z|[+-]\d\d:?\d\d/gi,Ga=/Z|[+-]\d\d(?::?\d\d)?/gi,ms=/[+-]?\d+(\.\d{1,3})?/,fa=/[0-9]{0,256}['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFF07\uFF10-\uFFEF]{1,256}|[\u0600-\u06FF\/]{1,256}(\s*?[\u0600-\u06FF]{1,256}){1,2}/i,Xt=/^[1-9]\d?/,Ar=/^([1-9]\d|\d)/,Oa;Oa={};function C(e,t,a){Oa[e]=ut(t)?t:function(i,l){return i&&a?a:t}}function fs(e,t){return ae(Oa,e)?Oa[e](t._strict,t._locale):new RegExp(gs(e))}function gs(e){return vt(e.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(t,a,i,l,s){return a||i||l||s}))}function vt(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}function He(e){return e<0?Math.ceil(e)||0:Math.floor(e)}function Q(e){var t=+e,a=0;return t!==0&&isFinite(t)&&(a=He(t)),a}var Mr={};function ie(e,t){var a,i=t,l;for(typeof e=="string"&&(e=[e]),Dt(t)&&(i=function(s,u){u[t]=Q(s)}),l=e.length,a=0;a<l;a++)Mr[e[a]]=i}function ga(e,t){ie(e,function(a,i,l,s){l._w=l._w||{},t(a,l._w,l,s)})}function ps(e,t,a){t!=null&&ae(Mr,e)&&Mr[e](t,a._a,a,e)}function Ha(e){return e%4===0&&e%100!==0||e%400===0}var Me=0,bt=1,ot=2,xe=3,Ke=4,xt=5,Ft=6,ys=7,bs=8;$("Y",0,0,function(){var e=this.year();return e<=9999?dt(e,4):"+"+e});$(0,["YY",2],0,function(){return this.year()%100});$(0,["YYYY",4],0,"year");$(0,["YYYYY",5],0,"year");$(0,["YYYYYY",6,!0],0,"year");C("Y",Va);C("YY",se,Ue);C("YYYY",Lr,Fr);C("YYYYY",Ua,ja);C("YYYYYY",Ua,ja);ie(["YYYYY","YYYYYY"],Me);ie("YYYY",function(e,t){t[Me]=e.length===2?R.parseTwoDigitYear(e):Q(e)});ie("YY",function(e,t){t[Me]=R.parseTwoDigitYear(e)});ie("Y",function(e,t){t[Me]=parseInt(e,10)});function oa(e){return Ha(e)?366:365}R.parseTwoDigitYear=function(e){return Q(e)+(Q(e)>68?1900:2e3)};var kn=ea("FullYear",!0);function xs(){return Ha(this.year())}function ea(e,t){return function(a){return a!=null?(Tn(this,e,a),R.updateOffset(this,t),this):sa(this,e)}}function sa(e,t){if(!e.isValid())return NaN;var a=e._d,i=e._isUTC;switch(t){case"Milliseconds":return i?a.getUTCMilliseconds():a.getMilliseconds();case"Seconds":return i?a.getUTCSeconds():a.getSeconds();case"Minutes":return i?a.getUTCMinutes():a.getMinutes();case"Hours":return i?a.getUTCHours():a.getHours();case"Date":return i?a.getUTCDate():a.getDate();case"Day":return i?a.getUTCDay():a.getDay();case"Month":return i?a.getUTCMonth():a.getMonth();case"FullYear":return i?a.getUTCFullYear():a.getFullYear();default:return NaN}}function Tn(e,t,a){var i,l,s,u,D;if(!(!e.isValid()||isNaN(a))){switch(i=e._d,l=e._isUTC,t){case"Milliseconds":return void(l?i.setUTCMilliseconds(a):i.setMilliseconds(a));case"Seconds":return void(l?i.setUTCSeconds(a):i.setSeconds(a));case"Minutes":return void(l?i.setUTCMinutes(a):i.setMinutes(a));case"Hours":return void(l?i.setUTCHours(a):i.setHours(a));case"Date":return void(l?i.setUTCDate(a):i.setDate(a));case"FullYear":break;default:return}s=a,u=e.month(),D=e.date(),D=D===29&&u===1&&!Ha(s)?28:D,l?i.setUTCFullYear(s,u,D):i.setFullYear(s,u,D)}}function vs(e){return e=Je(e),ut(this[e])?this[e]():this}function _s(e,t){if(typeof e=="object"){e=Ir(e);var a=us(e),i,l=a.length;for(i=0;i<l;i++)this[a[i].unit](e[a[i].unit])}else if(e=Je(e),ut(this[e]))return this[e](t);return this}function Ds(e,t){return(e%t+t)%t}var pe;Array.prototype.indexOf?pe=Array.prototype.indexOf:pe=function(e){var t;for(t=0;t<this.length;++t)if(this[t]===e)return t;return-1};function Er(e,t){if(isNaN(e)||isNaN(t))return NaN;var a=Ds(t,12);return e+=(t-a)/12,a===1?Ha(e)?29:28:31-a%7%2}$("M",["MM",2],"Mo",function(){return this.month()+1});$("MMM",0,0,function(e){return this.localeData().monthsShort(this,e)});$("MMMM",0,0,function(e){return this.localeData().months(this,e)});C("M",se,Xt);C("MM",se,Ue);C("MMM",function(e,t){return t.monthsShortRegex(e)});C("MMMM",function(e,t){return t.monthsRegex(e)});ie(["M","MM"],function(e,t){t[bt]=Q(e)-1});ie(["MMM","MMMM"],function(e,t,a,i){var l=a._locale.monthsParse(e,i,a._strict);l!=null?t[bt]=l:A(a).invalidMonth=e});var Ss="January_February_March_April_May_June_July_August_September_October_November_December".split("_"),wn="Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),Wn=/D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,Ps=fa,Ns=fa;function Ms(e,t){return e?Xe(this._months)?this._months[e.month()]:this._months[(this._months.isFormat||Wn).test(t)?"format":"standalone"][e.month()]:Xe(this._months)?this._months:this._months.standalone}function Rs(e,t){return e?Xe(this._monthsShort)?this._monthsShort[e.month()]:this._monthsShort[Wn.test(t)?"format":"standalone"][e.month()]:Xe(this._monthsShort)?this._monthsShort:this._monthsShort.standalone}function Cs(e,t,a){var i,l,s,u=e.toLocaleLowerCase();if(!this._monthsParse)for(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[],i=0;i<12;++i)s=ct([2e3,i]),this._shortMonthsParse[i]=this.monthsShort(s,"").toLocaleLowerCase(),this._longMonthsParse[i]=this.months(s,"").toLocaleLowerCase();return a?t==="MMM"?(l=pe.call(this._shortMonthsParse,u),l!==-1?l:null):(l=pe.call(this._longMonthsParse,u),l!==-1?l:null):t==="MMM"?(l=pe.call(this._shortMonthsParse,u),l!==-1?l:(l=pe.call(this._longMonthsParse,u),l!==-1?l:null)):(l=pe.call(this._longMonthsParse,u),l!==-1?l:(l=pe.call(this._shortMonthsParse,u),l!==-1?l:null))}function ks(e,t,a){var i,l,s;if(this._monthsParseExact)return Cs.call(this,e,t,a);for(this._monthsParse||(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[]),i=0;i<12;i++){if(l=ct([2e3,i]),a&&!this._longMonthsParse[i]&&(this._longMonthsParse[i]=new RegExp("^"+this.months(l,"").replace(".","")+"$","i"),this._shortMonthsParse[i]=new RegExp("^"+this.monthsShort(l,"").replace(".","")+"$","i")),!a&&!this._monthsParse[i]&&(s="^"+this.months(l,"")+"|^"+this.monthsShort(l,""),this._monthsParse[i]=new RegExp(s.replace(".",""),"i")),a&&t==="MMMM"&&this._longMonthsParse[i].test(e))return i;if(a&&t==="MMM"&&this._shortMonthsParse[i].test(e))return i;if(!a&&this._monthsParse[i].test(e))return i}}function $n(e,t){if(!e.isValid())return e;if(typeof t=="string"){if(/^\d+$/.test(t))t=Q(t);else if(t=e.localeData().monthsParse(t),!Dt(t))return e}var a=t,i=e.date();return i=i<29?i:Math.min(i,Er(e.year(),a)),e._isUTC?e._d.setUTCMonth(a,i):e._d.setMonth(a,i),e}function Yn(e){return e!=null?($n(this,e),R.updateOffset(this,!0),this):sa(this,"Month")}function Ts(){return Er(this.year(),this.month())}function ws(e){return this._monthsParseExact?(ae(this,"_monthsRegex")||On.call(this),e?this._monthsShortStrictRegex:this._monthsShortRegex):(ae(this,"_monthsShortRegex")||(this._monthsShortRegex=Ps),this._monthsShortStrictRegex&&e?this._monthsShortStrictRegex:this._monthsShortRegex)}function Ws(e){return this._monthsParseExact?(ae(this,"_monthsRegex")||On.call(this),e?this._monthsStrictRegex:this._monthsRegex):(ae(this,"_monthsRegex")||(this._monthsRegex=Ns),this._monthsStrictRegex&&e?this._monthsStrictRegex:this._monthsRegex)}function On(){function e(M,p){return p.length-M.length}var t=[],a=[],i=[],l,s,u,D;for(l=0;l<12;l++)s=ct([2e3,l]),u=vt(this.monthsShort(s,"")),D=vt(this.months(s,"")),t.push(u),a.push(D),i.push(D),i.push(u);t.sort(e),a.sort(e),i.sort(e),this._monthsRegex=new RegExp("^("+i.join("|")+")","i"),this._monthsShortRegex=this._monthsRegex,this._monthsStrictRegex=new RegExp("^("+a.join("|")+")","i"),this._monthsShortStrictRegex=new RegExp("^("+t.join("|")+")","i")}function $s(e,t,a,i,l,s,u){var D;return e<100&&e>=0?(D=new Date(e+400,t,a,i,l,s,u),isFinite(D.getFullYear())&&D.setFullYear(e)):D=new Date(e,t,a,i,l,s,u),D}function da(e){var t,a;return e<100&&e>=0?(a=Array.prototype.slice.call(arguments),a[0]=e+400,t=new Date(Date.UTC.apply(null,a)),isFinite(t.getUTCFullYear())&&t.setUTCFullYear(e)):t=new Date(Date.UTC.apply(null,arguments)),t}function Ia(e,t,a){var i=7+t-a,l=(7+da(e,0,i).getUTCDay()-t)%7;return-l+i-1}function In(e,t,a,i,l){var s=(7+a-i)%7,u=Ia(e,i,l),D=1+7*(t-1)+s+u,M,p;return D<=0?(M=e-1,p=oa(M)+D):D>oa(e)?(M=e+1,p=D-oa(e)):(M=e,p=D),{year:M,dayOfYear:p}}function ca(e,t,a){var i=Ia(e.year(),t,a),l=Math.floor((e.dayOfYear()-i-1)/7)+1,s,u;return l<1?(u=e.year()-1,s=l+_t(u,t,a)):l>_t(e.year(),t,a)?(s=l-_t(e.year(),t,a),u=e.year()+1):(u=e.year(),s=l),{week:s,year:u}}function _t(e,t,a){var i=Ia(e,t,a),l=Ia(e+1,t,a);return(oa(e)-i+l)/7}$("w",["ww",2],"wo","week");$("W",["WW",2],"Wo","isoWeek");C("w",se,Xt);C("ww",se,Ue);C("W",se,Xt);C("WW",se,Ue);ga(["w","ww","W","WW"],function(e,t,a,i){t[i.substr(0,1)]=Q(e)});function Ys(e){return ca(e,this._week.dow,this._week.doy).week}var Os={dow:0,doy:6};function Is(){return this._week.dow}function Fs(){return this._week.doy}function Ls(e){var t=this.localeData().week(this);return e==null?t:this.add((e-t)*7,"d")}function As(e){var t=ca(this,1,4).week;return e==null?t:this.add((e-t)*7,"d")}$("d",0,"do","day");$("dd",0,0,function(e){return this.localeData().weekdaysMin(this,e)});$("ddd",0,0,function(e){return this.localeData().weekdaysShort(this,e)});$("dddd",0,0,function(e){return this.localeData().weekdays(this,e)});$("e",0,0,"weekday");$("E",0,0,"isoWeekday");C("d",se);C("e",se);C("E",se);C("dd",function(e,t){return t.weekdaysMinRegex(e)});C("ddd",function(e,t){return t.weekdaysShortRegex(e)});C("dddd",function(e,t){return t.weekdaysRegex(e)});ga(["dd","ddd","dddd"],function(e,t,a,i){var l=a._locale.weekdaysParse(e,i,a._strict);l!=null?t.d=l:A(a).invalidWeekday=e});ga(["d","e","E"],function(e,t,a,i){t[i]=Q(e)});function Es(e,t){return typeof e!="string"?e:isNaN(e)?(e=t.weekdaysParse(e),typeof e=="number"?e:null):parseInt(e,10)}function js(e,t){return typeof e=="string"?t.weekdaysParse(e)%7||7:isNaN(e)?null:e}function jr(e,t){return e.slice(t,7).concat(e.slice(0,t))}var zs="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),Fn="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),Us="Su_Mo_Tu_We_Th_Fr_Sa".split("_"),Vs=fa,Gs=fa,Hs=fa;function qs(e,t){var a=Xe(this._weekdays)?this._weekdays:this._weekdays[e&&e!==!0&&this._weekdays.isFormat.test(t)?"format":"standalone"];return e===!0?jr(a,this._week.dow):e?a[e.day()]:a}function Js(e){return e===!0?jr(this._weekdaysShort,this._week.dow):e?this._weekdaysShort[e.day()]:this._weekdaysShort}function Bs(e){return e===!0?jr(this._weekdaysMin,this._week.dow):e?this._weekdaysMin[e.day()]:this._weekdaysMin}function Qs(e,t,a){var i,l,s,u=e.toLocaleLowerCase();if(!this._weekdaysParse)for(this._weekdaysParse=[],this._shortWeekdaysParse=[],this._minWeekdaysParse=[],i=0;i<7;++i)s=ct([2e3,1]).day(i),this._minWeekdaysParse[i]=this.weekdaysMin(s,"").toLocaleLowerCase(),this._shortWeekdaysParse[i]=this.weekdaysShort(s,"").toLocaleLowerCase(),this._weekdaysParse[i]=this.weekdays(s,"").toLocaleLowerCase();return a?t==="dddd"?(l=pe.call(this._weekdaysParse,u),l!==-1?l:null):t==="ddd"?(l=pe.call(this._shortWeekdaysParse,u),l!==-1?l:null):(l=pe.call(this._minWeekdaysParse,u),l!==-1?l:null):t==="dddd"?(l=pe.call(this._weekdaysParse,u),l!==-1||(l=pe.call(this._shortWeekdaysParse,u),l!==-1)?l:(l=pe.call(this._minWeekdaysParse,u),l!==-1?l:null)):t==="ddd"?(l=pe.call(this._shortWeekdaysParse,u),l!==-1||(l=pe.call(this._weekdaysParse,u),l!==-1)?l:(l=pe.call(this._minWeekdaysParse,u),l!==-1?l:null)):(l=pe.call(this._minWeekdaysParse,u),l!==-1||(l=pe.call(this._weekdaysParse,u),l!==-1)?l:(l=pe.call(this._shortWeekdaysParse,u),l!==-1?l:null))}function Zs(e,t,a){var i,l,s;if(this._weekdaysParseExact)return Qs.call(this,e,t,a);for(this._weekdaysParse||(this._weekdaysParse=[],this._minWeekdaysParse=[],this._shortWeekdaysParse=[],this._fullWeekdaysParse=[]),i=0;i<7;i++){if(l=ct([2e3,1]).day(i),a&&!this._fullWeekdaysParse[i]&&(this._fullWeekdaysParse[i]=new RegExp("^"+this.weekdays(l,"").replace(".","\\.?")+"$","i"),this._shortWeekdaysParse[i]=new RegExp("^"+this.weekdaysShort(l,"").replace(".","\\.?")+"$","i"),this._minWeekdaysParse[i]=new RegExp("^"+this.weekdaysMin(l,"").replace(".","\\.?")+"$","i")),this._weekdaysParse[i]||(s="^"+this.weekdays(l,"")+"|^"+this.weekdaysShort(l,"")+"|^"+this.weekdaysMin(l,""),this._weekdaysParse[i]=new RegExp(s.replace(".",""),"i")),a&&t==="dddd"&&this._fullWeekdaysParse[i].test(e))return i;if(a&&t==="ddd"&&this._shortWeekdaysParse[i].test(e))return i;if(a&&t==="dd"&&this._minWeekdaysParse[i].test(e))return i;if(!a&&this._weekdaysParse[i].test(e))return i}}function Ks(e){if(!this.isValid())return e!=null?this:NaN;var t=sa(this,"Day");return e!=null?(e=Es(e,this.localeData()),this.add(e-t,"d")):t}function Xs(e){if(!this.isValid())return e!=null?this:NaN;var t=(this.day()+7-this.localeData()._week.dow)%7;return e==null?t:this.add(e-t,"d")}function ed(e){if(!this.isValid())return e!=null?this:NaN;if(e!=null){var t=js(e,this.localeData());return this.day(this.day()%7?t:t-7)}else return this.day()||7}function td(e){return this._weekdaysParseExact?(ae(this,"_weekdaysRegex")||zr.call(this),e?this._weekdaysStrictRegex:this._weekdaysRegex):(ae(this,"_weekdaysRegex")||(this._weekdaysRegex=Vs),this._weekdaysStrictRegex&&e?this._weekdaysStrictRegex:this._weekdaysRegex)}function ad(e){return this._weekdaysParseExact?(ae(this,"_weekdaysRegex")||zr.call(this),e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex):(ae(this,"_weekdaysShortRegex")||(this._weekdaysShortRegex=Gs),this._weekdaysShortStrictRegex&&e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex)}function rd(e){return this._weekdaysParseExact?(ae(this,"_weekdaysRegex")||zr.call(this),e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex):(ae(this,"_weekdaysMinRegex")||(this._weekdaysMinRegex=Hs),this._weekdaysMinStrictRegex&&e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex)}function zr(){function e(b,z){return z.length-b.length}var t=[],a=[],i=[],l=[],s,u,D,M,p;for(s=0;s<7;s++)u=ct([2e3,1]).day(s),D=vt(this.weekdaysMin(u,"")),M=vt(this.weekdaysShort(u,"")),p=vt(this.weekdays(u,"")),t.push(D),a.push(M),i.push(p),l.push(D),l.push(M),l.push(p);t.sort(e),a.sort(e),i.sort(e),l.sort(e),this._weekdaysRegex=new RegExp("^("+l.join("|")+")","i"),this._weekdaysShortRegex=this._weekdaysRegex,this._weekdaysMinRegex=this._weekdaysRegex,this._weekdaysStrictRegex=new RegExp("^("+i.join("|")+")","i"),this._weekdaysShortStrictRegex=new RegExp("^("+a.join("|")+")","i"),this._weekdaysMinStrictRegex=new RegExp("^("+t.join("|")+")","i")}function Ur(){return this.hours()%12||12}function id(){return this.hours()||24}$("H",["HH",2],0,"hour");$("h",["hh",2],0,Ur);$("k",["kk",2],0,id);$("hmm",0,0,function(){return""+Ur.apply(this)+dt(this.minutes(),2)});$("hmmss",0,0,function(){return""+Ur.apply(this)+dt(this.minutes(),2)+dt(this.seconds(),2)});$("Hmm",0,0,function(){return""+this.hours()+dt(this.minutes(),2)});$("Hmmss",0,0,function(){return""+this.hours()+dt(this.minutes(),2)+dt(this.seconds(),2)});function Ln(e,t){$(e,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),t)})}Ln("a",!0);Ln("A",!1);function An(e,t){return t._meridiemParse}C("a",An);C("A",An);C("H",se,Ar);C("h",se,Xt);C("k",se,Xt);C("HH",se,Ue);C("hh",se,Ue);C("kk",se,Ue);C("hmm",Rn);C("hmmss",Cn);C("Hmm",Rn);C("Hmmss",Cn);ie(["H","HH"],xe);ie(["k","kk"],function(e,t,a){var i=Q(e);t[xe]=i===24?0:i});ie(["a","A"],function(e,t,a){a._isPm=a._locale.isPM(e),a._meridiem=e});ie(["h","hh"],function(e,t,a){t[xe]=Q(e),A(a).bigHour=!0});ie("hmm",function(e,t,a){var i=e.length-2;t[xe]=Q(e.substr(0,i)),t[Ke]=Q(e.substr(i)),A(a).bigHour=!0});ie("hmmss",function(e,t,a){var i=e.length-4,l=e.length-2;t[xe]=Q(e.substr(0,i)),t[Ke]=Q(e.substr(i,2)),t[xt]=Q(e.substr(l)),A(a).bigHour=!0});ie("Hmm",function(e,t,a){var i=e.length-2;t[xe]=Q(e.substr(0,i)),t[Ke]=Q(e.substr(i))});ie("Hmmss",function(e,t,a){var i=e.length-4,l=e.length-2;t[xe]=Q(e.substr(0,i)),t[Ke]=Q(e.substr(i,2)),t[xt]=Q(e.substr(l))});function nd(e){return(e+"").toLowerCase().charAt(0)==="p"}var ld=/[ap]\.?m?\.?/i,od=ea("Hours",!0);function sd(e,t,a){return e>11?a?"pm":"PM":a?"am":"AM"}var En={calendar:Qo,longDateFormat:es,invalidDate:as,ordinal:is,dayOfMonthOrdinalParse:ns,relativeTime:os,months:Ss,monthsShort:wn,week:Os,weekdays:zs,weekdaysMin:Us,weekdaysShort:Fn,meridiemParse:ld},ce={},na={},ua;function dd(e,t){var a,i=Math.min(e.length,t.length);for(a=0;a<i;a+=1)if(e[a]!==t[a])return a;return i}function en(e){return e&&e.toLowerCase().replace("_","-")}function cd(e){for(var t=0,a,i,l,s;t<e.length;){for(s=en(e[t]).split("-"),a=s.length,i=en(e[t+1]),i=i?i.split("-"):null;a>0;){if(l=qa(s.slice(0,a).join("-")),l)return l;if(i&&i.length>=a&&dd(s,i)>=a-1)break;a--}t++}return ua}function ud(e){return!!(e&&e.match("^[^/\\\\]*$"))}function qa(e){var t=null,a;if(ce[e]===void 0&&typeof module<"u"&&module&&module.exports&&ud(e))try{t=ua._abbr,a=Ho,a("./locale/"+e),Wt(t)}catch{ce[e]=null}return ce[e]}function Wt(e,t){var a;return e&&(Te(t)?a=St(e):a=Vr(e,t),a?ua=a:typeof console<"u"&&console.warn&&console.warn("Locale "+e+" not found. Did you forget to load it?")),ua._abbr}function Vr(e,t){if(t!==null){var a,i=En;if(t.abbr=e,ce[e]!=null)Sn("defineLocaleOverride","use moment.updateLocale(localeName, config) to change an existing locale. moment.defineLocale(localeName, config) should only be used for creating a new locale See http://momentjs.com/guides/#/warnings/define-locale/ for more info."),i=ce[e]._config;else if(t.parentLocale!=null)if(ce[t.parentLocale]!=null)i=ce[t.parentLocale]._config;else if(a=qa(t.parentLocale),a!=null)i=a._config;else return na[t.parentLocale]||(na[t.parentLocale]=[]),na[t.parentLocale].push({name:e,config:t}),null;return ce[e]=new Yr(Pr(i,t)),na[e]&&na[e].forEach(function(l){Vr(l.name,l.config)}),Wt(e),ce[e]}else return delete ce[e],null}function hd(e,t){if(t!=null){var a,i,l=En;ce[e]!=null&&ce[e].parentLocale!=null?ce[e].set(Pr(ce[e]._config,t)):(i=qa(e),i!=null&&(l=i._config),t=Pr(l,t),i==null&&(t.abbr=e),a=new Yr(t),a.parentLocale=ce[e],ce[e]=a),Wt(e)}else ce[e]!=null&&(ce[e].parentLocale!=null?(ce[e]=ce[e].parentLocale,e===Wt()&&Wt(e)):ce[e]!=null&&delete ce[e]);return ce[e]}function St(e){var t;if(e&&e._locale&&e._locale._abbr&&(e=e._locale._abbr),!e)return ua;if(!Xe(e)){if(t=qa(e),t)return t;e=[e]}return cd(e)}function md(){return Nr(ce)}function Gr(e){var t,a=e._a;return a&&A(e).overflow===-2&&(t=a[bt]<0||a[bt]>11?bt:a[ot]<1||a[ot]>Er(a[Me],a[bt])?ot:a[xe]<0||a[xe]>24||a[xe]===24&&(a[Ke]!==0||a[xt]!==0||a[Ft]!==0)?xe:a[Ke]<0||a[Ke]>59?Ke:a[xt]<0||a[xt]>59?xt:a[Ft]<0||a[Ft]>999?Ft:-1,A(e)._overflowDayOfYear&&(t<Me||t>ot)&&(t=ot),A(e)._overflowWeeks&&t===-1&&(t=ys),A(e)._overflowWeekday&&t===-1&&(t=bs),A(e).overflow=t),e}var fd=/^\s*((?:[+-]\d{6}|\d{4})-(?:\d\d-\d\d|W\d\d-\d|W\d\d|\d\d\d|\d\d))(?:(T| )(\d\d(?::\d\d(?::\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,gd=/^\s*((?:[+-]\d{6}|\d{4})(?:\d\d\d\d|W\d\d\d|W\d\d|\d\d\d|\d\d|))(?:(T| )(\d\d(?:\d\d(?:\d\d(?:[.,]\d+)?)?)?)([+-]\d\d(?::?\d\d)?|\s*Z)?)?$/,pd=/Z|[+-]\d\d(?::?\d\d)?/,wa=[["YYYYYY-MM-DD",/[+-]\d{6}-\d\d-\d\d/],["YYYY-MM-DD",/\d{4}-\d\d-\d\d/],["GGGG-[W]WW-E",/\d{4}-W\d\d-\d/],["GGGG-[W]WW",/\d{4}-W\d\d/,!1],["YYYY-DDD",/\d{4}-\d{3}/],["YYYY-MM",/\d{4}-\d\d/,!1],["YYYYYYMMDD",/[+-]\d{10}/],["YYYYMMDD",/\d{8}/],["GGGG[W]WWE",/\d{4}W\d{3}/],["GGGG[W]WW",/\d{4}W\d{2}/,!1],["YYYYDDD",/\d{7}/],["YYYYMM",/\d{6}/,!1],["YYYY",/\d{4}/,!1]],yr=[["HH:mm:ss.SSSS",/\d\d:\d\d:\d\d\.\d+/],["HH:mm:ss,SSSS",/\d\d:\d\d:\d\d,\d+/],["HH:mm:ss",/\d\d:\d\d:\d\d/],["HH:mm",/\d\d:\d\d/],["HHmmss.SSSS",/\d\d\d\d\d\d\.\d+/],["HHmmss,SSSS",/\d\d\d\d\d\d,\d+/],["HHmmss",/\d\d\d\d\d\d/],["HHmm",/\d\d\d\d/],["HH",/\d\d/]],yd=/^\/?Date\((-?\d+)/i,bd=/^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),?\s)?(\d{1,2})\s(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s(\d{2,4})\s(\d\d):(\d\d)(?::(\d\d))?\s(?:(UT|GMT|[ECMP][SD]T)|([Zz])|([+-]\d{4}))$/,xd={UT:0,GMT:0,EDT:-4*60,EST:-5*60,CDT:-5*60,CST:-6*60,MDT:-6*60,MST:-7*60,PDT:-7*60,PST:-8*60};function jn(e){var t,a,i=e._i,l=fd.exec(i)||gd.exec(i),s,u,D,M,p=wa.length,b=yr.length;if(l){for(A(e).iso=!0,t=0,a=p;t<a;t++)if(wa[t][1].exec(l[1])){u=wa[t][0],s=wa[t][2]!==!1;break}if(u==null){e._isValid=!1;return}if(l[3]){for(t=0,a=b;t<a;t++)if(yr[t][1].exec(l[3])){D=(l[2]||" ")+yr[t][0];break}if(D==null){e._isValid=!1;return}}if(!s&&D!=null){e._isValid=!1;return}if(l[4])if(pd.exec(l[4]))M="Z";else{e._isValid=!1;return}e._f=u+(D||"")+(M||""),qr(e)}else e._isValid=!1}function vd(e,t,a,i,l,s){var u=[_d(e),wn.indexOf(t),parseInt(a,10),parseInt(i,10),parseInt(l,10)];return s&&u.push(parseInt(s,10)),u}function _d(e){var t=parseInt(e,10);return t<=49?2e3+t:t<=999?1900+t:t}function Dd(e){return e.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").replace(/^\s\s*/,"").replace(/\s\s*$/,"")}function Sd(e,t,a){if(e){var i=Fn.indexOf(e),l=new Date(t[0],t[1],t[2]).getDay();if(i!==l)return A(a).weekdayMismatch=!0,a._isValid=!1,!1}return!0}function Pd(e,t,a){if(e)return xd[e];if(t)return 0;var i=parseInt(a,10),l=i%100,s=(i-l)/100;return s*60+l}function zn(e){var t=bd.exec(Dd(e._i)),a;if(t){if(a=vd(t[4],t[3],t[2],t[5],t[6],t[7]),!Sd(t[1],a,e))return;e._a=a,e._tzm=Pd(t[8],t[9],t[10]),e._d=da.apply(null,e._a),e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),A(e).rfc2822=!0}else e._isValid=!1}function Nd(e){var t=yd.exec(e._i);if(t!==null){e._d=new Date(+t[1]);return}if(jn(e),e._isValid===!1)delete e._isValid;else return;if(zn(e),e._isValid===!1)delete e._isValid;else return;e._strict?e._isValid=!1:R.createFromInputFallback(e)}R.createFromInputFallback=qe("value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.",function(e){e._d=new Date(e._i+(e._useUTC?" UTC":""))});function Ht(e,t,a){return e??t??a}function Md(e){var t=new Date(R.now());return e._useUTC?[t.getUTCFullYear(),t.getUTCMonth(),t.getUTCDate()]:[t.getFullYear(),t.getMonth(),t.getDate()]}function Hr(e){var t,a,i=[],l,s,u;if(!e._d){for(l=Md(e),e._w&&e._a[ot]==null&&e._a[bt]==null&&Rd(e),e._dayOfYear!=null&&(u=Ht(e._a[Me],l[Me]),(e._dayOfYear>oa(u)||e._dayOfYear===0)&&(A(e)._overflowDayOfYear=!0),a=da(u,0,e._dayOfYear),e._a[bt]=a.getUTCMonth(),e._a[ot]=a.getUTCDate()),t=0;t<3&&e._a[t]==null;++t)e._a[t]=i[t]=l[t];for(;t<7;t++)e._a[t]=i[t]=e._a[t]==null?t===2?1:0:e._a[t];e._a[xe]===24&&e._a[Ke]===0&&e._a[xt]===0&&e._a[Ft]===0&&(e._nextDay=!0,e._a[xe]=0),e._d=(e._useUTC?da:$s).apply(null,i),s=e._useUTC?e._d.getUTCDay():e._d.getDay(),e._tzm!=null&&e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),e._nextDay&&(e._a[xe]=24),e._w&&typeof e._w.d<"u"&&e._w.d!==s&&(A(e).weekdayMismatch=!0)}}function Rd(e){var t,a,i,l,s,u,D,M,p;t=e._w,t.GG!=null||t.W!=null||t.E!=null?(s=1,u=4,a=Ht(t.GG,e._a[Me],ca(oe(),1,4).year),i=Ht(t.W,1),l=Ht(t.E,1),(l<1||l>7)&&(M=!0)):(s=e._locale._week.dow,u=e._locale._week.doy,p=ca(oe(),s,u),a=Ht(t.gg,e._a[Me],p.year),i=Ht(t.w,p.week),t.d!=null?(l=t.d,(l<0||l>6)&&(M=!0)):t.e!=null?(l=t.e+s,(t.e<0||t.e>6)&&(M=!0)):l=s),i<1||i>_t(a,s,u)?A(e)._overflowWeeks=!0:M!=null?A(e)._overflowWeekday=!0:(D=In(a,i,l,s,u),e._a[Me]=D.year,e._dayOfYear=D.dayOfYear)}R.ISO_8601=function(){};R.RFC_2822=function(){};function qr(e){if(e._f===R.ISO_8601){jn(e);return}if(e._f===R.RFC_2822){zn(e);return}e._a=[],A(e).empty=!0;var t=""+e._i,a,i,l,s,u,D=t.length,M=0,p,b;for(l=Pn(e._f,e._locale).match(Or)||[],b=l.length,a=0;a<b;a++)s=l[a],i=(t.match(fs(s,e))||[])[0],i&&(u=t.substr(0,t.indexOf(i)),u.length>0&&A(e).unusedInput.push(u),t=t.slice(t.indexOf(i)+i.length),M+=i.length),Jt[s]?(i?A(e).empty=!1:A(e).unusedTokens.push(s),ps(s,i,e)):e._strict&&!i&&A(e).unusedTokens.push(s);A(e).charsLeftOver=D-M,t.length>0&&A(e).unusedInput.push(t),e._a[xe]<=12&&A(e).bigHour===!0&&e._a[xe]>0&&(A(e).bigHour=void 0),A(e).parsedDateParts=e._a.slice(0),A(e).meridiem=e._meridiem,e._a[xe]=Cd(e._locale,e._a[xe],e._meridiem),p=A(e).era,p!==null&&(e._a[Me]=e._locale.erasConvertYear(p,e._a[Me])),Hr(e),Gr(e)}function Cd(e,t,a){var i;return a==null?t:e.meridiemHour!=null?e.meridiemHour(t,a):(e.isPM!=null&&(i=e.isPM(a),i&&t<12&&(t+=12),!i&&t===12&&(t=0)),t)}function kd(e){var t,a,i,l,s,u,D=!1,M=e._f.length;if(M===0){A(e).invalidFormat=!0,e._d=new Date(NaN);return}for(l=0;l<M;l++)s=0,u=!1,t=$r({},e),e._useUTC!=null&&(t._useUTC=e._useUTC),t._f=e._f[l],qr(t),Wr(t)&&(u=!0),s+=A(t).charsLeftOver,s+=A(t).unusedTokens.length*10,A(t).score=s,D?s<i&&(i=s,a=t):(i==null||s<i||u)&&(i=s,a=t,u&&(D=!0));Tt(e,a||t)}function Td(e){if(!e._d){var t=Ir(e._i),a=t.day===void 0?t.date:t.day;e._a=_n([t.year,t.month,a,t.hour,t.minute,t.second,t.millisecond],function(i){return i&&parseInt(i,10)}),Hr(e)}}function wd(e){var t=new ma(Gr(Un(e)));return t._nextDay&&(t.add(1,"d"),t._nextDay=void 0),t}function Un(e){var t=e._i,a=e._f;return e._locale=e._locale||St(e._l),t===null||a===void 0&&t===""?Ea({nullInput:!0}):(typeof t=="string"&&(e._i=t=e._locale.preparse(t)),et(t)?new ma(Gr(t)):(ha(t)?e._d=t:Xe(a)?kd(e):a?qr(e):Wd(e),Wr(e)||(e._d=null),e))}function Wd(e){var t=e._i;Te(t)?e._d=new Date(R.now()):ha(t)?e._d=new Date(t.valueOf()):typeof t=="string"?Nd(e):Xe(t)?(e._a=_n(t.slice(0),function(a){return parseInt(a,10)}),Hr(e)):Lt(t)?Td(e):Dt(t)?e._d=new Date(t):R.createFromInputFallback(e)}function Vn(e,t,a,i,l){var s={};return(t===!0||t===!1)&&(i=t,t=void 0),(a===!0||a===!1)&&(i=a,a=void 0),(Lt(e)&&wr(e)||Xe(e)&&e.length===0)&&(e=void 0),s._isAMomentObject=!0,s._useUTC=s._isUTC=l,s._l=a,s._i=e,s._f=t,s._strict=i,wd(s)}function oe(e,t,a,i){return Vn(e,t,a,i,!1)}var $d=qe("moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var e=oe.apply(null,arguments);return this.isValid()&&e.isValid()?e<this?this:e:Ea()}),Yd=qe("moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var e=oe.apply(null,arguments);return this.isValid()&&e.isValid()?e>this?this:e:Ea()});function Gn(e,t){var a,i;if(t.length===1&&Xe(t[0])&&(t=t[0]),!t.length)return oe();for(a=t[0],i=1;i<t.length;++i)(!t[i].isValid()||t[i][e](a))&&(a=t[i]);return a}function Od(){var e=[].slice.call(arguments,0);return Gn("isBefore",e)}function Id(){var e=[].slice.call(arguments,0);return Gn("isAfter",e)}var Fd=function(){return Date.now?Date.now():+new Date},la=["year","quarter","month","week","day","hour","minute","second","millisecond"];function Ld(e){var t,a=!1,i,l=la.length;for(t in e)if(ae(e,t)&&!(pe.call(la,t)!==-1&&(e[t]==null||!isNaN(e[t]))))return!1;for(i=0;i<l;++i)if(e[la[i]]){if(a)return!1;parseFloat(e[la[i]])!==Q(e[la[i]])&&(a=!0)}return!0}function Ad(){return this._isValid}function Ed(){return tt(NaN)}function Ja(e){var t=Ir(e),a=t.year||0,i=t.quarter||0,l=t.month||0,s=t.week||t.isoWeek||0,u=t.day||0,D=t.hour||0,M=t.minute||0,p=t.second||0,b=t.millisecond||0;this._isValid=Ld(t),this._milliseconds=+b+p*1e3+M*6e4+D*1e3*60*60,this._days=+u+s*7,this._months=+l+i*3+a*12,this._data={},this._locale=St(),this._bubble()}function $a(e){return e instanceof Ja}function Rr(e){return e<0?Math.round(-1*e)*-1:Math.round(e)}function jd(e,t,a){var i=Math.min(e.length,t.length),l=Math.abs(e.length-t.length),s=0,u;for(u=0;u<i;u++)Q(e[u])!==Q(t[u])&&s++;return s+l}function Hn(e,t){$(e,0,0,function(){var a=this.utcOffset(),i="+";return a<0&&(a=-a,i="-"),i+dt(~~(a/60),2)+t+dt(~~a%60,2)})}Hn("Z",":");Hn("ZZ","");C("Z",Ga);C("ZZ",Ga);ie(["Z","ZZ"],function(e,t,a){a._useUTC=!0,a._tzm=Jr(Ga,e)});var zd=/([\+\-]|\d\d)/gi;function Jr(e,t){var a=(t||"").match(e),i,l,s;return a===null?null:(i=a[a.length-1]||[],l=(i+"").match(zd)||["-",0,0],s=+(l[1]*60)+Q(l[2]),s===0?0:l[0]==="+"?s:-s)}function Br(e,t){var a,i;return t._isUTC?(a=t.clone(),i=(et(e)||ha(e)?e.valueOf():oe(e).valueOf())-a.valueOf(),a._d.setTime(a._d.valueOf()+i),R.updateOffset(a,!1),a):oe(e).local()}function Cr(e){return-Math.round(e._d.getTimezoneOffset())}R.updateOffset=function(){};function Ud(e,t,a){var i=this._offset||0,l;if(!this.isValid())return e!=null?this:NaN;if(e!=null){if(typeof e=="string"){if(e=Jr(Ga,e),e===null)return this}else Math.abs(e)<16&&!a&&(e=e*60);return!this._isUTC&&t&&(l=Cr(this)),this._offset=e,this._isUTC=!0,l!=null&&this.add(l,"m"),i!==e&&(!t||this._changeInProgress?Bn(this,tt(e-i,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,R.updateOffset(this,!0),this._changeInProgress=null)),this}else return this._isUTC?i:Cr(this)}function Vd(e,t){return e!=null?(typeof e!="string"&&(e=-e),this.utcOffset(e,t),this):-this.utcOffset()}function Gd(e){return this.utcOffset(0,e)}function Hd(e){return this._isUTC&&(this.utcOffset(0,e),this._isUTC=!1,e&&this.subtract(Cr(this),"m")),this}function qd(){if(this._tzm!=null)this.utcOffset(this._tzm,!1,!0);else if(typeof this._i=="string"){var e=Jr(hs,this._i);e!=null?this.utcOffset(e):this.utcOffset(0,!0)}return this}function Jd(e){return this.isValid()?(e=e?oe(e).utcOffset():0,(this.utcOffset()-e)%60===0):!1}function Bd(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()}function Qd(){if(!Te(this._isDSTShifted))return this._isDSTShifted;var e={},t;return $r(e,this),e=Un(e),e._a?(t=e._isUTC?ct(e._a):oe(e._a),this._isDSTShifted=this.isValid()&&jd(e._a,t.toArray())>0):this._isDSTShifted=!1,this._isDSTShifted}function Zd(){return this.isValid()?!this._isUTC:!1}function Kd(){return this.isValid()?this._isUTC:!1}function qn(){return this.isValid()?this._isUTC&&this._offset===0:!1}var Xd=/^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/,ec=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;function tt(e,t){var a=e,i=null,l,s,u;return $a(e)?a={ms:e._milliseconds,d:e._days,M:e._months}:Dt(e)||!isNaN(+e)?(a={},t?a[t]=+e:a.milliseconds=+e):(i=Xd.exec(e))?(l=i[1]==="-"?-1:1,a={y:0,d:Q(i[ot])*l,h:Q(i[xe])*l,m:Q(i[Ke])*l,s:Q(i[xt])*l,ms:Q(Rr(i[Ft]*1e3))*l}):(i=ec.exec(e))?(l=i[1]==="-"?-1:1,a={y:It(i[2],l),M:It(i[3],l),w:It(i[4],l),d:It(i[5],l),h:It(i[6],l),m:It(i[7],l),s:It(i[8],l)}):a==null?a={}:typeof a=="object"&&("from"in a||"to"in a)&&(u=tc(oe(a.from),oe(a.to)),a={},a.ms=u.milliseconds,a.M=u.months),s=new Ja(a),$a(e)&&ae(e,"_locale")&&(s._locale=e._locale),$a(e)&&ae(e,"_isValid")&&(s._isValid=e._isValid),s}tt.fn=Ja.prototype;tt.invalid=Ed;function It(e,t){var a=e&&parseFloat(e.replace(",","."));return(isNaN(a)?0:a)*t}function tn(e,t){var a={};return a.months=t.month()-e.month()+(t.year()-e.year())*12,e.clone().add(a.months,"M").isAfter(t)&&--a.months,a.milliseconds=+t-+e.clone().add(a.months,"M"),a}function tc(e,t){var a;return e.isValid()&&t.isValid()?(t=Br(t,e),e.isBefore(t)?a=tn(e,t):(a=tn(t,e),a.milliseconds=-a.milliseconds,a.months=-a.months),a):{milliseconds:0,months:0}}function Jn(e,t){return function(a,i){var l,s;return i!==null&&!isNaN(+i)&&(Sn(t,"moment()."+t+"(period, number) is deprecated. Please use moment()."+t+"(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info."),s=a,a=i,i=s),l=tt(a,i),Bn(this,l,e),this}}function Bn(e,t,a,i){var l=t._milliseconds,s=Rr(t._days),u=Rr(t._months);e.isValid()&&(i=i??!0,u&&$n(e,sa(e,"Month")+u*a),s&&Tn(e,"Date",sa(e,"Date")+s*a),l&&e._d.setTime(e._d.valueOf()+l*a),i&&R.updateOffset(e,s||u))}var ac=Jn(1,"add"),rc=Jn(-1,"subtract");function Qn(e){return typeof e=="string"||e instanceof String}function ic(e){return et(e)||ha(e)||Qn(e)||Dt(e)||lc(e)||nc(e)||e===null||e===void 0}function nc(e){var t=Lt(e)&&!wr(e),a=!1,i=["years","year","y","months","month","M","days","day","d","dates","date","D","hours","hour","h","minutes","minute","m","seconds","second","s","milliseconds","millisecond","ms"],l,s,u=i.length;for(l=0;l<u;l+=1)s=i[l],a=a||ae(e,s);return t&&a}function lc(e){var t=Xe(e),a=!1;return t&&(a=e.filter(function(i){return!Dt(i)&&Qn(e)}).length===0),t&&a}function oc(e){var t=Lt(e)&&!wr(e),a=!1,i=["sameDay","nextDay","lastDay","nextWeek","lastWeek","sameElse"],l,s;for(l=0;l<i.length;l+=1)s=i[l],a=a||ae(e,s);return t&&a}function sc(e,t){var a=e.diff(t,"days",!0);return a<-6?"sameElse":a<-1?"lastWeek":a<0?"lastDay":a<1?"sameDay":a<2?"nextDay":a<7?"nextWeek":"sameElse"}function dc(e,t){arguments.length===1&&(arguments[0]?ic(arguments[0])?(e=arguments[0],t=void 0):oc(arguments[0])&&(t=arguments[0],e=void 0):(e=void 0,t=void 0));var a=e||oe(),i=Br(a,this).startOf("day"),l=R.calendarFormat(this,i)||"sameElse",s=t&&(ut(t[l])?t[l].call(this,a):t[l]);return this.format(s||this.localeData().calendar(l,this,oe(a)))}function cc(){return new ma(this)}function uc(e,t){var a=et(e)?e:oe(e);return this.isValid()&&a.isValid()?(t=Je(t)||"millisecond",t==="millisecond"?this.valueOf()>a.valueOf():a.valueOf()<this.clone().startOf(t).valueOf()):!1}function hc(e,t){var a=et(e)?e:oe(e);return this.isValid()&&a.isValid()?(t=Je(t)||"millisecond",t==="millisecond"?this.valueOf()<a.valueOf():this.clone().endOf(t).valueOf()<a.valueOf()):!1}function mc(e,t,a,i){var l=et(e)?e:oe(e),s=et(t)?t:oe(t);return this.isValid()&&l.isValid()&&s.isValid()?(i=i||"()",(i[0]==="("?this.isAfter(l,a):!this.isBefore(l,a))&&(i[1]===")"?this.isBefore(s,a):!this.isAfter(s,a))):!1}function fc(e,t){var a=et(e)?e:oe(e),i;return this.isValid()&&a.isValid()?(t=Je(t)||"millisecond",t==="millisecond"?this.valueOf()===a.valueOf():(i=a.valueOf(),this.clone().startOf(t).valueOf()<=i&&i<=this.clone().endOf(t).valueOf())):!1}function gc(e,t){return this.isSame(e,t)||this.isAfter(e,t)}function pc(e,t){return this.isSame(e,t)||this.isBefore(e,t)}function yc(e,t,a){var i,l,s;if(!this.isValid())return NaN;if(i=Br(e,this),!i.isValid())return NaN;switch(l=(i.utcOffset()-this.utcOffset())*6e4,t=Je(t),t){case"year":s=Ya(this,i)/12;break;case"month":s=Ya(this,i);break;case"quarter":s=Ya(this,i)/3;break;case"second":s=(this-i)/1e3;break;case"minute":s=(this-i)/6e4;break;case"hour":s=(this-i)/36e5;break;case"day":s=(this-i-l)/864e5;break;case"week":s=(this-i-l)/6048e5;break;default:s=this-i}return a?s:He(s)}function Ya(e,t){if(e.date()<t.date())return-Ya(t,e);var a=(t.year()-e.year())*12+(t.month()-e.month()),i=e.clone().add(a,"months"),l,s;return t-i<0?(l=e.clone().add(a-1,"months"),s=(t-i)/(i-l)):(l=e.clone().add(a+1,"months"),s=(t-i)/(l-i)),-(a+s)||0}R.defaultFormat="YYYY-MM-DDTHH:mm:ssZ";R.defaultFormatUtc="YYYY-MM-DDTHH:mm:ss[Z]";function bc(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")}function xc(e){if(!this.isValid())return null;var t=e!==!0,a=t?this.clone().utc():this;return a.year()<0||a.year()>9999?Wa(a,t?"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYYYY-MM-DD[T]HH:mm:ss.SSSZ"):ut(Date.prototype.toISOString)?t?this.toDate().toISOString():new Date(this.valueOf()+this.utcOffset()*60*1e3).toISOString().replace("Z",Wa(a,"Z")):Wa(a,t?"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYY-MM-DD[T]HH:mm:ss.SSSZ")}function vc(){if(!this.isValid())return"moment.invalid(/* "+this._i+" */)";var e="moment",t="",a,i,l,s;return this.isLocal()||(e=this.utcOffset()===0?"moment.utc":"moment.parseZone",t="Z"),a="["+e+'("]',i=0<=this.year()&&this.year()<=9999?"YYYY":"YYYYYY",l="-MM-DD[T]HH:mm:ss.SSS",s=t+'[")]',this.format(a+i+l+s)}function _c(e){e||(e=this.isUtc()?R.defaultFormatUtc:R.defaultFormat);var t=Wa(this,e);return this.localeData().postformat(t)}function Dc(e,t){return this.isValid()&&(et(e)&&e.isValid()||oe(e).isValid())?tt({to:this,from:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()}function Sc(e){return this.from(oe(),e)}function Pc(e,t){return this.isValid()&&(et(e)&&e.isValid()||oe(e).isValid())?tt({from:this,to:e}).locale(this.locale()).humanize(!t):this.localeData().invalidDate()}function Nc(e){return this.to(oe(),e)}function Zn(e){var t;return e===void 0?this._locale._abbr:(t=St(e),t!=null&&(this._locale=t),this)}var Kn=qe("moment().lang() is deprecated. Instead, use moment().localeData() to get the language configuration. Use moment().locale() to change languages.",function(e){return e===void 0?this.localeData():this.locale(e)});function Xn(){return this._locale}var Fa=1e3,Bt=60*Fa,La=60*Bt,el=(365*400+97)*24*La;function Qt(e,t){return(e%t+t)%t}function tl(e,t,a){return e<100&&e>=0?new Date(e+400,t,a)-el:new Date(e,t,a).valueOf()}function al(e,t,a){return e<100&&e>=0?Date.UTC(e+400,t,a)-el:Date.UTC(e,t,a)}function Mc(e){var t,a;if(e=Je(e),e===void 0||e==="millisecond"||!this.isValid())return this;switch(a=this._isUTC?al:tl,e){case"year":t=a(this.year(),0,1);break;case"quarter":t=a(this.year(),this.month()-this.month()%3,1);break;case"month":t=a(this.year(),this.month(),1);break;case"week":t=a(this.year(),this.month(),this.date()-this.weekday());break;case"isoWeek":t=a(this.year(),this.month(),this.date()-(this.isoWeekday()-1));break;case"day":case"date":t=a(this.year(),this.month(),this.date());break;case"hour":t=this._d.valueOf(),t-=Qt(t+(this._isUTC?0:this.utcOffset()*Bt),La);break;case"minute":t=this._d.valueOf(),t-=Qt(t,Bt);break;case"second":t=this._d.valueOf(),t-=Qt(t,Fa);break}return this._d.setTime(t),R.updateOffset(this,!0),this}function Rc(e){var t,a;if(e=Je(e),e===void 0||e==="millisecond"||!this.isValid())return this;switch(a=this._isUTC?al:tl,e){case"year":t=a(this.year()+1,0,1)-1;break;case"quarter":t=a(this.year(),this.month()-this.month()%3+3,1)-1;break;case"month":t=a(this.year(),this.month()+1,1)-1;break;case"week":t=a(this.year(),this.month(),this.date()-this.weekday()+7)-1;break;case"isoWeek":t=a(this.year(),this.month(),this.date()-(this.isoWeekday()-1)+7)-1;break;case"day":case"date":t=a(this.year(),this.month(),this.date()+1)-1;break;case"hour":t=this._d.valueOf(),t+=La-Qt(t+(this._isUTC?0:this.utcOffset()*Bt),La)-1;break;case"minute":t=this._d.valueOf(),t+=Bt-Qt(t,Bt)-1;break;case"second":t=this._d.valueOf(),t+=Fa-Qt(t,Fa)-1;break}return this._d.setTime(t),R.updateOffset(this,!0),this}function Cc(){return this._d.valueOf()-(this._offset||0)*6e4}function kc(){return Math.floor(this.valueOf()/1e3)}function Tc(){return new Date(this.valueOf())}function wc(){var e=this;return[e.year(),e.month(),e.date(),e.hour(),e.minute(),e.second(),e.millisecond()]}function Wc(){var e=this;return{years:e.year(),months:e.month(),date:e.date(),hours:e.hours(),minutes:e.minutes(),seconds:e.seconds(),milliseconds:e.milliseconds()}}function $c(){return this.isValid()?this.toISOString():null}function Yc(){return Wr(this)}function Oc(){return Tt({},A(this))}function Ic(){return A(this).overflow}function Fc(){return{input:this._i,format:this._f,locale:this._locale,isUTC:this._isUTC,strict:this._strict}}$("N",0,0,"eraAbbr");$("NN",0,0,"eraAbbr");$("NNN",0,0,"eraAbbr");$("NNNN",0,0,"eraName");$("NNNNN",0,0,"eraNarrow");$("y",["y",1],"yo","eraYear");$("y",["yy",2],0,"eraYear");$("y",["yyy",3],0,"eraYear");$("y",["yyyy",4],0,"eraYear");C("N",Qr);C("NN",Qr);C("NNN",Qr);C("NNNN",Jc);C("NNNNN",Bc);ie(["N","NN","NNN","NNNN","NNNNN"],function(e,t,a,i){var l=a._locale.erasParse(e,i,a._strict);l?A(a).era=l:A(a).invalidEra=e});C("y",Kt);C("yy",Kt);C("yyy",Kt);C("yyyy",Kt);C("yo",Qc);ie(["y","yy","yyy","yyyy"],Me);ie(["yo"],function(e,t,a,i){var l;a._locale._eraYearOrdinalRegex&&(l=e.match(a._locale._eraYearOrdinalRegex)),a._locale.eraYearOrdinalParse?t[Me]=a._locale.eraYearOrdinalParse(e,l):t[Me]=parseInt(e,10)});function Lc(e,t){var a,i,l,s=this._eras||St("en")._eras;for(a=0,i=s.length;a<i;++a){switch(typeof s[a].since){case"string":l=R(s[a].since).startOf("day"),s[a].since=l.valueOf();break}switch(typeof s[a].until){case"undefined":s[a].until=1/0;break;case"string":l=R(s[a].until).startOf("day").valueOf(),s[a].until=l.valueOf();break}}return s}function Ac(e,t,a){var i,l,s=this.eras(),u,D,M;for(e=e.toUpperCase(),i=0,l=s.length;i<l;++i)if(u=s[i].name.toUpperCase(),D=s[i].abbr.toUpperCase(),M=s[i].narrow.toUpperCase(),a)switch(t){case"N":case"NN":case"NNN":if(D===e)return s[i];break;case"NNNN":if(u===e)return s[i];break;case"NNNNN":if(M===e)return s[i];break}else if([u,D,M].indexOf(e)>=0)return s[i]}function Ec(e,t){var a=e.since<=e.until?1:-1;return t===void 0?R(e.since).year():R(e.since).year()+(t-e.offset)*a}function jc(){var e,t,a,i=this.localeData().eras();for(e=0,t=i.length;e<t;++e)if(a=this.clone().startOf("day").valueOf(),i[e].since<=a&&a<=i[e].until||i[e].until<=a&&a<=i[e].since)return i[e].name;return""}function zc(){var e,t,a,i=this.localeData().eras();for(e=0,t=i.length;e<t;++e)if(a=this.clone().startOf("day").valueOf(),i[e].since<=a&&a<=i[e].until||i[e].until<=a&&a<=i[e].since)return i[e].narrow;return""}function Uc(){var e,t,a,i=this.localeData().eras();for(e=0,t=i.length;e<t;++e)if(a=this.clone().startOf("day").valueOf(),i[e].since<=a&&a<=i[e].until||i[e].until<=a&&a<=i[e].since)return i[e].abbr;return""}function Vc(){var e,t,a,i,l=this.localeData().eras();for(e=0,t=l.length;e<t;++e)if(a=l[e].since<=l[e].until?1:-1,i=this.clone().startOf("day").valueOf(),l[e].since<=i&&i<=l[e].until||l[e].until<=i&&i<=l[e].since)return(this.year()-R(l[e].since).year())*a+l[e].offset;return this.year()}function Gc(e){return ae(this,"_erasNameRegex")||Zr.call(this),e?this._erasNameRegex:this._erasRegex}function Hc(e){return ae(this,"_erasAbbrRegex")||Zr.call(this),e?this._erasAbbrRegex:this._erasRegex}function qc(e){return ae(this,"_erasNarrowRegex")||Zr.call(this),e?this._erasNarrowRegex:this._erasRegex}function Qr(e,t){return t.erasAbbrRegex(e)}function Jc(e,t){return t.erasNameRegex(e)}function Bc(e,t){return t.erasNarrowRegex(e)}function Qc(e,t){return t._eraYearOrdinalRegex||Kt}function Zr(){var e=[],t=[],a=[],i=[],l,s,u,D,M,p=this.eras();for(l=0,s=p.length;l<s;++l)u=vt(p[l].name),D=vt(p[l].abbr),M=vt(p[l].narrow),t.push(u),e.push(D),a.push(M),i.push(u),i.push(D),i.push(M);this._erasRegex=new RegExp("^("+i.join("|")+")","i"),this._erasNameRegex=new RegExp("^("+t.join("|")+")","i"),this._erasAbbrRegex=new RegExp("^("+e.join("|")+")","i"),this._erasNarrowRegex=new RegExp("^("+a.join("|")+")","i")}$(0,["gg",2],0,function(){return this.weekYear()%100});$(0,["GG",2],0,function(){return this.isoWeekYear()%100});function Ba(e,t){$(0,[e,e.length],0,t)}Ba("gggg","weekYear");Ba("ggggg","weekYear");Ba("GGGG","isoWeekYear");Ba("GGGGG","isoWeekYear");C("G",Va);C("g",Va);C("GG",se,Ue);C("gg",se,Ue);C("GGGG",Lr,Fr);C("gggg",Lr,Fr);C("GGGGG",Ua,ja);C("ggggg",Ua,ja);ga(["gggg","ggggg","GGGG","GGGGG"],function(e,t,a,i){t[i.substr(0,2)]=Q(e)});ga(["gg","GG"],function(e,t,a,i){t[i]=R.parseTwoDigitYear(e)});function Zc(e){return rl.call(this,e,this.week(),this.weekday()+this.localeData()._week.dow,this.localeData()._week.dow,this.localeData()._week.doy)}function Kc(e){return rl.call(this,e,this.isoWeek(),this.isoWeekday(),1,4)}function Xc(){return _t(this.year(),1,4)}function eu(){return _t(this.isoWeekYear(),1,4)}function tu(){var e=this.localeData()._week;return _t(this.year(),e.dow,e.doy)}function au(){var e=this.localeData()._week;return _t(this.weekYear(),e.dow,e.doy)}function rl(e,t,a,i,l){var s;return e==null?ca(this,i,l).year:(s=_t(e,i,l),t>s&&(t=s),ru.call(this,e,t,a,i,l))}function ru(e,t,a,i,l){var s=In(e,t,a,i,l),u=da(s.year,0,s.dayOfYear);return this.year(u.getUTCFullYear()),this.month(u.getUTCMonth()),this.date(u.getUTCDate()),this}$("Q",0,"Qo","quarter");C("Q",Nn);ie("Q",function(e,t){t[bt]=(Q(e)-1)*3});function iu(e){return e==null?Math.ceil((this.month()+1)/3):this.month((e-1)*3+this.month()%3)}$("D",["DD",2],"Do","date");C("D",se,Xt);C("DD",se,Ue);C("Do",function(e,t){return e?t._dayOfMonthOrdinalParse||t._ordinalParse:t._dayOfMonthOrdinalParseLenient});ie(["D","DD"],ot);ie("Do",function(e,t){t[ot]=Q(e.match(se)[0])});var il=ea("Date",!0);$("DDD",["DDDD",3],"DDDo","dayOfYear");C("DDD",za);C("DDDD",Mn);ie(["DDD","DDDD"],function(e,t,a){a._dayOfYear=Q(e)});function nu(e){var t=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return e==null?t:this.add(e-t,"d")}$("m",["mm",2],0,"minute");C("m",se,Ar);C("mm",se,Ue);ie(["m","mm"],Ke);var lu=ea("Minutes",!1);$("s",["ss",2],0,"second");C("s",se,Ar);C("ss",se,Ue);ie(["s","ss"],xt);var ou=ea("Seconds",!1);$("S",0,0,function(){return~~(this.millisecond()/100)});$(0,["SS",2],0,function(){return~~(this.millisecond()/10)});$(0,["SSS",3],0,"millisecond");$(0,["SSSS",4],0,function(){return this.millisecond()*10});$(0,["SSSSS",5],0,function(){return this.millisecond()*100});$(0,["SSSSSS",6],0,function(){return this.millisecond()*1e3});$(0,["SSSSSSS",7],0,function(){return this.millisecond()*1e4});$(0,["SSSSSSSS",8],0,function(){return this.millisecond()*1e5});$(0,["SSSSSSSSS",9],0,function(){return this.millisecond()*1e6});C("S",za,Nn);C("SS",za,Ue);C("SSS",za,Mn);var wt,nl;for(wt="SSSS";wt.length<=9;wt+="S")C(wt,Kt);function su(e,t){t[Ft]=Q(("0."+e)*1e3)}for(wt="S";wt.length<=9;wt+="S")ie(wt,su);nl=ea("Milliseconds",!1);$("z",0,0,"zoneAbbr");$("zz",0,0,"zoneName");function du(){return this._isUTC?"UTC":""}function cu(){return this._isUTC?"Coordinated Universal Time":""}var _=ma.prototype;_.add=ac;_.calendar=dc;_.clone=cc;_.diff=yc;_.endOf=Rc;_.format=_c;_.from=Dc;_.fromNow=Sc;_.to=Pc;_.toNow=Nc;_.get=vs;_.invalidAt=Ic;_.isAfter=uc;_.isBefore=hc;_.isBetween=mc;_.isSame=fc;_.isSameOrAfter=gc;_.isSameOrBefore=pc;_.isValid=Yc;_.lang=Kn;_.locale=Zn;_.localeData=Xn;_.max=Yd;_.min=$d;_.parsingFlags=Oc;_.set=_s;_.startOf=Mc;_.subtract=rc;_.toArray=wc;_.toObject=Wc;_.toDate=Tc;_.toISOString=xc;_.inspect=vc;typeof Symbol<"u"&&Symbol.for!=null&&(_[Symbol.for("nodejs.util.inspect.custom")]=function(){return"Moment<"+this.format()+">"});_.toJSON=$c;_.toString=bc;_.unix=kc;_.valueOf=Cc;_.creationData=Fc;_.eraName=jc;_.eraNarrow=zc;_.eraAbbr=Uc;_.eraYear=Vc;_.year=kn;_.isLeapYear=xs;_.weekYear=Zc;_.isoWeekYear=Kc;_.quarter=_.quarters=iu;_.month=Yn;_.daysInMonth=Ts;_.week=_.weeks=Ls;_.isoWeek=_.isoWeeks=As;_.weeksInYear=tu;_.weeksInWeekYear=au;_.isoWeeksInYear=Xc;_.isoWeeksInISOWeekYear=eu;_.date=il;_.day=_.days=Ks;_.weekday=Xs;_.isoWeekday=ed;_.dayOfYear=nu;_.hour=_.hours=od;_.minute=_.minutes=lu;_.second=_.seconds=ou;_.millisecond=_.milliseconds=nl;_.utcOffset=Ud;_.utc=Gd;_.local=Hd;_.parseZone=qd;_.hasAlignedHourOffset=Jd;_.isDST=Bd;_.isLocal=Zd;_.isUtcOffset=Kd;_.isUtc=qn;_.isUTC=qn;_.zoneAbbr=du;_.zoneName=cu;_.dates=qe("dates accessor is deprecated. Use date instead.",il);_.months=qe("months accessor is deprecated. Use month instead",Yn);_.years=qe("years accessor is deprecated. Use year instead",kn);_.zone=qe("moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/",Vd);_.isDSTShifted=qe("isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information",Qd);function uu(e){return oe(e*1e3)}function hu(){return oe.apply(null,arguments).parseZone()}function ll(e){return e}var re=Yr.prototype;re.calendar=Zo;re.longDateFormat=ts;re.invalidDate=rs;re.ordinal=ls;re.preparse=ll;re.postformat=ll;re.relativeTime=ss;re.pastFuture=ds;re.set=Bo;re.eras=Lc;re.erasParse=Ac;re.erasConvertYear=Ec;re.erasAbbrRegex=Hc;re.erasNameRegex=Gc;re.erasNarrowRegex=qc;re.months=Ms;re.monthsShort=Rs;re.monthsParse=ks;re.monthsRegex=Ws;re.monthsShortRegex=ws;re.week=Ys;re.firstDayOfYear=Fs;re.firstDayOfWeek=Is;re.weekdays=qs;re.weekdaysMin=Bs;re.weekdaysShort=Js;re.weekdaysParse=Zs;re.weekdaysRegex=td;re.weekdaysShortRegex=ad;re.weekdaysMinRegex=rd;re.isPM=nd;re.meridiem=sd;function Aa(e,t,a,i){var l=St(),s=ct().set(i,t);return l[a](s,e)}function ol(e,t,a){if(Dt(e)&&(t=e,e=void 0),e=e||"",t!=null)return Aa(e,t,a,"month");var i,l=[];for(i=0;i<12;i++)l[i]=Aa(e,i,a,"month");return l}function Kr(e,t,a,i){typeof e=="boolean"?(Dt(t)&&(a=t,t=void 0),t=t||""):(t=e,a=t,e=!1,Dt(t)&&(a=t,t=void 0),t=t||"");var l=St(),s=e?l._week.dow:0,u,D=[];if(a!=null)return Aa(t,(a+s)%7,i,"day");for(u=0;u<7;u++)D[u]=Aa(t,(u+s)%7,i,"day");return D}function mu(e,t){return ol(e,t,"months")}function fu(e,t){return ol(e,t,"monthsShort")}function gu(e,t,a){return Kr(e,t,a,"weekdays")}function pu(e,t,a){return Kr(e,t,a,"weekdaysShort")}function yu(e,t,a){return Kr(e,t,a,"weekdaysMin")}Wt("en",{eras:[{since:"0001-01-01",until:1/0,offset:1,name:"Anno Domini",narrow:"AD",abbr:"AD"},{since:"0000-12-31",until:-1/0,offset:1,name:"Before Christ",narrow:"BC",abbr:"BC"}],dayOfMonthOrdinalParse:/\d{1,2}(th|st|nd|rd)/,ordinal:function(e){var t=e%10,a=Q(e%100/10)===1?"th":t===1?"st":t===2?"nd":t===3?"rd":"th";return e+a}});R.lang=qe("moment.lang is deprecated. Use moment.locale instead.",Wt);R.langData=qe("moment.langData is deprecated. Use moment.localeData instead.",St);var pt=Math.abs;function bu(){var e=this._data;return this._milliseconds=pt(this._milliseconds),this._days=pt(this._days),this._months=pt(this._months),e.milliseconds=pt(e.milliseconds),e.seconds=pt(e.seconds),e.minutes=pt(e.minutes),e.hours=pt(e.hours),e.months=pt(e.months),e.years=pt(e.years),this}function sl(e,t,a,i){var l=tt(t,a);return e._milliseconds+=i*l._milliseconds,e._days+=i*l._days,e._months+=i*l._months,e._bubble()}function xu(e,t){return sl(this,e,t,1)}function vu(e,t){return sl(this,e,t,-1)}function an(e){return e<0?Math.floor(e):Math.ceil(e)}function _u(){var e=this._milliseconds,t=this._days,a=this._months,i=this._data,l,s,u,D,M;return e>=0&&t>=0&&a>=0||e<=0&&t<=0&&a<=0||(e+=an(kr(a)+t)*864e5,t=0,a=0),i.milliseconds=e%1e3,l=He(e/1e3),i.seconds=l%60,s=He(l/60),i.minutes=s%60,u=He(s/60),i.hours=u%24,t+=He(u/24),M=He(dl(t)),a+=M,t-=an(kr(M)),D=He(a/12),a%=12,i.days=t,i.months=a,i.years=D,this}function dl(e){return e*4800/146097}function kr(e){return e*146097/4800}function Du(e){if(!this.isValid())return NaN;var t,a,i=this._milliseconds;if(e=Je(e),e==="month"||e==="quarter"||e==="year")switch(t=this._days+i/864e5,a=this._months+dl(t),e){case"month":return a;case"quarter":return a/3;case"year":return a/12}else switch(t=this._days+Math.round(kr(this._months)),e){case"week":return t/7+i/6048e5;case"day":return t+i/864e5;case"hour":return t*24+i/36e5;case"minute":return t*1440+i/6e4;case"second":return t*86400+i/1e3;case"millisecond":return Math.floor(t*864e5)+i;default:throw new Error("Unknown unit "+e)}}function Pt(e){return function(){return this.as(e)}}var cl=Pt("ms"),Su=Pt("s"),Pu=Pt("m"),Nu=Pt("h"),Mu=Pt("d"),Ru=Pt("w"),Cu=Pt("M"),ku=Pt("Q"),Tu=Pt("y"),wu=cl;function Wu(){return tt(this)}function $u(e){return e=Je(e),this.isValid()?this[e+"s"]():NaN}function At(e){return function(){return this.isValid()?this._data[e]:NaN}}var Yu=At("milliseconds"),Ou=At("seconds"),Iu=At("minutes"),Fu=At("hours"),Lu=At("days"),Au=At("months"),Eu=At("years");function ju(){return He(this.days()/7)}var yt=Math.round,qt={ss:44,s:45,m:45,h:22,d:26,w:null,M:11};function zu(e,t,a,i,l){return l.relativeTime(t||1,!!a,e,i)}function Uu(e,t,a,i){var l=tt(e).abs(),s=yt(l.as("s")),u=yt(l.as("m")),D=yt(l.as("h")),M=yt(l.as("d")),p=yt(l.as("M")),b=yt(l.as("w")),z=yt(l.as("y")),ne=s<=a.ss&&["s",s]||s<a.s&&["ss",s]||u<=1&&["m"]||u<a.m&&["mm",u]||D<=1&&["h"]||D<a.h&&["hh",D]||M<=1&&["d"]||M<a.d&&["dd",M];return a.w!=null&&(ne=ne||b<=1&&["w"]||b<a.w&&["ww",b]),ne=ne||p<=1&&["M"]||p<a.M&&["MM",p]||z<=1&&["y"]||["yy",z],ne[2]=t,ne[3]=+e>0,ne[4]=i,zu.apply(null,ne)}function Vu(e){return e===void 0?yt:typeof e=="function"?(yt=e,!0):!1}function Gu(e,t){return qt[e]===void 0?!1:t===void 0?qt[e]:(qt[e]=t,e==="s"&&(qt.ss=t-1),!0)}function Hu(e,t){if(!this.isValid())return this.localeData().invalidDate();var a=!1,i=qt,l,s;return typeof e=="object"&&(t=e,e=!1),typeof e=="boolean"&&(a=e),typeof t=="object"&&(i=Object.assign({},qt,t),t.s!=null&&t.ss==null&&(i.ss=t.s-1)),l=this.localeData(),s=Uu(this,!a,i,l),a&&(s=l.pastFuture(+this,s)),l.postformat(s)}var br=Math.abs;function Vt(e){return(e>0)-(e<0)||+e}function Qa(){if(!this.isValid())return this.localeData().invalidDate();var e=br(this._milliseconds)/1e3,t=br(this._days),a=br(this._months),i,l,s,u,D=this.asSeconds(),M,p,b,z;return D?(i=He(e/60),l=He(i/60),e%=60,i%=60,s=He(a/12),a%=12,u=e?e.toFixed(3).replace(/\.?0+$/,""):"",M=D<0?"-":"",p=Vt(this._months)!==Vt(D)?"-":"",b=Vt(this._days)!==Vt(D)?"-":"",z=Vt(this._milliseconds)!==Vt(D)?"-":"",M+"P"+(s?p+s+"Y":"")+(a?p+a+"M":"")+(t?b+t+"D":"")+(l||i||e?"T":"")+(l?z+l+"H":"")+(i?z+i+"M":"")+(e?z+u+"S":"")):"P0D"}var Z=Ja.prototype;Z.isValid=Ad;Z.abs=bu;Z.add=xu;Z.subtract=vu;Z.as=Du;Z.asMilliseconds=cl;Z.asSeconds=Su;Z.asMinutes=Pu;Z.asHours=Nu;Z.asDays=Mu;Z.asWeeks=Ru;Z.asMonths=Cu;Z.asQuarters=ku;Z.asYears=Tu;Z.valueOf=wu;Z._bubble=_u;Z.clone=Wu;Z.get=$u;Z.milliseconds=Yu;Z.seconds=Ou;Z.minutes=Iu;Z.hours=Fu;Z.days=Lu;Z.weeks=ju;Z.months=Au;Z.years=Eu;Z.humanize=Hu;Z.toISOString=Qa;Z.toString=Qa;Z.toJSON=Qa;Z.locale=Zn;Z.localeData=Xn;Z.toIsoString=qe("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",Qa);Z.lang=Kn;$("X",0,0,"unix");$("x",0,0,"valueOf");C("x",Va);C("X",ms);ie("X",function(e,t,a){a._d=new Date(parseFloat(e)*1e3)});ie("x",function(e,t,a){a._d=new Date(Q(e))});//! moment.js
R.version="2.30.1";qo(oe);R.fn=_;R.min=Od;R.max=Id;R.now=Fd;R.utc=ct;R.unix=uu;R.months=mu;R.isDate=ha;R.locale=Wt;R.invalid=Ea;R.duration=tt;R.isMoment=et;R.weekdays=gu;R.parseZone=hu;R.localeData=St;R.isDuration=$a;R.monthsShort=fu;R.weekdaysMin=yu;R.defineLocale=Vr;R.updateLocale=hd;R.locales=md;R.weekdaysShort=pu;R.normalizeUnits=Je;R.relativeTimeRounding=Vu;R.relativeTimeThreshold=Gu;R.calendarFormat=sc;R.prototype=_;R.HTML5_FMT={DATETIME_LOCAL:"YYYY-MM-DDTHH:mm",DATETIME_LOCAL_SECONDS:"YYYY-MM-DDTHH:mm:ss",DATETIME_LOCAL_MS:"YYYY-MM-DDTHH:mm:ss.SSS",DATE:"YYYY-MM-DD",TIME:"HH:mm",TIME_SECONDS:"HH:mm:ss",TIME_MS:"HH:mm:ss.SSS",WEEK:"GGGG-[W]WW",MONTH:"YYYY-MM"};function qu({row:e}){const[t,a]=S.useState(null),i=(e==null?void 0:e.shiftProducts)??[],l=u=>u.productVariant?`${u.productName} ${u.productVariant}`:u.productName;if(i.length===0){const u=(e==null?void 0:e.productName)??"-",D=e==null?void 0:e.productVariant;return n(P,{variant:"body2",children:D?`${u} ${D}`:u})}const s=i[0];return g(j,{sx:{display:"flex",alignItems:"center",gap:.5,width:"100%",overflow:"hidden"},children:[n(P,{variant:"body2",noWrap:!0,sx:{flex:1},children:l(s)}),i.length>1&&g(kt,{children:[n(vr,{title:`${i.length} products`,children:n(Zt,{size:"small",onClick:u=>a(u.currentTarget),children:n(Ro,{fontSize:"small"})})}),n(Wo,{open:!!t,anchorEl:t,onClose:()=>a(null),anchorOrigin:{vertical:"bottom",horizontal:"left"},children:g(j,{sx:{p:2,minWidth:220},children:[n(P,{variant:"subtitle2",sx:{mb:1,fontWeight:600},children:"Products"}),i.map((u,D)=>n(P,{variant:"body2",sx:{py:.25},children:l(u)},D))]})})]})]})}function sh(){var Ei;const[e,t]=S.useState(""),[a,i]=S.useState([]),[l,s]=S.useState(""),[u,D]=S.useState(""),[M,p]=S.useState([]),[b,z]=S.useState(""),[ne,N]=S.useState([]),[v,V]=S.useState(""),[ye,w]=S.useState([]);new Date().toISOString().split("T")[0];const[T,K]=S.useState({}),[m,Ie]=S.useState("getTopSeller"),[be,Be]=S.useState(!1),[Fe,ve]=S.useState("Daily"),[X,Le]=S.useState({page:0,pageSize:10}),[at,f]=S.useState(0),[y,E]=S.useState(""),[G,H]=S.useState(!1),[F,L]=S.useState("custom"),[W,Ve]=S.useState(null),rt=(r,o,d,x)=>{const q=R(d).diff(R(o),"days");let he="Daily";q>30&&q<=180?he="Weekly":q>180&&q<=730?he="Monthly":q>730&&(he="Yearly");const I={},J=ee=>x==="getPurchaseMaterial"?ee.totalInvoiceAmount||0:ee.totalAmount||0;return r.forEach(ee=>{const Ae=R(ee.createdDate);let Ne="";he==="Daily"&&(Ne=Ae.format("YYYY-MM-DD")),he==="Weekly"&&(Ne=Ae.startOf("week").format("YYYY-[W]WW")),he==="Monthly"&&(Ne=Ae.format("YYYY-MM")),he==="Yearly"&&(Ne=Ae.format("YYYY")),I[Ne]||(I[Ne]=0),I[Ne]+=J(ee)}),{groupType:he,groupedData:Object.keys(I).map(ee=>({date:ee,revenue:I[ee]}))}},ht=S.useRef(null),[Nt]=Yo(),[h]=Io(),[O]=Fo(),[Re]=jo(),[Et,{isLoading:Xr}]=Ql(),[Za,{isLoading:ei}]=Zl(),[Ka,{isLoading:ta}]=Kl(),[Xa,{isLoading:k}]=Xl(),[Mt,{isLoading:er}]=eo(),[pa,{isLoading:tr}]=to(),[ul,{isLoading:Ju}]=ao(),[hl,{isLoading:Bu}]=ro(),[ml,{isLoading:Qu}]=io(),[fl,{isLoading:Zu}]=ln(),[gl,{isLoading:Ku}]=on(),[pl,{isLoading:Xu}]=sn(),[ti]=no(),[ai]=lo(),[ri]=oo(),[ii]=so(),[ni]=co(),[li]=uo(),[oi]=ho(),[mt,ya]=S.useState(""),[Ge,si]=S.useState(""),[$t,di]=S.useState(null),[aa,ci]=S.useState([]),[ui,hi]=S.useState(!1),[ba,mi]=S.useState([]),[fi,gi]=S.useState(!1),[ue,Yt]=S.useState(null),[Pe,pi]=S.useState([]),[xa,yi]=S.useState([]),[va,bi]=S.useState(null),[_a,xi]=S.useState([]),[ar,vi]=S.useState(""),[Da,_i]=S.useState([]),[rr,Di]=S.useState(null),[ir,Si]=S.useState([]),[Pi,Ni]=S.useState(!1),[yl]=Lo(),[bl]=Eo(),[xl]=Oo(),[vl]=Ao(),[Mi,_l]=S.useState(null),Dl=!!Mi,[Ri,Ci]=S.useState(null),Sl=!!Ri,Sa=()=>_l(null),Pl=r=>{Ci(r.currentTarget)},ki=()=>{Ci(null)},ft=r=>{const o=new Date;let d="",x=o.toISOString().split("T")[0];switch(r){case"today":d=x;break;case"yesterday":const q=new Date(o);q.setDate(q.getDate()-1),d=q.toISOString().split("T")[0],x=d;break;case"last7":const he=new Date(o);he.setDate(he.getDate()-7),d=he.toISOString().split("T")[0];break;case"last30":const I=new Date(o);I.setDate(I.getDate()-30),d=I.toISOString().split("T")[0];break;case"last90":const J=new Date(o);J.setDate(J.getDate()-90),d=J.toISOString().split("T")[0];break;case"thisWeek":const ee=new Date(o);ee.setDate(o.getDate()-o.getDay()),d=ee.toISOString().split("T")[0];break;case"thisMonth":d=new Date(o.getFullYear(),o.getMonth(),1).toISOString().split("T")[0];break;case"thisYear":d=new Date(o.getFullYear(),0,1).toISOString().split("T")[0];break;case"lastMonth":const Ae=new Date(o.getFullYear(),o.getMonth()-1,1),Ne=new Date(o.getFullYear(),o.getMonth(),0);d=Ae.toISOString().split("T")[0],x=Ne.toISOString().split("T")[0];break;default:return}t(d),z(x),L(r),ki()},Ti=()=>{t(""),z(""),s(""),D(""),Yt(null),bi(null),vi(""),Di(null),ya(""),si(""),di(null),p([]),N([]),w([]),K({}),Be(!1),E(""),L("custom"),Le({page:0,pageSize:10}),f(0),Ve(null)},Nl=()=>{Ti(),V("")},Ml=r=>{const o=it();if(r==="getDailyProductionReport"||r==="getDaywiseReport")s(o.format("YYYY-MM-DD"));else if(r==="getWeeklyPlantProductionReport"){const d=o.endOf("week");t(o.startOf("week").format("YYYY-MM-DD")),z((d.isAfter(o)?o:d).format("YYYY-MM-DD")),L("thisWeek")}else if(r==="getMonthlyPlantProductionReport"){const d=o.endOf("month");t(o.startOf("month").format("YYYY-MM-DD")),z((d.isAfter(o)?o:d).format("YYYY-MM-DD")),L("thisMonth")}},Rl=r=>{Ti(),V(r),Ml(r)};S.useEffect(()=>{if(!y.trim())N(M);else{const r=M.filter(o=>{const d=y.toLowerCase();return Object.values(o).some(x=>x==null?void 0:x.toString().toLowerCase().includes(d))});N(r)}},[y,M]),S.useEffect(()=>{if(!["getPlantMaterialReport","getPlantwiseReport","getMachinewiseReport","getDailyProductionReport","getPlanVsActualReport","getDailyPlantProductionReport","getWeeklyPlantProductionReport","getMonthlyPlantProductionReport","getJobCardCostReport"].includes(v)||Pe.length>0)return;let o=!1;return(async()=>{try{const d=await ai({page:0,size:200,searchByName:{searchValue:""}}).unwrap();if(o)return;pi((d==null?void 0:d.data)??[])}catch{o||pi([])}})(),()=>{o=!0}},[v,Pe.length,ai]),S.useEffect(()=>{if(v!=="getMachinewiseReport"||ba.length>0)return;let r=!1;return(async()=>{try{gi(!0);const o=await ri({page:0,size:500,searchByName:{searchValue:""}}).unwrap();if(r)return;const d=(o==null?void 0:o.VendorsDetailsDTOList)??(o==null?void 0:o.data)??[];mi(Array.isArray(d)?d:[])}catch{r||mi([])}finally{r||gi(!1)}})(),()=>{r=!0}},[v,ba.length,ri]),S.useEffect(()=>{if(!["getVehicleTripReport","getDayWiseTripReport"].includes(v)||aa.length>0)return;let o=!1;return(async()=>{try{hi(!0);const d=await ti({page:0,size:500,searchByName:{searchValue:""}}).unwrap();if(o)return;const x=(d==null?void 0:d.data)??[];ci(Array.isArray(x)?x:[])}catch{o||ci([])}finally{o||hi(!1)}})(),()=>{o=!0}},[v,aa.length,ti]),S.useEffect(()=>{if(!["getDailyProductionReport","getPlanVsActualReport"].includes(v)||xa.length>0)return;let o=!1;return(async()=>{try{const d=await ni({page:0,size:200,searchByName:{searchValue:""}}).unwrap();if(o)return;yi((d==null?void 0:d.data)??[])}catch{o||yi([])}})(),()=>{o=!0}},[v,xa.length,ni]),S.useEffect(()=>{if(v!=="getDailyProductionReport"||_a.length>0)return;let r=!1;return(async()=>{try{const o=await li({page:0,size:100,searchByName:{searchValue:""}}).unwrap();if(r)return;const d=(o==null?void 0:o.data)??[];xi(Array.isArray(d)?d:[])}catch{r||xi([])}})(),()=>{r=!0}},[v,_a.length,li]),S.useEffect(()=>{if(v!=="getPlanVsActualReport"||Da.length>0)return;let r=!1;return(async()=>{try{const o=await oi({page:0,size:200,type:"PRODUCT",searchByName:{searchValue:""}}).unwrap();if(r)return;_i((o==null?void 0:o.data)??[])}catch{r||_i([])}})(),()=>{r=!0}},[v,Da.length,oi]),S.useEffect(()=>{if(v!=="getJobCardCostReport"||ir.length>0)return;let r=!1;return(async()=>{try{Ni(!0);const o=await ii({page:0,size:1e3,searchByName:{searchValue:""}}).unwrap();if(r)return;const d=((o==null?void 0:o.data)??[]).map(x=>x==null?void 0:x.jobCardNo).filter(x=>!!x);Si(Array.from(new Set(d)))}catch{r||Si([])}finally{r||Ni(!1)}})(),()=>{r=!0}},[v,ir.length,ii]);const gt=async(r,o)=>{if(m){if(m==="getDaywiseReport"){if(!l)return}else if(m==="getMachinewiseReport"){if(!mt||!e||!b)return}else if(m==="getPlantwiseReport"){if(!u||!e||!b)return}else if(m==="getPlantMaterialReport"){if(!ue||!e||!b)return}else if(m==="getDailyProductionReport"){if(!l)return}else if(m==="getPlanVsActualReport"){if(!e||!b)return}else if(m==="getDailyPlantProductionReport"||m==="getWeeklyPlantProductionReport"||m==="getMonthlyPlantProductionReport"){if(!e||!b)return}else if(m!=="getJobCardCostReport"){if(!e||!b)return}H(!0),Ve(null);try{let d;if(m==="getTopSeller"?d=await Nt({page:r,size:o,payload:{from:e,to:b}}).unwrap():m==="getSalesReport"?d=await h({page:r,size:o,payload:{from:e,to:b}}).unwrap():m==="getPurchaseMaterial"?d=await O({page:r,size:o,payload:{from:e,to:b}}).unwrap():m==="getTopBuyer"?d=await Re({page:r,size:o,payload:{from:e,to:b}}).unwrap():m==="getDaywiseReport"?d=await Et({page:r,size:o,payload:{productionDate:l,plantName:u}}).unwrap():m==="getMachinewiseReport"?d=await Za({page:r,size:o,payload:{machineName:mt,fromDate:e,toDate:b,plantId:ue||null}}).unwrap():m==="getPlantwiseReport"?d=await Ka({page:r,size:o,payload:{plantName:u,fromDate:e,toDate:b}}).unwrap():m==="getPlantMaterialReport"?d=await Xa({page:r,size:o,payload:{plantId:ue,fromDate:e,toDate:b}}).unwrap():m==="getDailyProductionReport"?d=await Mt({page:r,size:o,payload:{productionDate:l,plantId:ue,unitId:va,shiftName:ar||null}}).unwrap():m==="getPlanVsActualReport"?d=await pa({page:r,size:o,payload:{fromDate:e,toDate:b,plantId:ue,unitId:va,productId:rr}}).unwrap():m==="getDailyPlantProductionReport"?d=await ul({page:r,size:o,payload:{plantId:ue,fromDate:e,toDate:b}}).unwrap():m==="getWeeklyPlantProductionReport"?d=await hl({page:r,size:o,payload:{plantId:ue,fromDate:e,toDate:b}}).unwrap():m==="getMonthlyPlantProductionReport"?d=await ml({page:r,size:o,payload:{plantId:ue,fromDate:e,toDate:b}}).unwrap():m==="getJobCardCostReport"?d=await fl({page:r,size:o,payload:{fromDate:e||null,toDate:b||null,jobCardNo:Ge||null,plantId:ue||null}}).unwrap():m==="getVehicleTripReport"?d=await gl({page:r,size:o,payload:{vehicleId:$t,fromDate:e,toDate:b}}).unwrap():m==="getDayWiseTripReport"&&(d=await pl({page:r,size:o,payload:{vehicleId:$t,fromDate:e,toDate:b}}).unwrap()),d&&d.data){const x=d.data;let q=Array.isArray(x)?x:[x];if(m==="getPurchaseMaterial"&&(q=q.filter(I=>Fi(I==null?void 0:I.type))),p(q),m==="getPurchaseMaterial"?f(q.length):d.totalCount!==void 0?f(d.totalCount):d.totalElements!==void 0?f(d.totalElements):f(q.length),!["getDaywiseReport","getMachinewiseReport","getPlantwiseReport","getPlantMaterialReport","getDailyProductionReport","getPlanVsActualReport","getDailyPlantProductionReport","getWeeklyPlantProductionReport","getMonthlyPlantProductionReport","getJobCardCostReport","getVehicleTripReport","getDayWiseTripReport"].includes(m)&&q.length>0){const{groupType:I,groupedData:J}=rt(q,e,b,m);J.sort((ee,Ae)=>new Date(ee.date).getTime()-new Date(Ae.date).getTime()),w(J),ve(I)}else if(m==="getDailyProductionReport"&&q.length>0){const I={};q.forEach(J=>{const ee=J.shift_name||J.shiftName||"Unknown";I[ee]=(I[ee]||0)+Number(J.produced_qty??J.producedQty??0)}),w(Object.keys(I).map(J=>({date:J,revenue:I[J]}))),ve("Shift")}else if((m==="getDailyPlantProductionReport"||m==="getWeeklyPlantProductionReport"||m==="getMonthlyPlantProductionReport")&&q.length>0){const I=q.map(J=>({date:J.period??J.periodStart??"-",periodStart:J.periodStart??J.period??"",revenue:Number(J.netProduced??0),totalProduced:Number(J.totalProduced??0),totalRejected:Number(J.totalRejected??0)})).sort((J,ee)=>String(J.periodStart).localeCompare(String(ee.periodStart)));w(I),ve(m==="getDailyPlantProductionReport"?"Daily":m==="getWeeklyPlantProductionReport"?"Weekly":"Monthly")}else if(m==="getPlanVsActualReport"&&q.length>0){const I={};q.forEach(ee=>{const Ae=ee.date||ee.created_date||"",Ne=Ae?R(Ae).format("YYYY-MM-DD"):"Unknown";I[Ne]||(I[Ne]={planned:0,actual:0}),I[Ne].planned+=Number(ee.planned_qty??ee.plannedQty??0),I[Ne].actual+=Number(ee.actual_produced_qty??ee.actualProducedQty??0)});const J=Object.keys(I).sort().map(ee=>({date:ee,revenue:I[ee].actual,planned:I[ee].planned,actual:I[ee].actual}));w(J),ve("Daily")}else w([]);d.summary?K(d.summary):K({})}else p([]),w([]),f(0)}catch(d){Ve(d),console.error("Error fetching report:",d),p([]),N([]),w([]),f(0)}finally{H(!1)}}};S.useEffect(()=>{!m||!be||(m==="getDaywiseReport"?l&&gt(X.page,X.pageSize):m==="getMachinewiseReport"?mt&&e&&b&&gt(X.page,X.pageSize):m==="getPlantwiseReport"?u&&e&&b&&gt(X.page,X.pageSize):m==="getPlantMaterialReport"?ue&&e&&b&&gt(X.page,X.pageSize):m==="getDailyProductionReport"?l&&gt(X.page,X.pageSize):m==="getPlanVsActualReport"||m==="getDailyPlantProductionReport"||m==="getWeeklyPlantProductionReport"||m==="getMonthlyPlantProductionReport"?e&&b&&gt(X.page,X.pageSize):(m==="getJobCardCostReport"||e&&b)&&gt(X.page,X.pageSize))},[X,e,b,l,mt,u,ue,va,ar,rr,Ge,m,be]);const Cl=r=>{r.preventDefault(),v&&(v==="getDaywiseReport"&&!l||v==="getMachinewiseReport"&&!mt||v==="getPlantwiseReport"&&(!u||!e||!b)||v==="getPlantMaterialReport"&&(!ue||!e||!b)||v==="getDailyProductionReport"&&!l||v==="getPlanVsActualReport"&&(!e||!b)||v==="getVehicleTripReport"&&!$t||(v==="getDailyPlantProductionReport"||v==="getWeeklyPlantProductionReport"||v==="getMonthlyPlantProductionReport")&&(!e||!b)||v!=="getDaywiseReport"&&v!=="getMachinewiseReport"&&v!=="getPlantwiseReport"&&v!=="getPlantMaterialReport"&&v!=="getDailyProductionReport"&&v!=="getPlanVsActualReport"&&v!=="getDailyPlantProductionReport"&&v!=="getWeeklyPlantProductionReport"&&v!=="getMonthlyPlantProductionReport"&&v!=="getJobCardCostReport"&&v!=="getVehicleTripReport"&&(!e||!b)||(Ie(v),Be(!0),Le(o=>({...o,page:0})),v==="getMachinewiseReport"&&wl(o=>o+1),v==="getJobCardCostReport"&&Ge&&Fl(o=>o+1),v==="getVehicleTripReport"&&jl(o=>o+1)))},Pa=()=>{switch(m){case"getTopSeller":return"Top Seller Report";case"getSalesReport":return"Sales Report";case"getPurchaseMaterial":return"Purchase Material Report";case"getTopBuyer":return"Top Buyers Report";case"getDaywiseReport":return"Daywise Report";case"getMachinewiseReport":return"Machinewise Report";case"getPlantwiseReport":return"Plantwise Report";case"getPlantMaterialReport":return"Plant-wise Material Request Report";case"getDailyProductionReport":return"Daily Production Report (DPR)";case"getPlanVsActualReport":return"Production Plan vs Actual Report";case"getDailyPlantProductionReport":return"Daily Plant Production Report";case"getWeeklyPlantProductionReport":return"Weekly Plant Production Report";case"getMonthlyPlantProductionReport":return"Monthly Plant Production Report";case"getJobCardCostReport":return"Job Card Cost Report";case"getVehicleTripReport":return"Vehicle Fuel Report";case"getDayWiseTripReport":return"Day-wise Trip Sheet";default:return"Report"}},[eh,kl]=S.useState([]),[Ot,wi]=S.useState(null),[Wi,$i]=S.useState(null),[Tl,wl]=S.useState(0),Yi=S.useRef(null),[Wl,$l]=S.useState(!1),Oi=S.useRef(null),[Yl,Ol]=S.useState(!1),[Il,Fl]=S.useState(0),Ii=S.useRef(null),[Ll,Al]=S.useState(!1),[El,jl]=S.useState(0),zl=async()=>{if(M.length===0)return;const r=window.open("","_blank","width=1200,height=800");if(!r)return;const o=Li[m],d=1e5;let x=[];m==="getPurchaseMaterial"?x=((await yl({page:0,size:d,payload:{from:e,to:b}}).unwrap()).data||[]).filter(J=>Fi(J==null?void 0:J.type)):m==="getSalesReport"?x=(await vl({page:0,size:d,payload:{from:e,to:b}}).unwrap()).data||[]:m==="getTopBuyer"?x=(await bl({page:0,size:d,payload:{from:e,to:b}}).unwrap()).data||[]:m==="getTopSeller"?x=(await xl({page:0,size:d,payload:{from:e,to:b}}).unwrap()).data||[]:x=M,kl(x);const q=x.map(I=>Ai[m](I)),he=`
      <!DOCTYPE html>
      <html>
        <head>
          <title>${Pa()}</title>
          <style>
            @media print {
              @page {
                size: A4 landscape;
                margin: 1cm;
              }
            }
            * {
              margin: 0;
              padding: 0;
              box-sizing: border-box;
            }
            body {
              font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
              padding: 20px;
              color: #333;
              background: #fff;
            }
            .print-header {
              display: flex;
              align-items: center;
              justify-content: space-between;
              margin-bottom: 30px;
              border-bottom: 3px solid #1976d2;
              padding-bottom: 15px;
            }
            .header-left {
              display: flex;
              align-items: center;
              gap: 15px;
            }
            .company-logo {
              width: 80px;
              height: 80px;
              background: #fff;
              border-radius: 8px;
              padding: 5px;
              box-shadow: 0 2px 8px rgba(0,0,0,0.1);
              display: flex;
              align-items: center;
              justify-content: center;
            }
            .company-logo img {
              width: 100%;
              height: 100%;
              object-fit: contain;
            }
            .logo-fallback {
              display: none;
              font-size: 24px;
              font-weight: bold;
              color: #1976d2;
            }
            .company-info {
              display: flex;
              flex-direction: column;
            }
            .company-name {
              font-size: 22px;
              font-weight: 700;
              color: #1976d2;
              margin-bottom: 5px;
              text-transform: uppercase;
            }
            .print-header-center {
              flex: 1;
              text-align: center;
            }
            .print-header h1 {
              font-size: 24px;
              color: #1976d2;
              font-weight: 700;
              margin-bottom: 10px;
            }
            .print-header .date-range {
              font-size: 14px;
              color: #666;
              margin-top: 5px;
            }
            .print-summary {
              display: flex;
              justify-content: space-around;
              margin-bottom: 25px;
              padding: 15px;
              background: #f5f5f5;
              border-radius: 5px;
            }
            .summary-item {
              text-align: center;
            }
            .summary-label {
              font-size: 12px;
              color: #666;
              margin-bottom: 5px;
            }
            .summary-value {
              font-size: 18px;
              font-weight: 700;
              color: #1976d2;
            }
            table {
              width: 100%;
              border-collapse: collapse;
              margin-top: 20px;
              font-size: 12px;
            }
            thead {
              background-color: #1976d2;
              color: #fff;
            }
            th {
              padding: 12px 8px;
              text-align: left;
              font-weight: 600;
              border: 1px solid #1565c0;
              font-size: 13px;
            }
            td {
              padding: 10px 8px;
              border: 1px solid #e0e0e0;
              text-align: left;
            }
            tbody tr:nth-child(even) {
              background-color: #f9f9f9;
            }
            tbody tr:hover {
              background-color: #f0f0f0;
            }
            .text-right {
              text-align: right;
            }
            .text-center {
              text-align: center;
            }
            .print-footer {
              margin-top: 30px;
              padding-top: 15px;
              border-top: 2px solid #e0e0e0;
              text-align: center;
              font-size: 11px;
              color: #666;
            }
            @media print {
              body {
                padding: 10px;
              }
              .print-header {
                margin-bottom: 20px;
                padding-bottom: 10px;
                flex-wrap: wrap;
              }
              .header-left {
                gap: 10px;
              }
              .company-logo {
                width: 60px;
                height: 60px;
                padding: 3px;
              }
              .company-name {
                font-size: 18px;
              }
              .print-header-center {
                margin-top: 10px;
                width: 100%;
              }
              .print-header h1 {
                font-size: 20px;
              }
              .print-summary {
                margin-bottom: 15px;
                padding: 10px;
              }
              table {
                font-size: 10px;
              }
              th, td {
                padding: 6px 4px;
              }
              .no-print {
                display: none;
              }
            }
          </style>
        </head>
        <body>
          <div class="print-header">
            <div class="header-left">
              <div class="company-info">
                <div class="company-name">PR BLOCKS</div>
              </div>
            </div>
            <div class="print-header-center">
              <h1>${Pa()}</h1>
              <div class="date-range">
                <strong>Date Range:</strong> ${de(e)} to ${de(b)}
              </div>
              <div class="date-range">
                <strong>Generated:</strong> ${new Date().toLocaleString("en-IN",{day:"2-digit",month:"2-digit",year:"numeric",hour:"2-digit",minute:"2-digit"})}
              </div>
            </div>
          </div>

          ${Object.keys(T).length>0?`
            <div class="print-summary">
              ${m==="getTopSeller"||m==="getSalesReport"?`
                <div class="summary-item">
                  <div class="summary-label">Total Clients</div>
                  <div class="summary-value">${T.totalClients||0}</div>
                </div>
                <div class="summary-item">
                  <div class="summary-label">Total Amount</div>
                  <div class="summary-value">₹ ${T.totalAmount?T.totalAmount.toLocaleString("en-IN"):"0.00"}</div>
                </div>
              `:""}
              ${m==="getPurchaseMaterial"?`
                <div class="summary-item">
               
                </div>
                <div class="summary-item">
                  <div class="summary-label">Purchase Total</div>
                  <div class="summary-value">₹ ${T.totalAmount?T.totalAmount.toLocaleString("en-IN"):"0.00"}</div>
                </div>
              `:""}
              ${m==="getTopBuyer"?`
                <div class="summary-item">
                  <div class="summary-label">Total Vendors</div>
                  <div class="summary-value">${T.totalClients||0}</div>
                </div>
                <div class="summary-item">
                  <div class="summary-label">Total Amount</div>
                  <div class="summary-value">₹ ${T.totalAmount?T.totalAmount.toLocaleString("en-IN"):"0.00"}</div>
                </div>
              `:""}
            </div>
          `:""}

          <table>
            <thead>
              <tr>
                ${o.map(I=>`<th>${I}</th>`).join("")}
              </tr>
            </thead>
            <tbody>
              ${q.map(I=>`
                <tr>
                  ${I.map((J,ee)=>{var ji,zi;const Ae=((ji=o[ee])==null?void 0:ji.toLowerCase().includes("amount"))||((zi=o[ee])==null?void 0:zi.toLowerCase().includes("total")),Ne=typeof J=="number"||!isNaN(parseFloat(J))&&isFinite(J);return`<td class="${Ae||Ne?"text-right":""}">${J||"-"}</td>`}).join("")}
                </tr>
              `).join("")}
            </tbody>
          </table>

          <div class="print-footer">
            <p>Total Records: ${x.length} </p>
          </div>
        </body>
      </html>
    `;r.document.write(he),r.document.close(),setTimeout(()=>{r.print()},250)},de=r=>{if(!r)return"-";const o=new Date(r);return isNaN(o.getTime())?"-":o.toLocaleDateString("en-IN",{day:"2-digit",month:"2-digit",year:"numeric"})},Fi=r=>{const o=String(r??"").toUpperCase().replace(/[\s-]+/g,"_");return o==="RAW_MATERIAL"||o==="CONSUMABLE"},ra=(r,o)=>{for(const d of o){const x=r==null?void 0:r[d];if(x!=null&&x!==""&&!Number.isNaN(Number(x)))return Number(x)}return 0},Qe=(r,o)=>{switch(o){case"material":return ra(r,["material_cost","materialCost","material_usage_cost","materialUsageCost"]);case"utility":return ra(r,["utility_charges","utilityCharges","utility_charge","utilityCharge"]);case"production":return ra(r,["production_cost","productionCost"]);case"total":return ra(r,["total_cost","totalCost"])||Qe(r,"material")+Qe(r,"utility")+Qe(r,"production");case"unit":return ra(r,["cost_per_unit","costPerUnit"]);default:return 0}},nr=r=>`₹ ${Number(r??0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,Ul=r=>{const o=String(r??"").toUpperCase(),d=o?o.replace(/_/g," ").replace(/\b\w/g,x=>x.toUpperCase()):"-";return["COMPLETED","DRYING_COMPLETED","SEND_TO_STOCK"].includes(o)?{label:d,color:"#2e7d32",bg:"rgba(46,125,50,0.12)"}:["RUNNING","IN_PROGRESS","STARTED","HOURLY_CLOSED","IN_DRYING","SEND_TO_RECYCLE"].includes(o)?{label:d,color:"#1565c0",bg:"rgba(21,101,192,0.12)"}:["HOLD"].includes(o)?{label:d,color:"#ed6c02",bg:"rgba(237,108,2,0.12)"}:["CANCELLED"].includes(o)?{label:d,color:"#d32f2f",bg:"rgba(211,47,47,0.12)"}:{label:d,color:"#616161",bg:"rgba(97,97,97,0.12)"}},Vl=r=>{switch(r){case"getTopSeller":return[{field:"clientName",headerName:"Client Name",flex:1,minWidth:150},{field:"name",headerName:"Name",flex:1,minWidth:150},{field:"totalAmount",headerName:"Total Amount",flex:1,minWidth:150,valueFormatter:o=>{var d;return`₹ ${((d=o.value)==null?void 0:d.toLocaleString("en-IN"))||"0.00"}`}},{field:"createdDate",headerName:"Date",flex:1,minWidth:120,valueFormatter:o=>de(o.value)}];case"getSalesReport":return[{field:"clientName",headerName:"Client Name",flex:1,minWidth:150},{field:"name",headerName:"Name",flex:1,minWidth:150},{field:"totalAmount",headerName:"Total Amount",flex:1,minWidth:150,valueFormatter:o=>{var d;return`₹ ${((d=o.value)==null?void 0:d.toLocaleString("en-IN"))||"0.00"}`}},{field:"createdDate",headerName:"Date",flex:1,minWidth:120,valueFormatter:o=>de(o.value)}];case"getPurchaseMaterial":return[{field:"type",headerName:"Product Type",flex:1,minWidth:120},{field:"invoiceNo",headerName:"Invoice No",flex:1,minWidth:120},{field:"vendorName",headerName:"Vendor Name",flex:1,minWidth:150,valueFormatter:o=>o.value||"N/A"},{field:"totalInvoiceAmount",headerName:"Total Amount",flex:1,minWidth:150,valueFormatter:o=>{var d;return`₹ ${((d=o.value)==null?void 0:d.toLocaleString("en-IN"))||"0.00"}`}},{field:"createdDate",headerName:"Date",flex:1,minWidth:120,valueFormatter:o=>de(o.value)}];case"getTopBuyer":return[{field:"vendorName",headerName:"Vendor Name",flex:1,minWidth:150},{field:"noOfInvoice",headerName:"No Of Invoice",flex:1,minWidth:120},{field:"totalAmount",headerName:"Total Amount",flex:1,minWidth:150,valueFormatter:o=>o.value?`₹ ${o.value.toLocaleString("en-IN")}`:"N/A"},{field:"createdDate",headerName:"Date",flex:1,minWidth:120,valueFormatter:o=>de(o.value)}];case"getDaywiseReport":return[{field:"production_date",headerName:"Production Date",flex:1,minWidth:120,valueFormatter:o=>de(o.value)},{field:"job_card_no",headerName:"Job Card No",flex:1,minWidth:150},{field:"total_produced",headerName:"Total Produced",flex:1}];case"getMachinewiseReport":{const o=d=>Number((d==null?void 0:d.value)??0).toLocaleString("en-IN");return[{field:"machineName",headerName:"Machine Name",flex:1,minWidth:150},{field:"machineCode",headerName:"Code",flex:.8,minWidth:110,valueFormatter:d=>(d==null?void 0:d.value)??"-"},{field:"machineType",headerName:"Type",flex:.9,minWidth:120,valueFormatter:d=>(d==null?void 0:d.value)??"-"},{field:"capacity",headerName:"Capacity",flex:.8,minWidth:100,valueFormatter:d=>(d==null?void 0:d.value)??"-"},{field:"condition",headerName:"Condition",flex:.8,minWidth:110,valueFormatter:d=>(d==null?void 0:d.value)??"-"},{field:"location",headerName:"Location",flex:.9,minWidth:120,valueFormatter:d=>(d==null?void 0:d.value)??"-"},{field:"status",headerName:"Status",flex:.8,minWidth:110,valueFormatter:d=>(d==null?void 0:d.value)??"-"},{field:"totalProduced",headerName:"Total Produced",flex:.9,minWidth:120,align:"right",headerAlign:"right",valueFormatter:o},{field:"totalRejected",headerName:"Total Rejected",flex:.9,minWidth:120,align:"right",headerAlign:"right",valueFormatter:o},{field:"netProduced",headerName:"Net Produced",flex:.9,minWidth:120,align:"right",headerAlign:"right",valueFormatter:o}]}case"getPlantwiseReport":{const o=d=>Number((d==null?void 0:d.value)??0).toLocaleString("en-IN");return[{field:"productionDate",headerName:"Date",flex:.9,minWidth:110,valueFormatter:d=>de(d.value)},{field:"plantName",headerName:"Plant",flex:1,minWidth:130},{field:"shiftName",headerName:"Shift",flex:.8,minWidth:100,valueFormatter:d=>(d==null?void 0:d.value)??"-"},{field:"jobCardNo",headerName:"Job Card No",flex:1,minWidth:130,valueFormatter:d=>(d==null?void 0:d.value)??"-"},{field:"shiftProducts",headerName:"Product",flex:1.3,minWidth:180,renderCell:d=>n(qu,{row:d.row})},{field:"totalProduced",headerName:"Produced",flex:.8,minWidth:100,align:"right",headerAlign:"right",valueFormatter:o},{field:"totalRejected",headerName:"Rejected",flex:.8,minWidth:100,align:"right",headerAlign:"right",valueFormatter:o},{field:"netProduced",headerName:"Net Produced",flex:.8,minWidth:110,align:"right",headerAlign:"right",valueFormatter:o}]}case"getPlantMaterialReport":{const o=x=>Number((x==null?void 0:x.value)??0).toLocaleString("en-IN");return[{field:"requested_date",headerName:"Date",flex:.9,minWidth:110,valueFormatter:x=>x!=null&&x.value?it(x.value).format("DD/MM/YYYY"):"-"},{field:"plant_name",headerName:"Plant",flex:1,minWidth:120},{field:"product_name",headerName:"Product",flex:1.2,minWidth:160,renderCell:x=>{var he;const q=Vi((he=x.row)==null?void 0:he.variant_payload).map(I=>`${I.name}: ${I.value}`).join(" · ");return g(j,{sx:{lineHeight:1.25,py:.5},children:[n(P,{variant:"body2",sx:{fontWeight:500},children:x.value??"-"}),q?n(P,{variant:"caption",color:"text.secondary",sx:{display:"block"},children:q}):null]})}},{field:"material_type",headerName:"Type",flex:.8,minWidth:110,valueFormatter:x=>(x==null?void 0:x.value)??"-"},{field:"requested_qty",headerName:"Requested",flex:.8,minWidth:100,align:"right",headerAlign:"right",valueFormatter:o},{field:"issued_qty",headerName:"Issued",flex:.8,minWidth:90,align:"right",headerAlign:"right",valueFormatter:o},{field:"remaining_qty",headerName:"Remaining",flex:.8,minWidth:100,align:"right",headerAlign:"right",valueFormatter:o},{field:"unit",headerName:"Unit",flex:.5,minWidth:70,valueFormatter:x=>(x==null?void 0:x.value)??"-"},{field:"landed_cost",headerName:"Landed Cost",flex:.9,minWidth:120,align:"right",headerAlign:"right",valueFormatter:x=>`₹ ${Number((x==null?void 0:x.value)??0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`}]}case"getDailyProductionReport":return[{field:"production_date",headerName:"Date",flex:1,minWidth:110,valueFormatter:o=>de(o.value)},{field:"shift_name",headerName:"Shift",flex:.8,minWidth:100},{field:"job_card_no",headerName:"Job Card No",flex:1,minWidth:130},{field:"product_name",headerName:"Product",flex:1,minWidth:160,renderCell:o=>{var q;const d=(q=o.row)==null?void 0:q.product_variant,x=d?`${o.value??"-"} ${d}`:o.value??"-";return n(P,{variant:"body2",sx:{fontWeight:500},children:x})}},{field:"planned_qty",headerName:"Planned Qty",flex:.8,minWidth:110,align:"right",headerAlign:"right"},{field:"produced_qty",headerName:"Produced Qty",flex:.8,minWidth:110,align:"right",headerAlign:"right"}];case"getWeeklyPlantProductionReport":{const o=d=>Number((d==null?void 0:d.value)??0).toLocaleString("en-IN");return[{field:"period",headerName:"Week",flex:.7,minWidth:100},{field:"productionDate",headerName:"Date",flex:.8,minWidth:110,valueFormatter:d=>d!=null&&d.value?de(d.value):"-"},{field:"plantName",headerName:"Plant",flex:1,minWidth:130},{field:"shiftName",headerName:"Shift",flex:.7,minWidth:90},{field:"jobCardNo",headerName:"Job Card No",flex:.9,minWidth:120},{field:"productName",headerName:"Product",flex:1.2,minWidth:160,renderCell:d=>{var he;const x=(he=d.row)==null?void 0:he.productVariant,q=x?`${d.value??"-"} ${x}`:d.value??"-";return n(P,{variant:"body2",sx:{fontWeight:500},children:q})}},{field:"totalProduced",headerName:"Produced",flex:.7,minWidth:100,align:"right",headerAlign:"right",valueFormatter:o},{field:"totalRejected",headerName:"Rejected",flex:.7,minWidth:100,align:"right",headerAlign:"right",valueFormatter:o},{field:"netProduced",headerName:"Net Produced",flex:.8,minWidth:110,align:"right",headerAlign:"right",renderCell:d=>n("span",{style:{fontWeight:600,color:"#2e7d32"},children:Number(d.value??0).toLocaleString("en-IN")})}]}case"getDailyPlantProductionReport":case"getMonthlyPlantProductionReport":return[{field:"period",headerName:r==="getDailyPlantProductionReport"?"Date":"Month",flex:.9,minWidth:110},{field:"plantName",headerName:"Plant",flex:1,minWidth:140},{field:"productName",headerName:"Product",flex:1.2,minWidth:160,valueFormatter:o=>(o==null?void 0:o.value)??"-"},{field:"totalProduced",headerName:"Total Produced",flex:.9,minWidth:120,align:"right",headerAlign:"right",valueFormatter:o=>Number((o==null?void 0:o.value)??0).toLocaleString("en-IN")},{field:"totalRejected",headerName:"Total Rejected",flex:.9,minWidth:120,align:"right",headerAlign:"right",valueFormatter:o=>Number((o==null?void 0:o.value)??0).toLocaleString("en-IN")},{field:"totalDryReject",headerName:"Dry Reject",flex:.8,minWidth:110,align:"right",headerAlign:"right",valueFormatter:o=>Number((o==null?void 0:o.value)??0).toLocaleString("en-IN")},{field:"netProduced",headerName:"Net Produced",flex:.9,minWidth:120,align:"right",headerAlign:"right",renderCell:o=>{const d=Number(o.value??0);return n("span",{style:{fontWeight:600,color:"#2e7d32"},children:d.toLocaleString("en-IN")})}},{field:"shiftCount",headerName:"Shifts",flex:.6,minWidth:80,align:"right",headerAlign:"right"},{field:"jobCardCount",headerName:"Job Cards",flex:.6,minWidth:90,align:"right",headerAlign:"right"}];case"getJobCardCostReport":return[{field:"production_date",headerName:"Date",flex:.9,minWidth:110,valueFormatter:o=>o!=null&&o.value?de(o.value):"-"},{field:"job_card_no",headerName:"Job Card No",flex:1,minWidth:130},{field:"product_name",headerName:"Product",flex:1,minWidth:140},{field:"plant_name",headerName:"Plant",flex:1,minWidth:130},{field:"net_produced_qty",headerName:"Net Produced",flex:.8,minWidth:110,align:"right",headerAlign:"right",valueFormatter:o=>Number((o==null?void 0:o.value)??0).toLocaleString("en-IN")},{field:"material_cost",headerName:"Material Cost",flex:.9,minWidth:120,align:"right",headerAlign:"right",renderCell:o=>nr(Qe(o.row,"material"))},{field:"utility_charges",headerName:"Utility Charges",flex:.9,minWidth:120,align:"right",headerAlign:"right",renderCell:o=>nr(Qe(o.row,"utility"))},{field:"production_cost",headerName:"Production Cost",flex:.9,minWidth:120,align:"right",headerAlign:"right",renderCell:o=>nr(Qe(o.row,"production"))},{field:"cost_per_unit",headerName:"Cost / Unit",flex:.8,minWidth:110,align:"right",headerAlign:"right",valueFormatter:o=>`₹ ${Number((o==null?void 0:o.value)??0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`}];case"getVehicleTripReport":return[{field:"vehicle_number",headerName:"Vehicle No",flex:1,minWidth:130},{field:"make_model",headerName:"Make / Model",flex:1,minWidth:150},{field:"driver_name",headerName:"Driver(s)",flex:1,minWidth:150,valueFormatter:d=>(d==null?void 0:d.value)||"-"},{field:"trip_count",headerName:"Trips",flex:.6,minWidth:80,align:"right",headerAlign:"right"},{field:"total_distance",headerName:"Distance (km)",flex:.9,minWidth:120,align:"right",headerAlign:"right",valueFormatter:d=>Number((d==null?void 0:d.value)??0).toLocaleString("en-IN")},{field:"total_fuel",headerName:"Fuel",flex:.8,minWidth:100,align:"right",headerAlign:"right",valueFormatter:d=>Number((d==null?void 0:d.value)??0).toLocaleString("en-IN")},{field:"total_fuel_cost",headerName:"Fuel Cost",flex:.9,minWidth:120,align:"right",headerAlign:"right",valueFormatter:d=>`₹ ${Number((d==null?void 0:d.value)??0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`},{field:"avg_mileage",headerName:"Avg Mileage",flex:.8,minWidth:110,align:"right",headerAlign:"right",valueFormatter:d=>Number((d==null?void 0:d.value)??0).toFixed(2)}];case"getDayWiseTripReport":return[{field:"trip_date",headerName:"Date",flex:.8,minWidth:105,valueFormatter:d=>d!=null&&d.value?de(d.value):"-"},{field:"vehicle_number",headerName:"Vehicle No",flex:.9,minWidth:120},{field:"driver_name",headerName:"Driver",flex:.9,minWidth:120},{field:"taken_by",headerName:"Taken By",flex:.9,minWidth:120},{field:"start_km",headerName:"Start KM",flex:.7,minWidth:95,align:"right",headerAlign:"right",valueFormatter:d=>(d==null?void 0:d.value)!=null?Number(d.value).toLocaleString("en-IN"):"-"},{field:"end_km",headerName:"End KM",flex:.7,minWidth:95,align:"right",headerAlign:"right",valueFormatter:d=>(d==null?void 0:d.value)!=null?Number(d.value).toLocaleString("en-IN"):"-"},{field:"distance",headerName:"Distance",flex:.7,minWidth:95,align:"right",headerAlign:"right",valueFormatter:d=>Number((d==null?void 0:d.value)??0).toLocaleString("en-IN")},{field:"fuel_added",headerName:"Fuel",flex:.6,minWidth:85,align:"right",headerAlign:"right",valueFormatter:d=>Number((d==null?void 0:d.value)??0).toLocaleString("en-IN")},{field:"fuel_cost",headerName:"Fuel Cost",flex:.8,minWidth:110,align:"right",headerAlign:"right",valueFormatter:d=>`₹ ${Number((d==null?void 0:d.value)??0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`},{field:"mileage",headerName:"Mileage",flex:.7,minWidth:95,align:"right",headerAlign:"right",valueFormatter:d=>Number((d==null?void 0:d.value)??0).toFixed(2)},{field:"status",headerName:"Status",flex:.7,minWidth:100}];case"getPlanVsActualReport":return[{field:"date",headerName:"Date",flex:1,minWidth:110,valueGetter:o=>{var d,x;return((d=o==null?void 0:o.row)==null?void 0:d.date)??((x=o==null?void 0:o.row)==null?void 0:x.created_date)??null},valueFormatter:o=>o!=null&&o.value?de(o.value):"-"},{field:"job_card_no",headerName:"Job Card No",flex:1,minWidth:130},{field:"product_name",headerName:"Product",flex:1,minWidth:160,renderCell:o=>{var x;const d=(x=o.row)==null?void 0:x.product_variant;return g(j,{sx:{lineHeight:1.25,py:.5},children:[n(P,{variant:"body2",sx:{fontWeight:500},children:o.value??"-"}),d?n(P,{variant:"caption",color:"text.secondary",sx:{display:"block"},children:d}):null]})}},{field:"planned_qty",headerName:"Planned Qty",flex:.8,minWidth:110,align:"right",headerAlign:"right"},{field:"actual_produced_qty",headerName:"Actual Qty",flex:.8,minWidth:110,align:"right",headerAlign:"right"},{field:"variance",headerName:"Variance",flex:.8,minWidth:110,align:"right",headerAlign:"right",renderCell:o=>{const d=Number(o.value??0),x=d<0;return n("span",{style:{color:x?"#d32f2f":"inherit",fontWeight:x?600:400},children:d.toFixed(2)})}},{field:"completion_percent",headerName:"Completion %",flex:.8,minWidth:120,align:"right",headerAlign:"right",valueFormatter:o=>`${Number((o==null?void 0:o.value)??0).toFixed(2)}%`}];default:return[]}},Li={getTopSeller:["Client Name","Name","Total Amount","Date"],getSalesReport:["Client Name","Name","Total Amount","Date"],getPurchaseMaterial:["Product Type","Invoice No","Vendor Name","Vendor Currency","Total InvoiceAmount","Date"],getTopBuyer:["Vendor Name","No Of Invoice","Total Amount","Date"],getDaywiseReport:["Production Date","Job Card No","Product","Morning Produced","Evening Produced","Total Produced"],getMachinewiseReport:["Machine Name","Code","Type","Capacity","Condition","Location","Status","Product","Total Produced","Net Produced"],getPlantwiseReport:["Date","Plant","Shift","Machine","Job Card No","Product","Produced","Rejected","Net Produced"],getPlantMaterialReport:["Request No","Date","Plant","Product","Type","Requested","Issued","Remaining","Unit","Landed Cost","Status"],getDailyProductionReport:["Date","Shift","Machine","Job Card No","Product","Status","Planned Qty","Produced Qty","Material Cost","Utility Charge","Efficiency %"],getPlanVsActualReport:["Date","Job Card No","Product","Planned Qty","Actual Qty","Variance","Completion %"],getJobCardCostReport:["Date","Job Card No","Product","Plant","Net Produced","Material Cost","Utility Charges","Production Cost","Total Cost","Cost / Unit"],getVehicleTripReport:["Vehicle No","Make / Model","Driver(s)","Trips","Distance (km)","Fuel","Fuel Cost","Avg Mileage"],getDayWiseTripReport:["Date","Vehicle No","Driver","Taken By","Start KM","End KM","Distance","Fuel","Fuel Cost","Mileage","Status"],getDailyPlantProductionReport:["Date","Plant","Total Produced","Total Rejected","Dry Reject","Net Produced","Material Cost","Utility","Production Cost","Total Cost","Shifts","Job Cards"],getWeeklyPlantProductionReport:["Week","Date","Plant","Shift","Machine","Job Card No","Product","Produced","Rejected","Net Produced","Material Cost","Utility","Production Cost","Total Cost"],getMonthlyPlantProductionReport:["Month","Plant","Total Produced","Total Rejected","Dry Reject","Net Produced","Material Cost","Utility","Production Cost","Total Cost","Shifts","Job Cards"]},Ai={getTopSeller:r=>[r.clientName,r.name,r.totalAmount,de(r.createdDate)],getSalesReport:r=>[r.clientName,r.name,r.totalAmount,de(r.createdDate)],getPurchaseMaterial:r=>[r.type,r.invoiceNo,r.vendorName?r.vendorName:"N/A",r.vendorCurrency?r.vendorCurrency:"N/A",r.totalInvoiceAmount,de(r.createdDate)],getDaywiseReport:r=>[de(r.production_date),r.job_card_no,r.product_variant?`${r.product_name??"-"} ${r.product_variant}`:r.product_name??"-",r.morning_produced,r.evening_produced,r.total_produced],getMachinewiseReport:r=>[r.machineName??r.machine_name??"-",r.machineCode??r.machine_code??"-",r.machineType??r.machine_type??"-",r.capacity??"-",r.condition??"-",r.location??"-",r.status??"-",r.product_variant?`${r.product_name??"-"} ${r.product_variant}`:r.product_name??"-",Number(r.totalProduced??r.total_produced??0).toLocaleString("en-IN"),Number(r.totalRejected??r.total_rejected??0).toLocaleString("en-IN"),Number(r.netProduced??r.net_produced??0).toLocaleString("en-IN")],getPlantwiseReport:r=>[de(r.productionDate),r.plantName??"-",r.shiftName??"-",r.machineName??"-",r.jobCardNo??"-",r.productVariant?`${r.productName??"-"} ${r.productVariant}`:r.productName??"-",Number(r.totalProduced??0).toLocaleString("en-IN"),Number(r.totalRejected??0).toLocaleString("en-IN"),Number(r.netProduced??0).toLocaleString("en-IN")],getPlantMaterialReport:r=>{const o=Vi(r==null?void 0:r.variant_payload).map(d=>`${d.name}: ${d.value}`).join(" · ");return[r.request_no,r.requested_date?it(r.requested_date).format("DD/MM/YYYY"):"-",r.plant_name,o?`${r.product_name??"-"} (${o})`:r.product_name??"-",r.material_type??"-",Number(r.requested_qty??0).toLocaleString("en-IN"),Number(r.issued_qty??0).toLocaleString("en-IN"),Number(r.remaining_qty??0).toLocaleString("en-IN"),r.unit??"-",Number(r.landed_cost??0).toFixed(2),Number(r.total_cost??0).toFixed(2),r.item_status??"-"]},getTopBuyer:r=>[r.vendorName,r.noOfInvoice,r.totalAmount?r.totalAmount:"N/A",de(r.createdDate)],getDailyProductionReport:r=>[de(r.production_date),r.shift_name??"-",r.machine_name??"-",r.job_card_no??"-",r.product_variant?`${r.product_name??"-"} ${r.product_variant}`:r.product_name??"-",Ul(r.status).label,r.planned_qty??0,r.produced_qty??0,Number(r.material_cost??0).toFixed(2),Number(r.utility_charge??0).toFixed(2),`${Number(r.efficiency_percent??0).toFixed(2)}%`],getPlanVsActualReport:r=>[de(r.date??r.created_date),r.job_card_no??"-",r.product_variant?`${r.product_name??"-"} ${r.product_variant}`:r.product_name??"-",r.planned_qty??0,r.actual_produced_qty??0,r.variance??0,`${Number(r.completion_percent??0).toFixed(2)}%`],getJobCardCostReport:r=>[de(r.production_date),r.job_card_no??"-",r.product_variant?`${r.product_name??"-"} ${r.product_variant}`:r.product_name??"-",r.plant_name??"-",Number(r.net_produced_qty??0).toLocaleString("en-IN"),Qe(r,"material").toFixed(2),Qe(r,"utility").toFixed(2),Qe(r,"production").toFixed(2),Qe(r,"total").toFixed(2),Qe(r,"unit").toFixed(2)],getVehicleTripReport:r=>[r.vehicle_number??"-",r.make_model??"-",r.driver_name??"-",r.trip_count??0,Number(r.total_distance??0).toLocaleString("en-IN"),Number(r.total_fuel??0).toLocaleString("en-IN"),Number(r.total_fuel_cost??0).toFixed(2),Number(r.avg_mileage??0).toFixed(2)],getDayWiseTripReport:r=>[de(r.trip_date),r.vehicle_number??"-",r.driver_name??"-",r.taken_by??"-",`${r.from_location??"-"} → ${r.to_location??"-"}`,r.start_km!=null?Number(r.start_km).toLocaleString("en-IN"):"-",r.end_km!=null?Number(r.end_km).toLocaleString("en-IN"):"-",Number(r.distance??0).toLocaleString("en-IN"),Number(r.fuel_added??0).toLocaleString("en-IN"),Number(r.fuel_cost??0).toFixed(2),Number(r.mileage??0).toFixed(2),r.status??"-"],getDailyPlantProductionReport:r=>[r.period??"-",r.plantName??"-",Number(r.totalProduced??0),Number(r.totalRejected??0),Number(r.totalDryReject??0),Number(r.netProduced??0),`₹ ${Number(r.materialCost??0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,`₹ ${Number(r.utilityCharge??0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,`₹ ${Number(r.productionCost??0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,`₹ ${(Number(r.materialCost??0)+Number(r.utilityCharge??0)+Number(r.productionCost??0)).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,Number(r.totalUpTime??0).toFixed(2),Number(r.shiftCount??0),Number(r.jobCardCount??0)],getWeeklyPlantProductionReport:r=>[r.period??"-",r.productionDate?de(r.productionDate):"-",r.plantName??"-",r.shiftName??"-",r.machineName??"-",r.jobCardNo??"-",r.productVariant?`${r.productName??"-"} ${r.productVariant}`:r.productName??"-",Number(r.totalProduced??0),Number(r.totalRejected??0),Number(r.netProduced??0),`₹ ${Number(r.materialCost??0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,`₹ ${Number(r.utilityCharge??0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,`₹ ${Number(r.productionCost??0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,`₹ ${(Number(r.materialCost??0)+Number(r.utilityCharge??0)+Number(r.productionCost??0)).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`],getMonthlyPlantProductionReport:r=>[r.period??"-",r.plantName??"-",Number(r.totalProduced??0),Number(r.totalRejected??0),Number(r.totalDryReject??0),Number(r.netProduced??0),`₹ ${Number(r.materialCost??0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,`₹ ${Number(r.utilityCharge??0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,`₹ ${Number(r.productionCost??0).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,`₹ ${(Number(r.materialCost??0)+Number(r.utilityCharge??0)+Number(r.productionCost??0)).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`,Number(r.totalUpTime??0).toFixed(2),Number(r.shiftCount??0),Number(r.jobCardCount??0)]},Gl=()=>{const r=ia.json_to_sheet(M),o=ia.book_new();ia.book_append_sheet(o,r,"Report"),yo(o,"report.xlsx"),Sa()},Hl=()=>{const r=ia.json_to_sheet(M),o=ia.sheet_to_csv(r),d=new Blob([o],{type:"text/csv"}),x=window.URL.createObjectURL(d),q=document.createElement("a");q.href=x,q.download="report.csv",q.click(),Sa()},ql=()=>{const r=new go("landscape"),o=Li[m],d=M.map(x=>Ai[m](x));po(r,{head:[o],body:d,startY:20}),r.save("report.pdf"),Sa()};return g(j,{p:3,sx:{width:"100%",minHeight:"100vh",bgcolor:"grey.50"},children:[g(Se,{elevation:0,sx:{mb:2.5,p:{xs:2.5,md:3},borderRadius:3,color:"common.white",background:"linear-gradient(135deg, #1565c0 0%, #1976d2 45%, #42a5f5 100%)",display:"flex",alignItems:"center",justifyContent:"space-between",flexWrap:"wrap",gap:2,boxShadow:"0 8px 24px rgba(25, 118, 210, 0.18)"},children:[g(j,{display:"flex",alignItems:"center",gap:2,children:[n(j,{sx:{width:56,height:56,borderRadius:"50%",bgcolor:"rgba(255,255,255,0.18)",display:"flex",alignItems:"center",justifyContent:"center",backdropFilter:"blur(8px)"},children:n(vo,{sx:{fontSize:32}})}),n(j,{children:n(P,{variant:"h5",fontWeight:800,lineHeight:1.15,children:"Reports"})})]}),v&&g(j,{sx:{px:2,py:1,borderRadius:2,bgcolor:"rgba(255,255,255,0.16)",display:"flex",alignItems:"center",gap:1,backdropFilter:"blur(8px)"},children:[n(_o,{fontSize:"small"}),n(P,{variant:"body2",fontWeight:600,children:Pa()})]})]}),g(Se,{sx:{p:{xs:2,md:3},borderRadius:3,boxShadow:"0 1px 3px rgba(0,0,0,0.06), 0 8px 24px rgba(0,0,0,0.04)"},children:[g(j,{display:"flex",alignItems:"center",gap:1,mb:2,sx:{pb:1.25,borderBottom:"1px solid",borderColor:"divider"},children:[n(Do,{color:"primary"}),n(P,{variant:"subtitle1",fontWeight:700,color:"primary.main",sx:{textTransform:"uppercase",letterSpacing:"0.04em"},children:"Filters"}),n(P,{variant:"caption",color:"text.secondary",sx:{ml:1},children:"Pick a report and the criteria to run"})]}),n("form",{onSubmit:Cl,children:g(Y,{container:!0,spacing:2,alignItems:"flex-end",sx:{mb:3},children:[n(Y,{item:!0,xs:12,sm:6,md:2,children:g(ko,{fullWidth:!0,size:"small",children:[n(To,{children:"Report Type"}),g(wo,{value:v,label:"Report Type",onChange:r=>Rl(r.target.value),children:[n(me,{value:"getPurchaseMaterial",children:"Purchase Material"}),n(me,{value:"getMachinewiseReport",children:"Machinewise"}),n(me,{value:"getPlantwiseReport",children:"Plantwise"}),n(me,{value:"getPlantMaterialReport",children:"Plant Material Request"}),n(me,{value:"getDailyProductionReport",children:"Daily Production (DPR)"}),n(me,{value:"getWeeklyPlantProductionReport",children:"Weekly Production"}),n(me,{value:"getMonthlyPlantProductionReport",children:"Monthly Production"}),n(me,{value:"getJobCardCostReport",children:"Job Card "}),n(me,{value:"getVehicleTripReport",children:"Vehicle Fuel Report"})]})]})}),v==="getJobCardCostReport"&&n(Y,{item:!0,xs:12,sm:6,md:2,children:n(Ee,{size:"small",fullWidth:!0,disabled:!!e||!!b,options:ir,loading:Pi,getOptionLabel:r=>typeof r=="string"?r:"",value:Ge||null,onChange:(r,o)=>si(o??""),renderInput:r=>n(je,{...r,label:"Job Card No *",InputProps:{...r.InputProps,endAdornment:g(kt,{children:[Pi?n(st,{size:16}):null,r.InputProps.endAdornment]})}})})}),(v==="getDaywiseReport"||v==="getDailyProductionReport")&&n(Y,{item:!0,xs:12,sm:6,md:1.8,children:n(lr,{dateAdapter:or,children:n(sr,{label:"Production Date",format:"DD-MM-YYYY",value:l?it(l):null,maxDate:it(),onChange:r=>{s(r?r.format("YYYY-MM-DD"):"")},slotProps:{textField:{size:"small",fullWidth:!0}}})})}),v==="getDailyProductionReport"&&g(kt,{children:[n(Y,{item:!0,xs:12,sm:6,md:2,children:n(Ee,{size:"small",fullWidth:!0,options:Pe,getOptionLabel:r=>(r==null?void 0:r.name)??"",isOptionEqualToValue:(r,o)=>(r==null?void 0:r.id)===(o==null?void 0:o.id),value:Pe.find(r=>(r==null?void 0:r.id)===ue)??null,onChange:(r,o)=>Yt((o==null?void 0:o.id)??null),renderInput:r=>n(je,{...r,label:"Plant"})})}),n(Y,{item:!0,xs:12,sm:6,md:2,children:n(Ee,{size:"small",fullWidth:!0,options:_a,getOptionLabel:r=>(r==null?void 0:r.shiftName)??(r==null?void 0:r.name)??"",value:_a.find(r=>((r==null?void 0:r.shiftName)??(r==null?void 0:r.name))===ar)??null,onChange:(r,o)=>vi((o==null?void 0:o.shiftName)??(o==null?void 0:o.name)??""),renderInput:r=>n(je,{...r,label:"Shift"})})})]}),v!=="getDaywiseReport"&&v!=="getDailyProductionReport"&&g(kt,{children:[n(Y,{item:!0,xs:12,sm:6,md:1.8,children:n(lr,{dateAdapter:or,children:n(sr,{label:"From Date",format:"DD-MM-YYYY",disabled:v==="getJobCardCostReport"&&!!Ge,value:e?it(e):null,maxDate:it(),onChange:r=>{t(r?r.format("YYYY-MM-DD"):"")},slotProps:{textField:{size:"small",fullWidth:!0}}})})}),n(Y,{item:!0,xs:12,sm:6,md:1.8,children:n(lr,{dateAdapter:or,children:n(sr,{label:"To Date",format:"DD-MM-YYYY",disabled:v==="getJobCardCostReport"&&!!Ge,value:b?it(b):null,minDate:e?it(e):void 0,maxDate:it(),onChange:r=>{z(r?r.format("YYYY-MM-DD"):"")},slotProps:{textField:{size:"small",fullWidth:!0}}})})}),v==="getMachinewiseReport"&&n(Y,{item:!0,xs:12,sm:6,md:2,children:n(Ee,{size:"small",fullWidth:!0,options:ba,loading:fi,getOptionLabel:r=>typeof r=="string"?r:(r==null?void 0:r.machineName)??"",isOptionEqualToValue:(r,o)=>((r==null?void 0:r.machineName)??r)===((o==null?void 0:o.machineName)??o),value:ba.find(r=>(r==null?void 0:r.machineName)===mt)??(mt||null),onChange:(r,o)=>{ya(o?typeof o=="string"?o:o.machineName??"":"")},renderInput:r=>n(je,{...r,label:"Machine Name",InputProps:{...r.InputProps,endAdornment:g(kt,{children:[fi?n(st,{size:16}):null,r.InputProps.endAdornment]})}})})}),v==="getMachinewiseReport"&&n(Y,{item:!0,xs:12,sm:6,md:2,children:n(Ee,{size:"small",fullWidth:!0,options:Pe,getOptionLabel:r=>(r==null?void 0:r.name)??"",isOptionEqualToValue:(r,o)=>(r==null?void 0:r.id)===(o==null?void 0:o.id),value:Pe.find(r=>(r==null?void 0:r.id)===ue)??null,onChange:(r,o)=>Yt((o==null?void 0:o.id)??null),renderInput:r=>n(je,{...r,label:"Plant (optional)"})})}),v==="getPlantwiseReport"&&n(Y,{item:!0,xs:12,sm:6,md:2,children:n(Ee,{size:"small",fullWidth:!0,options:Pe,getOptionLabel:r=>(r==null?void 0:r.name)??"",isOptionEqualToValue:(r,o)=>(r==null?void 0:r.name)===(o==null?void 0:o.name),value:Pe.find(r=>(r==null?void 0:r.name)===u)??null,onChange:(r,o)=>D((o==null?void 0:o.name)??""),renderInput:r=>n(je,{...r,label:"Plant Name",size:"small"})})}),v==="getPlantMaterialReport"&&n(Y,{item:!0,xs:12,sm:6,md:2,children:n(Ee,{size:"small",fullWidth:!0,options:Pe,getOptionLabel:r=>(r==null?void 0:r.name)??"",isOptionEqualToValue:(r,o)=>(r==null?void 0:r.id)===(o==null?void 0:o.id),value:Pe.find(r=>(r==null?void 0:r.id)===ue)??null,onChange:(r,o)=>Yt((o==null?void 0:o.id)??null),renderInput:r=>n(je,{...r,label:"Plant"})})}),(v==="getDailyPlantProductionReport"||v==="getWeeklyPlantProductionReport"||v==="getMonthlyPlantProductionReport")&&n(Y,{item:!0,xs:12,sm:6,md:2,children:n(Ee,{size:"small",fullWidth:!0,options:Pe,getOptionLabel:r=>(r==null?void 0:r.name)??"",isOptionEqualToValue:(r,o)=>(r==null?void 0:r.id)===(o==null?void 0:o.id),value:Pe.find(r=>(r==null?void 0:r.id)===ue)??null,onChange:(r,o)=>Yt((o==null?void 0:o.id)??null),renderInput:r=>n(je,{...r,label:"Plant (optional)"})})}),v==="getJobCardCostReport"&&n(Y,{item:!0,xs:12,sm:6,md:2,children:n(Ee,{size:"small",fullWidth:!0,options:Pe,getOptionLabel:r=>(r==null?void 0:r.name)??"",isOptionEqualToValue:(r,o)=>(r==null?void 0:r.id)===(o==null?void 0:o.id),value:Pe.find(r=>(r==null?void 0:r.id)===ue)??null,onChange:(r,o)=>Yt((o==null?void 0:o.id)??null),renderInput:r=>n(je,{...r,label:"Plant (optional)"})})}),(v==="getVehicleTripReport"||v==="getDayWiseTripReport")&&n(Y,{item:!0,xs:12,sm:6,md:2.5,children:n(Ee,{size:"small",fullWidth:!0,options:aa,loading:ui,getOptionLabel:r=>r!=null&&r.vehicleNumber?`${r.vehicleNumber}${r.makeModel?` · ${r.makeModel}`:""}`:"",isOptionEqualToValue:(r,o)=>(r==null?void 0:r.id)===(o==null?void 0:o.id),value:aa.find(r=>(r==null?void 0:r.id)===$t)??null,onChange:(r,o)=>di((o==null?void 0:o.id)??null),renderInput:r=>n(je,{...r,label:v==="getVehicleTripReport"?"Vehicle":"Vehicle (optional)",InputProps:{...r.InputProps,endAdornment:g(kt,{children:[ui?n(st,{size:16}):null,r.InputProps.endAdornment]})}})})}),v==="getPlanVsActualReport"&&g(kt,{children:[n(Y,{item:!0,xs:12,sm:6,md:2,children:n(Ee,{size:"small",fullWidth:!0,options:Pe,getOptionLabel:r=>(r==null?void 0:r.name)??"",isOptionEqualToValue:(r,o)=>(r==null?void 0:r.id)===(o==null?void 0:o.id),value:Pe.find(r=>(r==null?void 0:r.id)===ue)??null,onChange:(r,o)=>Yt((o==null?void 0:o.id)??null),renderInput:r=>n(je,{...r,label:"Plant"})})}),n(Y,{item:!0,xs:12,sm:6,md:2,children:n(Ee,{size:"small",fullWidth:!0,options:xa,getOptionLabel:r=>(r==null?void 0:r.name)??"",isOptionEqualToValue:(r,o)=>(r==null?void 0:r.id)===(o==null?void 0:o.id),value:xa.find(r=>(r==null?void 0:r.id)===va)??null,onChange:(r,o)=>bi((o==null?void 0:o.id)??null),renderInput:r=>n(je,{...r,label:"Unit"})})}),n(Y,{item:!0,xs:12,sm:6,md:2,children:n(Ee,{size:"small",fullWidth:!0,options:Da,getOptionLabel:r=>(r==null?void 0:r.productName)??(r==null?void 0:r.name)??"",isOptionEqualToValue:(r,o)=>(r==null?void 0:r.id)===(o==null?void 0:o.id),value:Da.find(r=>(r==null?void 0:r.id)===rr)??null,onChange:(r,o)=>Di((o==null?void 0:o.id)??null),renderInput:r=>n(je,{...r,label:"Product"})})})]})]}),g(Y,{item:!0,xs:12,sm:12,md:6.4,children:[g(mo,{variant:"outlined",fullWidth:!0,sx:{height:"40px","& .MuiButton-root":{textTransform:"none",borderRight:"none","&:last-child":{borderRight:"1px solid rgba(0, 0, 0, 0.23)"}},"& .MuiIconButton-root":{borderRight:"none",borderRadius:0}},children:[n(vr,{title:"Quick Date Presets",children:n(Zt,{onClick:Pl,disabled:v==="",size:"small",sx:{borderRadius:0,borderTopLeftRadius:"4px",borderBottomLeftRadius:"4px",padding:"4px",minWidth:"32px",width:"32px",height:"40px"},children:n(So,{fontSize:"small"})})}),g(Hi,{direction:"row",spacing:2,alignItems:"center",children:[n(Hi,{direction:"row",spacing:2,alignItems:"center",children:n(Ui,{disabled:!v||(v==="getDaywiseReport"?!l:v==="getMachinewiseReport"?!mt:v==="getPlantwiseReport"?!u||!e||!b:v==="getPlantMaterialReport"?!ue||!e||!b:v==="getDailyProductionReport"?!l:v==="getPlanVsActualReport"?!e||!b:v==="getJobCardCostReport"?!1:v==="getVehicleTripReport"?!$t:!e||!b),btnType:"submit",type:"submit",children:G?n(st,{size:20,color:"inherit"}):"Run"})}),n(Ui,{btnType:"print",onClick:m==="getMachinewiseReport"?()=>{var r;return(r=Yi.current)==null?void 0:r.print()}:m==="getJobCardCostReport"&&Ge?()=>{var r;return(r=Oi.current)==null?void 0:r.print()}:m==="getVehicleTripReport"?()=>{var r;return(r=Ii.current)==null?void 0:r.print()}:zl,disabled:m==="getMachinewiseReport"?!Wl:m==="getJobCardCostReport"&&Ge?!Yl:m==="getVehicleTripReport"?!Ll:M.length===0,children:"Print"})]}),n(vr,{title:"Clear All Filters",children:n(Zt,{onClick:Nl,sx:{borderRadius:0,borderRight:"1px solid rgba(0, 0, 0, 0.23)",borderTopRightRadius:"4px",borderBottomRightRadius:"4px",flex:.5,minWidth:"48px",height:"40px"},children:n(Po,{})})})]}),g(qi,{anchorEl:Ri,open:Sl,onClose:ki,anchorOrigin:{vertical:"bottom",horizontal:"left"},transformOrigin:{vertical:"top",horizontal:"left"},children:[n(me,{onClick:()=>ft("today"),children:"Today"}),n(me,{onClick:()=>ft("yesterday"),children:"Yesterday"}),n(me,{onClick:()=>ft("last7"),children:"Last 7 Days"}),n(me,{onClick:()=>ft("last30"),children:"Last 30 Days"}),n(me,{onClick:()=>ft("last90"),children:"Last 90 Days"}),n(me,{onClick:()=>ft("thisWeek"),children:"This Week"}),n(me,{onClick:()=>ft("thisMonth"),children:"This Month"}),n(me,{onClick:()=>ft("lastMonth"),children:"Last Month"}),n(me,{onClick:()=>ft("thisYear"),children:"This Year"})]}),g(qi,{anchorEl:Mi,open:Dl,onClose:Sa,anchorOrigin:{vertical:"bottom",horizontal:"left"},transformOrigin:{vertical:"top",horizontal:"left"},children:[n(me,{onClick:ql,children:"Export PDF"}),n(me,{onClick:Gl,children:"Export Excel"}),n(me,{onClick:Hl,children:"Export CSV"})]})]})]})}),(m==="getDailyPlantProductionReport"||m==="getWeeklyPlantProductionReport"||m==="getMonthlyPlantProductionReport")&&T&&Object.keys(T).length>0&&(()=>{const r=Number(T.total_material_cost??0),o=Number(T.total_utility_charge??0),d=Number(T.total_production_cost??0);return n(Y,{container:!0,spacing:2,sx:{mb:3},children:[{label:"Total Produced",value:Number(T.total_produced??0),color:"primary.main",money:!1},{label:"Net Produced",value:Number(T.net_produced??0),color:"success.main",money:!1},{label:"Total Rejected",value:Number(T.total_rejected??0),color:"warning.main",money:!1},{label:"Material Cost",value:r,color:"error.main",money:!0},{label:"Utility",value:o,color:"info.main",money:!0},{label:"Production Cost",value:d,color:"secondary.main",money:!0}].map(x=>n(Y,{item:!0,xs:6,sm:4,md:"auto",children:g(we,{variant:"outlined",sx:{p:2,borderLeft:3,borderLeftColor:x.color,borderRadius:2,minWidth:140},children:[n(P,{variant:"caption",color:"text.secondary",sx:{fontWeight:500},children:x.label}),n(P,{variant:"h6",fontWeight:700,sx:{color:x.color,lineHeight:1.3},children:x.money?`₹ ${Number(x.value).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`:Number(x.value).toLocaleString("en-IN")})]})},x.label))})})(),m==="getPlanVsActualReport"&&M.length>0&&(()=>{const r=M.reduce((d,x)=>(d.planned+=Number(x.planned_qty??0),d.actual+=Number(x.actual_produced_qty??0),d),{planned:0,actual:0}),o=r.planned>0?r.actual/r.planned*100:0;return n(Y,{container:!0,spacing:2,sx:{mb:3},children:[{label:"Total Planned",value:r.planned,color:"primary.main"},{label:"Total Actual",value:r.actual,color:"success.main"},{label:"Variance",value:r.actual-r.planned,color:r.actual<r.planned?"error.main":"success.main"},{label:"Overall Completion",value:`${o.toFixed(2)}%`,color:"info.main"}].map(d=>n(Y,{item:!0,xs:6,sm:3,md:3,children:g(we,{variant:"outlined",sx:{p:2,borderLeft:3,borderLeftColor:d.color,borderRadius:2},children:[n(P,{variant:"caption",color:"text.secondary",sx:{fontWeight:500},children:d.label}),n(P,{variant:"h6",fontWeight:700,sx:{color:d.color,lineHeight:1.3},children:typeof d.value=="number"?Number(d.value).toLocaleString("en-IN"):d.value})]})},d.label))})})(),m==="getJobCardCostReport"&&!Ge&&T&&Object.keys(T).length>0&&n(Y,{container:!0,spacing:2,sx:{mb:3},children:[{label:"Job Cards",value:T.job_card_count??0,color:"primary.main",money:!1},{label:"Material Cost",value:T.total_material_cost??0,color:"info.main",money:!0},{label:"Utility Charges",value:T.total_utility_charges??0,color:"warning.main",money:!0},{label:"Grand Total",value:T.grand_total??0,color:"error.main",money:!0}].map(r=>n(Y,{item:!0,xs:6,sm:4,md:2.4,children:g(we,{variant:"outlined",sx:{p:2,borderLeft:3,borderLeftColor:r.color,borderRadius:2},children:[n(P,{variant:"caption",color:"text.secondary",sx:{fontWeight:500},children:r.label}),n(P,{variant:"h6",fontWeight:700,sx:{color:r.color,lineHeight:1.3},children:r.money?`₹ ${Number(r.value).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`:Number(r.value).toLocaleString("en-IN")})]})},r.label))}),m==="getJobCardCostReport"&&!Ge&&M.length>0&&g(j,{display:"flex",alignItems:"center",gap:.75,sx:{mb:2,color:"text.secondary"},children:[n(Gi,{sx:{fontSize:16}}),n(P,{variant:"caption",children:"Click any job card row to see its full cost breakdown — materials, utilities and process costs."})]}),m==="getDayWiseTripReport"&&T&&Object.keys(T).length>0&&n(Y,{container:!0,spacing:2,sx:{mb:3},children:[{label:"Trips",value:T.trip_count??0,color:"primary.main",money:!1},{label:"Vehicles",value:T.vehicle_count??0,color:"info.main",money:!1},{label:"Total Distance (km)",value:T.total_distance??0,color:"success.main",money:!1},{label:"Fuel",value:T.total_fuel??0,color:"warning.main",money:!1},{label:"Fuel Cost",value:T.total_fuel_cost??0,color:"error.main",money:!0}].map(r=>n(Y,{item:!0,xs:6,sm:4,md:2.4,children:g(we,{variant:"outlined",sx:{p:2,borderLeft:3,borderLeftColor:r.color,borderRadius:2},children:[n(P,{variant:"caption",color:"text.secondary",sx:{fontWeight:500},children:r.label}),n(P,{variant:"h6",fontWeight:700,sx:{color:r.color,lineHeight:1.3},children:r.money?`₹ ${Number(r.value).toLocaleString("en-IN",{minimumFractionDigits:2,maximumFractionDigits:2})}`:Number(r.value).toLocaleString("en-IN")})]})},r.label))}),(M.length>0||m)&&g(j,{display:"flex",alignItems:"center",justifyContent:"space-between",flexWrap:"wrap",gap:1,mt:3,mb:2,sx:{pb:1.25,borderBottom:"1px solid",borderColor:"divider"},children:[g(j,{display:"flex",alignItems:"center",gap:1,children:[n(No,{color:"primary"}),n(P,{variant:"subtitle1",fontWeight:700,color:"primary.main",sx:{textTransform:"uppercase",letterSpacing:"0.04em"},children:"Results"}),M.length>0&&g(P,{variant:"caption",sx:{ml:1,px:1.25,py:.25,borderRadius:4,bgcolor:"primary.50",color:"primary.main",fontWeight:700,border:"1px solid",borderColor:"primary.100"},children:[(at||M.length).toLocaleString("en-IN")," record",(at||M.length)===1?"":"s"]})]}),m&&n(P,{variant:"caption",color:"text.secondary",children:Pa()})]}),g(Y,{container:!0,spacing:3,children:[n(Y,{item:!0,xs:12,md:12,children:m==="getMachinewiseReport"?n(xn,{ref:Yi,machineName:mt,fromDate:e,toDate:b,plantId:ue,reloadKey:Tl,onReadyChange:$l}):m==="getJobCardCostReport"&&Ge?n(yn,{ref:Oi,jobCardNo:Ge,fromDate:e,toDate:b,plantId:ue,reloadKey:Il,onReadyChange:Ol}):m==="getVehicleTripReport"?n(bn,{ref:Ii,vehicleId:$t,vehicleLabel:((Ei=aa.find(r=>(r==null?void 0:r.id)===$t))==null?void 0:Ei.vehicleNumber)??"",fromDate:e,toDate:b,reloadKey:El,onReadyChange:Al}):M.length>0?n(j,{ref:ht,sx:{height:"600px",width:"100%"},children:n(fo,{columns:Vl(m),rows:ne.map((r,o)=>({...r,id:(r==null?void 0:r.id)??`row-${o}`})),rowCount:at,checkboxSelection:!1,getRowId:r=>r.id,paginationMode:"server",initialState:{pagination:{paginationModel:X}},pageSizeOptions:[5,10,20,50],loading:G,paginationModel:X,onPaginationModelChange:Le,onRowClick:m==="getJobCardCostReport"?r=>wi(r.row):m==="getMachinewiseReport"?r=>$i(r.row):void 0,sx:{borderRadius:2,boxShadow:1,height:600,...(m==="getJobCardCostReport"||m==="getMachinewiseReport")&&{"& .MuiDataGrid-row":{cursor:"pointer"}},"& .MuiDataGrid-cell":{fontSize:"0.875rem"},"& .MuiDataGrid-columnHeaders":{backgroundColor:"action.hover",fontWeight:600},"& .MuiDataGrid-root":{height:"100% !important"},"& .MuiDataGrid-main":{height:"100% !important"}}})}):g(Se,{elevation:0,sx:{p:{xs:4,md:6},textAlign:"center",border:"1px dashed",borderColor:"divider",borderRadius:3,background:"linear-gradient(180deg, rgba(25,118,210,0.02) 0%, rgba(25,118,210,0) 100%)"},children:[n(j,{sx:{width:72,height:72,mx:"auto",mb:2,borderRadius:"50%",bgcolor:"primary.50",display:"flex",alignItems:"center",justifyContent:"center",color:"primary.main"},children:n(Mo,{sx:{fontSize:36}})}),n(P,{variant:"h6",fontWeight:700,color:"text.primary",sx:{mb:.5},children:"No data yet"}),g(P,{variant:"body2",sx:{color:"text.secondary",maxWidth:420,mx:"auto"},children:["Select a report type, choose your filters and date range, then click ",n("strong",{children:"Run"})," to view the report."]}),g(j,{display:"flex",alignItems:"center",justifyContent:"center",gap:.75,mt:2,sx:{color:"text.disabled"},children:[n(Gi,{sx:{fontSize:16}}),n(P,{variant:"caption",children:"Tip: use Quick Date presets for common ranges"})]})]})}),!1]})]}),n(Uo,{open:!!Ot,jobCardId:(Ot==null?void 0:Ot.job_card_id)??null,jobCardNo:Ot==null?void 0:Ot.job_card_no,onClose:()=>wi(null)}),n(Go,{open:!!Wi,machine:Wi,onClose:()=>$i(null)})]})}export{sh as default};
