PageSourceSearch

https://stone-profit-flow.base44.app/assets/CustomerQuote-oMyIMg1J.js

js stone-profit-flow.base44.app collected 2026-10-03 03:10:36 UTC 305,327 bytes, 104 lines download raw bytes

1import{a as m,d as jt,j as t,u as xa,b as ho}from"./vendor-query-B-_nDQQY.js";import{y as Bs,C as at,d as rt,s as Ar,B as X,e as Tt,a as Ua,c as Ha,b as ge,n as js,I as He,Q as Ba,X as ca,q as Ze,t as $,h as Wt,i as zt,j as Ut,k as Ht,l as Ye,as as ki,aC as Va,O as Ga,M as $r,a8 as fo,v as Si,F as Ps,ac as po,ad as xo,S as Or,L as Bt,x as Aa,T as Ci,f as Yr,ao as go,_ as Mi,r as Di,ah as yo,W as Rr,m as _o,ak as Pi,Z as bo,U as jo,J as hr,aX as wo}from"./index-D8ww6b7J.js";import{A as vo,a as ta,b as sa,c as aa}from"./accordion-aiFwGedp.js";import{D as ts,f as No,a as ss,b as as,c as rs,e as gs,d as $a}from"./dialog-BQWtAG_x.js";import{C as qs}from"./circle-check-big-4Ew-rpqG.js";import{P as da}from"./package-kgQR05VR.js";import{B as Xn}from"./barcode-DVFsVwWU.js";import{R as ua}from"./ruler-Bcj6zKuq.js";import{C as Hs}from"./circle-check-BXjz6L8_.js";import{C as ko}from"./circle-x-CIIBFH3_.js";import{E as So}from"./eye-off-sdlW1LAI.js";import{E as Ti}from"./eye-DQ9YWbv-.js";import{T as Co}from"./tag-Dp_exg6F.js";import{S as Mo}from"./sticky-note-CAvkSZuA.js";import{I as Do}from"./image-W2HJP6c8.js";import{T as Po}from"./textarea-Bhj0eADY.js";import"./checkbox-DYv8y0li.js";import{T as Fs}from"./trash-2-LBknmkIl.js";import{P as It}from"./plus-MQo5wr8n.js";import{A as To,a as qi}from"./arrow-up-Blck6wym.js";import{S as Ka}from"./save-d5GEALD8.js";import{P as Ir}from"./pencil-iBu5MVPj.js";import{M as Fi}from"./message-circle-Cg6XlpSC.js";import{P as Li}from"./phone-CA5yr35z.js";import{C as la}from"./credit-card-CDUARo9S.js";import{S as qo}from"./signature-CFru0EYs.js";import{R as Fo}from"./refresh-cw-B9y4TrLK.js";import{A as Jn}from"./arrow-right-BeikyhzV.js";import{T as Ai}from"./trending-down-BIipizug.js";import{T as Lo}from"./target-sa9DKzQo.js";import{R as Ao}from"./rotate-cw-BMMpojoW.js";import{S as Cr}from"./square-B1YMa_kL.js";import{P as Oa}from"./pen-tool-BEizwLls.js";import{T as $o,r as Oo}from"./polygonTools-CSx3SZxL.js";import{S as $i}from"./scissors-DEQgEDjN.js";import{P as Yo}from"./paintbrush-CUQF6LTa.js";import{U as Ro}from"./undo-B7EFSuy7.js";import{R as Io}from"./redo-2-BhBxJ1Yc.js";import{C as Er}from"./copy-CeElQ86j.js";import{G as Eo}from"./grid-3x3-E2z5-2sj.js";import{Z as Wo,a as zo}from"./zoom-in-Dx_LX7cY.js";import{H as Uo}from"./hand-CuULmjp7.js";import{L as Oi}from"./layers-De-P0_bF.js";import{F as Yi}from"./file-image-sDRH1efz.js";import{U as fr}from"./upload-DN-6vN7H.js";import{M as Ho}from"./mouse-pointer-2-BbEgZT8W.js";import{H as Bo}from"./history-CLwtiCQB.js";import{P as Vo}from"./PageHeader-DOQecRZi.js";import{P as Go,a as Ko,b as Zo}from"./popover-CXzIWiKA.js";import{C as Xo,a as Jo,b as Qo,c as ec,d as Qn,e as ei}from"./command-B--4woJF.js";import{U as tc}from"./user-CHo1Apvy.js";import{S as Wr}from"./send-DJBvsBZ5.js";import{E as Ri}from"./external-link-H0n6aDkP.js";import{C as ti}from"./camera-B5zm8J-v.js";import{S as pr}from"./shield-check-BAeEGIHA.js";import{B as xr}from"./banknote-u4qSGFU6.js";import{F as sc}from"./file-pen-line-Cf5esZdC.js";import{b as ac}from"./vendor-react-BUIlT3ms.js";import"./vendor-three-1K-S22da.js";import"./vendor-charts-i-522T5A.js";import"./vendor-pdf-Bwkk3Ew0.js";import"./vendor-radix-X0WMATEu.js";import"./index-CEETb8YB.js";/**
2 * @license lucide-react v1.21.0 - ISC
3 *
4 * This source code is licensed under the ISC license.
5 * See the LICENSE file in the root directory of this source tree.
6 */const rc=[["path",{d:"M2.97 12.92A2 2 0 0 0 2 14.63v3.24a2 2 0 0 0 .97 1.71l3 1.8a2 2 0 0 0 2.06 0L12 19v-5.5l-5-3-4.03 2.42Z",key:"lc1i9w"}],["path",{d:"m7 16.5-4.74-2.85",key:"1o9zyk"}],["path",{d:"m7 16.5 5-3",key:"va8pkn"}],["path",{d:"M7 16.5v5.17",key:"jnp8gn"}],["path",{d:"M12 13.5V19l3.97 2.38a2 2 0 0 0 2.06 0l3-1.8a2 2 0 0 0 .97-1.71v-3.24a2 2 0 0 0-.97-1.71L17 10.5l-5 3Z",key:"8zsnat"}],["path",{d:"m17 16.5-5-3",key:"8arw3v"}],["path",{d:"m17 16.5 4.74-2.85",key:"8rfmw"}],["path",{d:"M17 16.5v5.17",key:"k6z78m"}],["path",{d:"M7.97 4.42A2 2 0 0 0 7 6.13v4.37l5 3 5-3V6.13a2 2 0 0 0-.97-1.71l-3-1.8a2 2 0 0 0-2.06 0l-3 1.8Z",key:"1xygjf"}],["path",{d:"M12 8 7.26 5.15",key:"1vbdud"}],["path",{d:"m12 8 4.74-2.85",key:"3rx089"}],["path",{d:"M12 13.5V8",key:"1io7kd"}]],si=Bs("boxes",rc);/**
7 * @license lucide-react v1.21.0 - ISC
8 *
9 * This source code is licensed under the ISC license.
10 * See the LICENSE file in the root directory of this source tree.
11 */const nc=[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]],ic=Bs("chevrons-up-down",nc);/**
12 * @license lucide-react v1.21.0 - ISC
13 *
14 * This source code is licensed under the ISC license.
15 * See the LICENSE file in the root directory of this source tree.
16 */const lc=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]],oc=Bs("folder-open",lc);/**
17 * @license lucide-react v1.21.0 - ISC
18 *
19 * This source code is licensed under the ISC license.
20 * See the LICENSE file in the root directory of this source tree.
21 */const cc=[["line",{x1:"22",x2:"2",y1:"6",y2:"6",key:"15w7dq"}],["line",{x1:"22",x2:"2",y1:"18",y2:"18",key:"1ip48p"}],["line",{x1:"6",x2:"6",y1:"2",y2:"22",key:"a2lnyx"}],["line",{x1:"18",x2:"18",y1:"2",y2:"22",key:"8vb6jd"}]],dc=Bs("frame",cc);/**
22 * @license lucide-react v1.21.0 - ISC
23 *
24 * This source code is licensed under the ISC license.
25 * See the LICENSE file in the root directory of this source tree.
26 */const uc=[["path",{d:"M13 7 8.7 2.7a2.41 2.41 0 0 0-3.4 0L2.7 5.3a2.41 2.41 0 0 0 0 3.4L7 13",key:"orapub"}
26],["path",{d:"m8 6 2-2",key:"115y1s"}],["path",{d:"m18 16 2-2",key:"ee94s4"}],["path",{d:"m17 11 4.3 4.3c.94.94.94 2.46 0 3.4l-2.6 2.6c-.94.94-2.46.94-3.4 0L11 17",key:"cfq27r"}],["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]],mc=Bs("pencil-ruler",uc);/**
27 * @license lucide-react v1.21.0 - ISC
28 *
29 * This source code is licensed under the ISC license.
30 * See the LICENSE file in the root directory of this source tree.
31 */const hc=[["line",{x1:"10",x2:"14",y1:"2",y2:"2",key:"14vaq8"}],["line",{x1:"12",x2:"15",y1:"14",y2:"11",key:"17fdiu"}],["circle",{cx:"12",cy:"14",r:"8",key:"1e1u0o"}]],ai=Bs("timer",hc);function fc({selectedMaterial:e,requiredSqft:s,onSlabSelect:a}){const[r,n]=m.useState([]),[i,l]=m.useState(!1),{data:u=[],isLoading:c}=jt({queryKey:["inventory-availability"],queryFn:()=>ge.entities.Inventory.list()}),d=u.filter(M=>e&&M.material_name!==e?!1:(M.total_sqft||0)-(M.reserved_sqft||0)>0),j=d.reduce((M,T)=>M+((T.total_sqft||0)-(T.reserved_sqft||0)),0),w=j>=(s||0),A=M=>{r.find(T=>T.id===M.id)?n(r.filter(T=>T.id!==M.id)):(n([...r,M]),a==null||a([...r,M]))};return c?t.jsx("div",{className:"flex justify-center py-8",children:t.jsx("div",{className:"w-8 h-8 border-4 border-slate-200 border-t-slate-800 rounded-full animate-spin"})}):t.jsxs("div",{className:"space-y-4",children:[t.jsx(at,{className:w?"border-green-200 bg-green-50 dark:bg-green-900/10":"border-red-200 bg-red-50 dark:bg-red-900/10",children:t.jsx(rt,{className:"pt-6",children:t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsxs("div",{className:"flex items-center gap-3",children:[w?t.jsx(qs,{className:"w-6 h-6 text-green-600"}):t.jsx(Ar,{className:"w-6 h-6 text-red-600"}),t.jsxs("div",{children:[t.jsx("p",{className:"font-semibold",children:w?"✓ Material Available":"✗ Insufficient Material"}),t.jsxs("p",{className:"text-sm text-muted-foreground",children:[j.toFixed(1)," sqft available ",s&&`(need ${s} sqft)`]})]})]}),t.jsxs(ts,{open:i,onOpenChange:l,children:[t.jsx(No,{asChild:!0,children:t.jsxs(X,{variant:"outline",size:"sm",children:[t.jsx(da,{className:"w-4 h-4 mr-2"}),"View Slabs (",d.length,")"]})}),t.jsxs(ss,{className:"max-w-4xl max-h-[80vh] overflow-y-auto",children:[t.jsx(as,{children:t.jsx(rs,{children:"Available Slabs"})}),t.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 mt-4",children:d.map(M=>{var D;const T=(M.total_sqft||0)-(M.reserved_sqft||0);return t.jsx(at,{className:`cursor-pointer transition-all ${r.find(Y=>Y.id===M.id)?"border-primary ring-2 ring-primary":"hover:border-primary"}`,onClick:()=>A(M),children:t.jsxs(rt,{className:"p-4 space-y-3",children:[((D=M.slab_photos)==null?void 0:D.length)>0&&t.jsx("div",{className:"aspect-video bg-slate-100 rounded-lg overflow-hidden",children:t.jsx("img",{src:M.slab_photos[0],alt:M.material_name,className:"w-full h-full object-cover"})}),t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx("p",{className:"font-semibold",children:M.material_name}),t.jsxs(Tt,{variant:T>=(s||0)?"default":"secondary",children:[T.toFixed(0)," sqft"]})]}),M.barcode&&t.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[t.jsx(Xn,{className:"w-4 h-4"}),t.jsx("span",{children:M.barcode})]}),t.jsxs("div",{className:"grid grid-cols-2 gap-2 text-xs",children:[t.jsxs("div",{className:"flex items-center gap-1",children:[t.jsx(ua,{className:"w-3 h-3"}),t.jsx("span",{children:M.thickness||"N/A"})]}),t.jsxs("div",{className:"flex items-center gap-1",children:[t.jsx(da,{className:"w-3 h-3"}),t.jsxs("span",{children:[M.slab_count||0," slabs"]})]})]}),M.location&&t.jsxs("p",{className:"text-xs text-muted-foreground",children:["Location: ",M.location]})]})]})},M.id)})})]})]})]})})}),r.length>0&&t.jsxs(at,{children:[t.jsx(Ua,{children:t.jsx(Ha,{className:"text-sm",children:"Selected Slabs for Reservation"})}),t.jsx(rt,{children:t.jsx("div",{className:"space-y-2",children:r.map(M=>t.jsxs("div",{className:"flex items-center justify-between p-2 bg-slate-50 dark:bg-slate-900 rounded",children:[t.jsxs("div",{children:[t.jsx("p",{className:"font-medium text-sm",children:M.material_name}),M.barcode&&t.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[t.jsx(Xn,{className:"w-3 h-3"}),M.barcode]})]}),t.jsxs(Tt,{variant:"outline",children:[((M.total_sqft||0)-(M.reserved_sqft||0)).toFixed(0)," sqft"]})]},M.id))})})]})]})}const Ii=10.7639;function pc(e,s="imperial"){return!e||isNaN(e)?0:s==="metric"?e/Ii:e}function Es(e,s="imperial",a=2){const r=pc(e,s),n=s==="metric"?"sq m":"sq ft";return`${r.toFixed(a)} ${n}`}function gr(e,s="imperial"){return s==="metric"?`$${((e||0)*Ii).toFixed(2)}/sq m`:`$${(e||0).toFixed(2)}/sq ft`}function Ya({basePrice:e,discountType:s,discountValue:a,taxRate:r,applyCreditCardFee:n,ccFeeRate:i}){const l=Number(e)||0;let u=0;s==="percentage"?u=l*(a/100):s==="fixed"&&(u=a);const c=l-u,d=c*(r/100),j=n?c*(i/100):0,w=c+d+j;return{discountAmount:u,priceAfterDiscount:c,taxAmount:d,ccFeeAmount:j,finalTotal:w}}function Ei(e,s){const a=(e||[]).map(i=>
31parseFloat(i.sqft)||0),r=Math.max(0,(Number(s)||0)-a.reduce((i,l)=>i+l,0)),n=[...a];if(r>0){const i=a.findIndex(l=>l>0);i!==-1&&(n[i]=a[i]+r)}return{shortfallSqft:r,pricingSqfts:n}}function xc({status:e,pendingPrice:s,currentPrice:a,requestedBy:r,onApprove:n,onReject:i,isAdmin:l}){return!e||e!=="pending"?null:t.jsxs("div",{className:"flex flex-col gap-1 mt-1 px-2 py-1 rounded-md bg-amber-50 dark:bg-amber-950/30 border border-amber-200 dark:border-amber-800",children:[t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx(js,{className:"w-3 h-3 text-amber-600 dark:text-amber-400 shrink-0"}),t.jsx("span",{className:"text-[11px] font-medium text-amber-700 dark:text-amber-300",children:"Price change pending approval"})]}),t.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground",children:[t.jsxs("span",{className:"line-through",children:["$",(a||0).toFixed(2)]}),t.jsxs("span",{className:"text-amber-700 dark:text-amber-300 font-medium",children:["→ $",(s||0).toFixed(2),"/sqft"]}),r&&t.jsxs("span",{className:"text-xs",children:["by ",r]})]}),l&&t.jsxs("div",{className:"flex items-center gap-1.5 mt-1",children:[t.jsxs("button",{onClick:n,className:"flex items-center gap-1 px-2 py-0.5 rounded text-[11px] font-medium bg-green-100 text-green-700 hover:bg-green-200 dark:bg-green-900/40 dark:text-green-300 dark:hover:bg-green-900/60 transition-colors",children:[t.jsx(Hs,{className:"w-3 h-3"}),"Approve"]}),t.jsxs("button",{onClick:i,className:"flex items-center gap-1 px-2 py-0.5 rounded text-[11px] font-medium bg-red-100 text-red-700 hover:bg-red-200 dark:bg-red-900/40 dark:text-red-300 dark:hover:bg-red-900/60 transition-colors",children:[t.jsx(ko,{className:"w-3 h-3"}),"Reject"]})]})]})}function gc({line:e,type:s,index:a,isAdmin:r,user:n,onUpdateLine:i}){const[l,u]=m.useState(!!e.notes),c=!!e.hidden_from_customer,d=e.discount_pct||0,j=e.discount_approval_status||null,w=e.notes||"",A=()=>i(s,a,{hidden_from_customer:!c}),M=P=>{const h=Math.min(100,Math.max(0,parseFloat(P)||0));h>0?r?i(s,a,{discount_pct:h,discount_approval_status:"approved",discount_requested_by:null}):i(s,a,{discount_pct:h,discount_approval_status:"pending",discount_requested_by:(n==null?void 0:n.full_name)||(n==null?void 0:n.email)||"Salesperson"}):i(s,a,{discount_pct:0,discount_approval_status:null,discount_requested_by:null})},T=()=>i(s,a,{discount_approval_status:"approved"}),D=()=>i(s,a,{discount_approval_status:"rejected",discount_pct:0,discount_requested_by:null}),Y="flex items-center gap-1.5 h-9 px-3 rounded-md text-xs font-medium border transition-colors shrink-0";return t.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-2 pt-2 border-t border-dashed border-border",children:[t.jsxs("button",{type:"button",onClick:A,className:`${Y} ${c?"bg-warning/15 text-warning border-warning/40":"bg-muted/50 text-muted-foreground hover:bg-accent border-border"}`,title:c?"Line hidden from customer print":"Hide this line from the customer print",children:[c?t.jsx(So,{className:"w-3.5 h-3.5"}):t.jsx(Ti,{className:"w-3.5 h-3.5"}),c?"Hidden":"Hide"]}),t.jsxs("div",{className:`flex items-center gap-1.5 h-9 px-2.5 rounded-md border shrink-0 ${d>0&&j==="approved"?"bg-success/10 border-success/30":"bg-muted/50 border-border"}`,children:[t.jsx(Co,{className:"w-3.5 h-3.5 text-muted-foreground shrink-0"}),t.jsx("span",{className:"text-xs font-medium text-muted-foreground whitespace-nowrap",children:"Discount"}),t.jsx(He,{type:"number",step:"1",min:"0",max:"100",value:d||"",onChange:P=>M(P.target.value),placeholder:"0",className:"h-7 w-16 text-xs border px-2"}),t.jsx("span",{className:"text-xs text-muted-foreground font-medium",children:"%"}),j==="pending"&&t.jsx("span",{className:"text-[10px] font-semibold px-1.5 py-0.5 rounded bg-warning/20 text-warning",children:"Pending"}),j==="pending"&&r&&t.jsxs("div",{className:"flex items-center gap-0.5",children:[t.jsx("button",{type:"button",onClick:T,className:"p-1 rounded bg-success/15 text-success hover:bg-success/25",title:"Approve discount",children:t.jsx(Ba,{className:"w-3.5 h-3.5"})}),t.jsx("button",{type:"button",onClick:D,className:"p-1 rounded bg-destructive/15 text-destructive hover:bg-destructive/25",title:"Reject discount",children:t.jsx(ca,{className:"w-3.5 h-3.5"})})]}),j==="approved"&&d>0&&t.jsxs("span",{className:"text-[10px] font-semibold px-1.5 py-0.5 rounded bg-success/20 text-success",children:["-",d,"%"]}),j==="rejected"&&t.jsx("span",{className:"text-[10px] font-semibold px-1.5 py-0.5 rounded bg-destructive/20 text-destructive",children:"Rejected"})]}),t.jsxs("button",{type:"button",onClick:()=>u(!l),className:`${Y} ${w?"bg-primary/10 text-primary border-primary/40":"bg-muted/50 text-muted-foreground hover:bg-accent border-border"}`,children:[t.jsx(Mo,{className:"w-3.5 h-3.5"}),"Note"]}),!l&&w&&t.jsxs("span",{className:"text-xs text-muted-foreground truncate max-w-[220px] italic ml-1",children:["“",w,"”"]}
31),l&&t.jsxs("div",{className:"w-full flex items-center gap-1.5 mt-1",children:[t.jsx(He,{value:w,onChange:P=>i(s,a,{notes:P.target.value}),placeholder:"Add a production note for this line (e.g. “Side edge don’t polish”)...",className:"h-8 flex-1 text-xs"}),t.jsx("button",{type:"button",onClick:()=>u(!1),className:"p-1.5 rounded-md text-muted-foreground hover:bg-accent shrink-0",title:"Collapse note",children:t.jsx(ca,{className:"w-3.5 h-3.5"})})]})]})}function Wi({material:e,size:s="sm"}){const a=s==="lg"?"w-10 h-10":"w-8 h-8",r=s==="lg"?"w-10 h-10":"w-8 h-8";return e!=null&&e.image_url?t.jsx("img",{src:e.image_url,alt:e.material_name||"",className:`${r} rounded-md object-cover border border-border shrink-0`,loading:"lazy",onError:n=>{var i,l;n.currentTarget.style.display="none",(l=(i=n.currentTarget.nextSibling)==null?void 0:i.style)==null||l.setProperty("display","flex")}}):e!=null&&e.color?t.jsx("div",{className:`${a} rounded-md border border-border shrink-0`,style:{backgroundColor:e.color}}):t.jsx("div",{className:`${a} rounded-md border border-border shrink-0 flex items-center justify-center bg-muted/50`,children:t.jsx(Do,{className:"w-3.5 h-3.5 text-muted-foreground/50"})})}const yc=[{value:"eased",label:"Eased (Standard)",description:"Straight 90° edge",svg_path:"M 8,16 L 82,16 L 84,17 L 84,29 L 82,30 L 8,30 Z",is_premium:!1},{value:"bevel",label:"Bevel",description:"Angled 45° cut",svg_path:"M 8,16 L 74,16 L 84,26 L 84,30 L 8,30 Z",is_premium:!1},{value:"bullnose",label:"Bullnose",description:"Fully rounded",svg_path:"M 8,16 L 84,16 A 7,7 0 0 1 84,30 L 8,30 Z",is_premium:!1},{value:"half_bullnose",label:"Half Bullnose",description:"Top rounded",svg_path:"M 8,16 L 84,16 Q 84,23 84,23 L 84,30 L 8,30 Z",is_premium:!1},{value:"ogee",label:"Ogee (Premium)",description:"S-curve detail",svg_path:"M 8,8 L 84,8 C 92,11 76,18 84,22 L 84,36 L 58,36 L 58,22 L 8,22 Z",is_premium:!0},{value:"dupont",label:"Dupont (Premium)",description:"Dupont profile",svg_path:"M 8,16 L 84,16 A 5,5 0 0 1 84,26 L 84,30 L 8,30 Z",is_premium:!0},{value:"waterfall",label:"Waterfall (Premium)",description:"Waterfall edge",svg_path:"M 8,8 L 84,8 L 84,36 L 58,36 L 58,22 L 8,22 Z",is_premium:!0},{value:"mitered",label:"Mitered",description:"Laminated fold",svg_path:"M 8,8 L 84,8 L 84,36 L 58,36 L 58,22 L 8,22 Z",is_premium:!1}];function _c(){const{data:e=[],isLoading:s}=jt({queryKey:["edge-profiles"],queryFn:()=>ge.entities.EdgeProfile.list("sort_order"),staleTime:3e5}),a=!s&&e.length===0,r=a?yc.map((i,l)=>({...i,id:`default-${i.value}`,sort_order:l+1,is_active:!0})):e.filter(i=>i.is_active!==!1),n=r.slice().sort((i,l)=>(i.sort_order||99)-(l.sort_order||99)).map(i=>({value:i.value,label:i.name,is_premium:i.is_premium,svg_path:i.svg_path,description:i.description,price_per_linear_ft:i.price_per_linear_ft||0}));return{edgeProfiles:r,edgeOptions:n,isLoading:s,usingDefaults:a}}const ga={name:"",item_type:"material",area_name:"",length_inches:"",width_inches:"",material_type:"",material_name:"",sqft:"",edge_profile:"eased",edge_linear_ft:0,edge_price_per_linear_ft:0,edge_cost:0,sink_type:"none",sink_material:"",cooktop_included:!1,backsplash:!1,special_features:[],unit_price_per_sqft:0,material_cost:0,labor_cost:0,total_cost:0,selling_price:0,notes:""};function bc({open:e,onOpenChange:s,onInsert:a,currentLineItems:r=[],currentServices:n=[],currentProducts:i=[]}){const l=xa(),[u,c]=m.useState(!1),[d,j]=m.useState(""),[w,A]=m.useState(!1),{data:M=[],isLoading:T}=jt({queryKey:["assemblies"],queryFn:()=>ge.entities.Assembly.list(),enabled:e}),D=async()=>{if(!d.trim()){$.error("Enter an assembly name");return}if(!r.length&&!n.length&&!i.length){$.error("Add line items to the quote first, then save them as an assembly");return}A(!0);try{await ge.entities.Assembly.create({name:d.trim(),line_items:r.map(h=>({name:h.name,material_type:h.material_type,material_name:h.material_name,color:h.color,sqft:Number(h.sqft)||0,edge_profile:h.edge_profile||"eased",edge_linear_ft:Number(h.edge_linear_ft)||0,sink_type:h.sink_type||"none",sink_material:h.sink_material||"",cooktop_included:!!h.cooktop_included,backsplash:!!h.backsplash,special_features:h.special_features||[],unit_price_per_sqft:Number(h.unit_price_per_sqft)||
310})),services:n.map(h=>({description:h.description,price:Number(h.price)||0,qty:Number(h.qty)||1,unit:h.unit||"each"})),products:i.map(h=>({name:h.name,price:Number(h.price)||0,qty:Number(h.qty)||1,unit:h.unit||"each"})),is_active:!0}),l.invalidateQueries({queryKey:["assemblies"]}),$.success(`Assembly "${d.trim()}" saved`),j(""),c(!1)}catch(h){$.error("Failed to save assembly: "+h.message)}finally{A(!1)}},Y=async h=>{try{await ge.entities.Assembly.delete(h),l.invalidateQueries({queryKey:["assemblies"]}),$.success("Assembly deleted")}catch{$.error("Failed to delete assembly")}},P=h=>{const J=(h.line_items||[]).map(U=>({...ga,name:U.name||U.material_name,material_name:U.material_name,material_type:U.material_type,color:U.color,sqft:U.sqft?String(U.sqft):"",edge_profile:U.edge_profile||"eased",edge_linear_ft:U.edge_linear_ft||0,sink_type:U.sink_type||"none",sink_material:U.sink_material||"",cooktop_included:!!U.cooktop_included,backsplash:!!U.backsplash,special_features:U.special_features||[],unit_price_per_sqft:U.unit_price_per_sqft||0})),z=(h.services||[]).map(U=>({description:U.description,price:String(U.price||0),qty:U.qty||1,unit:U.unit||"each",markup_pct:0})),B=(h.products||[]).map(U=>({name:U.name,price:String(U.price||0),qty:U.qty||1,unit:U.unit||"each",markup_pct:0}));a({lineItems:J,services:z,products:B}),$.success(`Inserted ${h.name}`),s(!1)};return t.jsx(ts,{open:e,onOpenChange:s,children:t.jsxs(ss,{className:"max-w-lg",children:[t.jsxs(as,{children:[t.jsx(rs,{children:"Saved Assemblies"}),t.jsx(gs,{children:"Insert a reusable bill of materials, or save the current quote lines as a new assembly."})]}),T?t.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"}):t.jsxs("div",{className:"space-y-2 max-h-80 overflow-y-auto",children:[M.length===0&&!u&&t.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No saved assemblies yet."}),M.map(h=>t.jsxs("div",{className:"flex items-center justify-between gap-2 p-2 border rounded hover:bg-accent/40",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("p",{className:"text-sm font-medium truncate",children:h.name}),t.jsxs("p",{className:"text-xs text-muted-foreground",children:[(h.line_items||[]).length," items",(h.services||[]).length?` · ${h.services.length} services`:"",(h.products||[]).length?` · ${h.products.length} products`:""]})]}),t.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[t.jsx(X,{size:"sm",onClick:()=>P(h),children:"Insert"}),t.jsx(X,{size:"icon",variant:"ghost",onClick:()=>Y(h.id),title:"Delete assembly",children:t.jsx(Fs,{className:"w-4 h-4 text-destructive"})})]})]},h.id))]}),u?t.jsxs("div",{className:"space-y-2 border-t pt-3",children:[t.jsx(Ze,{className:"text-xs",children:"Assembly name"}),t.jsx(He,{value:d,onChange:h=>j(h.target.value),placeholder:"e.g. Standard Kitchen w/ Island",className:"h-9",autoFocus:!0}),t.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Saves the ",r.length," material, ",n.length," service, and ",i.length," product line(s) currently on this quote."]}),t.jsxs("div",{className:"flex gap-2 justify-end",children:[t.jsx(X,{variant:"outline",size:"sm",onClick:()=>c(!1),children:"Cancel"}),t.jsx(X,{size:"sm",onClick:D,disabled:w,children:w?"Saving…":"Save current lines"})]})]}):t.jsx($a,{children:t.jsxs(X,{variant:"outline",size:"sm",onClick:()=>c(!0),children:[t.jsx(It,{className:"w-4 h-4 mr-1"})," Save current lines as assembly"]})})]})})}function jc({lineItems:e,services:s,products:a,onUpdateItems:r,onUpdateServices:n,onUpdateProducts:i,allMaterials:l=[]}){const[u,c]=m.useState(!1),[d,j]=m.useState(!1),[w,A]=m.useState(!1),[M,T]=m.useState(!1),[D,Y]=m.useState(!1),[P,h]=m.useState(!1),[J,z]=m.useState(!1),[B,U]=m.useState({description:"",price:"",qty:1}),[oe,Ne]=m.useState(""),[ue,je]=m.useState(""),[ye,W]=m.useState(""),[V,q]=m.useState(""),[E,be]=m.useState({material_name:"",supplier:"",material_type:"quartz",cost_per_sqft:"",selling_price_per_sqft:"",color:""}),[we,le]=m.useState(!1),me=xa(),De=async()=>{if(!E.material_name||!E.supplier||!E.cost_per_sqft||!E.selling_price_per_sqft){$.error("Please fill in all required fields");return}le(!0);try{const C=await ge.entities.MaterialPriceList.create({material_name:E.material_name,supplier:E.supplier,material_type:E.material_type,cost_per_sqft:parseFloat(E.cost_per_sqft),selling_price_per_sqft:parseFloat(E.selling_price_per_sqft),color:E.color||"",is_active:!0});
31me.invalidateQueries({queryKey:["material-price-list-for-quote"]}),Y(!1),be({material_name:"",supplier:"",material_type:"quartz",cost_per_sqft:"",selling_price_per_sqft:"",color:""}),et(C),c(!1)}catch(C){$.error("Failed to add material: "+C.message)}finally{le(!1)}},{data:Ge=[]}=jt({queryKey:["servicePriceList"],queryFn:()=>ge.entities.ServicePriceList.list()}),{data:Ue=[]}=jt({queryKey:["productPriceList"],queryFn:()=>ge.entities.ProductPriceList.list()}),nt=C=>{const ne=l.filter(te=>te.material_type===C);if(!oe)return ne;const ce=oe.toLowerCase();return ne.filter(te=>{var Ce,Oe,b;return((Ce=te.material_name)==null?void 0:Ce.toLowerCase().includes(ce))||((Oe=te.color)==null?void 0:Oe.toLowerCase().includes(ce))||((b=te.supplier)==null?void 0:b.toLowerCase().includes(ce))})},lt=ue?Ge.filter(C=>{var ne,ce;return((ne=C.service_name)==null?void 0:ne.toLowerCase().includes(ue.toLowerCase()))||((ce=C.description)==null?void 0:ce.toLowerCase().includes(ue.toLowerCase()))}):Ge,dt=ye?Ue.filter(C=>{var ne,ce;return((ne=C.product_name)==null?void 0:ne.toLowerCase().includes(ye.toLowerCase()))||((ce=C.brand)==null?void 0:ce.toLowerCase().includes(ye.toLowerCase()))}):Ue,{edgeOptions:fe}=_c(),Ke=V?fe.filter(C=>{var ne,ce,te;return((ne=C.label)==null?void 0:ne.toLowerCase().includes(V.toLowerCase()))||((ce=C.description)==null?void 0:ce.toLowerCase().includes(V.toLowerCase()))||((te=C.value)==null?void 0:te.toLowerCase().includes(V.toLowerCase()))}):fe,et=C=>{r([...e,{...ga,name:C.material_name,material_name:C.material_name,material_type:C.material_type,color:C.color||"",unit_price_per_sqft:C.selling_price_per_sqft||C.cost_per_sqft||0,markup_pct:0}]),Ne(""),$.success(`Added ${C.material_name}`)},it=C=>{n([...s,{description:C.service_name,price:C.selling_price.toString(),qty:1,unit:C.unit||"each",markup_pct:0}]),je(""),$.success(`Added ${C.service_name}`)},Xe=C=>{i([...a,{name:C.product_name,price:C.selling_price.toString(),qty:1,unit:"each",markup_pct:0}]),W(""),$.success(`Added ${C.product_name}`)},pt=C=>{n([...s,{description:C.label,price:(C.price_per_linear_ft||0).toString(),qty:1,unit:"linear ft",markup_pct:0}]),q(""),$.success(`Added ${C.label}`)},x=()=>{if(!B.description||!B.price){$.error("Enter a description and amount");return}n([...s,{description:B.description,price:B.price,qty:parseFloat(B.qty)||1,unit:"each",markup_pct:0,is_custom_cost:!0}]),U({description:"",price:"",qty:1}),h(!1),$.success(`Added custom cost: ${B.description}`)},Q=({lineItems:C,services:ne,products:ce})=>{C!=null&&C.length&&r([...e,...C]),ne!=null&&ne.length&&n([...s,...ne]),ce!=null&&ce.length&&i([...a,...ce])};return t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"grid grid-cols-2 sm:flex gap-2 pt-3 border-t border-border",children:[t.jsxs(X,{variant:"outline",size:"sm",className:"sm:flex-1",onClick:()=>c(!0),children:[t.jsx(It,{className:"w-4 h-4 mr-1"})," Material"]}),t.jsxs(X,{variant:"outline",size:"sm",className:"sm:flex-1",onClick:()=>T(!0),children:[t.jsx(It,{className:"w-4 h-4 mr-1"})," Edges"]}),t.jsxs(X,{variant:"outline",size:"sm",className:"sm:flex-1",onClick:()=>j(!0),children:[t.jsx(It,{className:"w-4 h-4 mr-1"})," Service"]}),t.jsxs(X,{variant:"outline",size:"sm",className:"sm:flex-1",onClick:()=>A(!0),children:[t.jsx(It,{className:"w-4 h-4 mr-1"})," Product"]}),t.jsxs(X,{variant:"outline",size:"sm",className:"sm:flex-1 col-span-2 sm:col-span-1",onClick:()=>h(!0),children:[t.jsx(It,{className:"w-4 h-4 mr-1"})," Custom Cost"]}),t.jsxs(X,{variant:"outline",size:"sm",className:"sm:flex-1 col-span-2 sm:col-span-1",onClick:()=>z(!0),children:[t.jsx(da,{className:"w-4 h-4 mr-1"})," Assembly"]})]}),t.jsx(ts,{open:u,onOpenChange:c,children:t.jsxs(ss,{className:"max-w-2xl",children:[t.jsxs(as,{children:[t.jsx(rs,{children:"Add Material"}),t.jsx(gs,{children:"Select a material from your price list or inventory"})]}),t.jsxs("div",{className:"space-y-3",children:[t.jsxs("div",{className:"flex gap-2",children:[t.jsx(He,{placeholder:"Search by name, color, or supplier...",value:oe,onChange:C=>Ne(C.target.value),className:"h-9"}),t.jsxs(X,{type:"button",size:"sm",variant:"outline",className:"h-9 px-3 shrink-0",onClick:()=>Y(!0),title:"Add new material to price list",children:[t.jsx(It,{className:"w-4 h-4 mr-1"})," New"]})]}),t.jsx("div",{className:"space-y-3 max-h-96 overflow-y-auto",children:["quartz","granite","marble","quartzite","soapstone","laminate","butcher_block"].map(C=>{const ne=nt(C);return ne.length===0?null:t.jsxs("div",{className:"space-y-2",children:[t.jsx("h4",{className:"text-sm font-semibold capitalize",children:C}),t.jsx("div",{className:"grid grid-cols-2 gap-2",children:ne.map(ce=>{const te=!ce.is_remnant&&ce.slab_count!==void 0&&ce.total_sqft!==void 0,Ce=ce.is_remnant===!0,Oe=Ce?{label:"Remnant",cls:"bg-purple/10 text-purple border-purple/20"}:te?{label:"In Stock",cls:"bg-success/10 text-success border-success/20"}:{label:"Supplier",cls:"bg-info/10 text-info border-info/20"};return t.jsxs("button",{onClick:()=>{et(ce),c(!1)},className:"p-2 text-left border rounded hover:bg-primary/5 hover:border-primary/30 transition",children:[t.jsxs("div",{className:"flex items-start justify-between gap-1",children:[t.jsx("p",{className:"text-sm font-medium leading-tight",children:ce.material_name}),t.jsx("span",{className:`text-[10px] font-semibold px-1.5 py-0.5 rounded border whitespace-nowrap shrink-0 ${Oe.cls}`,children:Oe.label})]}),t.jsxs("p",{className:"text-xs text-muted-foreground",children:["$",ce.selling_price_per_sqft||ce.cost_per_sqft,"/sqft",te&&ce.total_sqft?` · ${ce.total_sqft} sqft`:"",!te&&!Ce&&ce.supplier?` · ${ce.supplier}`:"",Ce&&ce.sqft?` · ${ce.sqft} sqft`:""]})]},ce.id)})})]},C)})})]})]})}),t.jsx(ts,{open:M,onOpenChange:T,children:t.jsxs(ss,{children:[t.jsxs(as,{children:[t.jsx(rs,{children:"Add Edge Profile"}),t.jsx(gs,{children:"Select an edge type from your price list"})]}),t.jsxs("div",{className:"space-y-3",children:[t.jsx(He,{placeholder:"Search edges...",value:V,onChange:C=>q(C.target.value),className:"h-9"}),t.jsxs("div",{className:"space-y-2 max-h-96 overflow-y-auto",children:[Ke.map(C=>t.jsxs("button",{onClick:()=>{pt(C),T(!1)},className:"w-full p-2 text-left border rounded hover:bg-primary/5 hover:border-primary/30 transition",children:[t.jsxs("p",{className:"text-sm font-medium",children:[C.label,C.is_premium?" ★":""]}),t.jsxs("p",{className:"text-xs text-muted-foreground",children:[C.price_per_linear_ft?`$${C.price_per_linear_ft.toFixed(2)}/linear ft`:"—",C.description?` · ${C.description}`:""]})]},C.value)),Ke.length===0&&t.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No edge profiles found"})]})]})]})}),t.jsx(ts,{open:d,onOpenChange:j,children:t.jsxs(ss,{children:[t.jsxs(as,{children:[t.jsx(rs,{children:"Add Service"}),t.jsx(gs,{children:"Select a service from your price list"})]}),t.jsxs("div",{className:"space-y-3",children:[t.jsx(He,{placeholder:"Search services...",value:ue,onChange:C=>je(C.target.value),className:"h-9"}),t.jsxs("div",{className:"space-y-2 max-h-96 overflow-y-auto",children:[lt.map(C=>t.jsxs("button",{onClick:()=>{it(C),j(!1)},className:"w-full p-2 text-left border rounded hover:bg-primary/5 hover:border-primary/30 transition",children:[t.jsx("p",{className:"text-sm font-medium",children:C.service_name}),t.jsxs("p",{className:"text-xs text-muted-foreground",children:["$",C.selling_price]})]},C.id)),lt.length===0&&t.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No services found"})]})]})]})}),t.jsx(ts,{open:w,onOpenChange:A,children:t.jsxs(ss,{children:[t.jsxs(as,{children:[t.jsx(rs,{children:"Add Product"}),t.jsx(gs,{children:"Select a product from your price list"})]}),t.jsxs("div",{className:"space-y-3",children:[t.jsx(He,{placeholder:"Search by name or brand...",value:ye,onChange:C=>W(C.target.value),className:"h-9"}),t.jsxs("div",{className:"space-y-2 max-h-96 overflow-y-auto",children:[dt.map(C=>t.jsxs("button",{onClick:()=>{Xe(C),A(!1)},className:"w-full p-2 text-left border rounded hover:bg-primary/5 hover:border-primary/30 transition",children:[t.jsx("p",{className:"text-sm font-medium",children:C.product_name}),t.jsxs("p",{className:"text-xs text-muted-foreground",children:["$",C.selling_price]})]},C.id)),dt.length===0&&t.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No products found"})]})]})]})}),t.jsx(ts,{open:D,onOpenChange:Y,children:t.jsxs(ss,{children:[t.jsxs(as,{children:[t.jsx(rs,{children:"Add New Material Color"}),t.jsx(gs,{children:"This will be saved to the master price list under the designated supplier"})]}),t.jsxs("div",{className:"space-y-3 py-2",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsx(Ze,{className:"text-xs",children:"Material Name *"}),t.jsx(He,{value:E.material_name,onChange:C=>be({...E,material_name:C.target.value}),placeholder:"e.g. Calacatta Gold",className:"h-9"})]}),t.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsx(Ze,{className:"text-xs",children:"Material Type"}),t.jsxs(Wt,{value:E.material_type,onValueChange:C=>be({...E,material_type:C}),children:[t.jsx(zt,{className:"h-9",children:t.jsx(Ut,{})}),t.jsxs(Ht,{children:[t.jsx(Ye,{value:"quartz",children:"Quartz"}),t.jsx(Ye,{value:"granite",children:"Granite"}),t.jsx(Ye,{value:"marble",children:"Marble"}
31),t.jsx(Ye,{value:"quartzite",children:"Quartzite"}),t.jsx(Ye,{value:"soapstone",children:"Soapstone"}),t.jsx(Ye,{value:"laminate",children:"Laminate"}),t.jsx(Ye,{value:"butcher_block",children:"Butcher Block"})]})]})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx(Ze,{className:"text-xs",children:"Color"}),t.jsx(He,{value:E.color,onChange:C=>be({...E,color:C.target.value}),placeholder:"e.g. White",className:"h-9"})]})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx(Ze,{className:"text-xs",children:"Supplier *"}),t.jsx(He,{value:E.supplier,onChange:C=>be({...E,supplier:C.target.value}),placeholder:"e.g. Cambria",className:"h-9"})]}),t.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsx(Ze,{className:"text-xs",children:"Cost / Sqft ($) *"}),t.jsx(He,{type:"number",step:"0.01",value:E.cost_per_sqft,onChange:C=>be({...E,cost_per_sqft:C.target.value}),placeholder:"45.00",className:"h-9"})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx(Ze,{className:"text-xs",children:"Sell Price / Sqft ($) *"}),t.jsx(He,{type:"number",step:"0.01",value:E.selling_price_per_sqft,onChange:C=>be({...E,selling_price_per_sqft:C.target.value}),placeholder:"85.00",className:"h-9"})]})]})]}),t.jsxs($a,{children:[t.jsx(X,{variant:"outline",onClick:()=>Y(!1),children:"Cancel"}),t.jsx(X,{onClick:De,disabled:we,children:we?"Saving...":"Save to Price List"})]})]})}),t.jsx(ts,{open:P,onOpenChange:h,children:t.jsxs(ss,{children:[t.jsxs(as,{children:[t.jsx(rs,{children:"Add Custom Cost"}),t.jsx(gs,{children:"Add any one-off cost: transport, crane rental, sealing, after-hours, machine time, etc."})]}),t.jsxs("div",{className:"space-y-3 py-2",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsx(Ze,{className:"text-xs",children:"Description *"}),t.jsx(He,{value:B.description,onChange:C=>U({...B,description:C.target.value}),placeholder:"e.g. Crane rental for 3rd floor",className:"h-9"})]}),t.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsx(Ze,{className:"text-xs",children:"Amount ($) *"}),t.jsx(He,{type:"number",step:"0.01",value:B.price,onChange:C=>U({...B,price:C.target.value}),placeholder:"500.00",className:"h-9"})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx(Ze,{className:"text-xs",children:"Quantity"}),t.jsx(He,{type:"number",step:"1",value:B.qty,onChange:C=>U({...B,qty:C.target.value}),placeholder:"1",className:"h-9"})]})]})]}),t.jsxs($a,{children:[t.jsx(X,{variant:"outline",onClick:()=>h(!1),children:"Cancel"}),t.jsx(X,{onClick:x,children:"Add Cost"})]})]})}),t.jsx(bc,{open:J,onOpenChange:z,onInsert:Q,currentLineItems:e,currentServices:s,currentProducts:a})]})}function wc({lineItems:e,services:s,products:a,onUpdateItems:r,onUpdateServices:n,onUpdateProducts:i,allMaterials:l=[],pricingConfig:u={},discountType:c,discountValue:d,taxRate:j,applyCreditCardFee:w,creditCardFeeRate:A,paymentsReceived:M=0,depositSchedule:T=[],measurementUnit:D="imperial",headerTitle:Y="Your Custom Quote",headerTools:P=null,actionBar:h=null,children:J}){const{user:z}=ki(),B=(z==null?void 0:z.role)==="admin";u.backsplash_rate_per_sqft,u.sink_cutout_flat_fee,u.cooktop_cutout_flat_fee,u.special_feature_flat_fee,u.finished_edge_rate_per_linear_ft;const U=(x,Q)=>Q.discount_approval_status==="approved"&&Q.discount_pct>0?x*(1-Q.discount_pct/100):x,oe=x=>{const Q=parseFloat(x.sqft)||0,C=x.unit_price_per_sqft||0,ne=x.markup_pct||0,ce=x.sink_type&&x.sink_type!=="none"?u.sink_cutout_flat_fee??75:0,te=x.cooktop_included?u.cooktop_cutout_flat_fee??125:0,Ce=x.backsplash?Q*(u.backsplash_rate_per_sqft??12):0,Oe=(x.special_features||[]).length*(u.special_feature_flat_fee??50),tt=(parseFloat(x.edge_linear_ft)||0)*(u.finished_edge_rate_per_linear_ft??8),ms=ce+te+Ce+Oe+tt;return U(Q*C*(1+ne/100)+ms,x)},Ne=x=>{const Q=parseFloat(x.price)||0,C=x.markup_pct||0,ne=parseFloat(x.qty)||1;return U(ne*Q*(1+C/100),x)},ue=x=>{const Q=parseFloat(x.price)||0,C=x.markup_pct||0,ne=parseFloat(x.qty)||1;return U(ne*Q*(1+C/100),x)},je=e,ye=je[0]||{},W=je.reduce((x,Q)=>
31x+(parseFloat(Q.sqft)||0),0),V=je.reduce((x,Q)=>{let C=0;return Q.sink_type&&Q.sink_type!=="none"&&C++,Q.cooktop_included&&C++,x+C},0),q=[{label:"Material",value:ye.material_name||"—"},{label:"Edge",value:ye.edge_profile?ye.edge_profile.charAt(0).toUpperCase()+ye.edge_profile.slice(1):"Eased"},{label:"Area",value:Es(W,D)},{label:"Cutouts",value:V}],E=[...e.map((x,Q)=>({type:"material",data:x,index:Q,total:oe(x)})),...s.map((x,Q)=>({type:"service",data:x,index:Q,total:Ne(x)})),...a.map((x,Q)=>({type:"product",data:x,index:Q,total:ue(x)}))],be=(x,Q)=>{const C=parseFloat(Q)||0;if(x.type==="material"){const ne=[...e];B?ne[x.index]={...ne[x.index],unit_price_per_sqft:C}:ne[x.index]={...ne[x.index],pending_price:C,price_approval_status:"pending",price_approval_requested_by:(z==null?void 0:z.full_name)||(z==null?void 0:z.email)||"Salesperson"},r(ne)}else if(x.type==="service"){const ne=[...s];ne[x.index]={...ne[x.index],price:C.toString()},n(ne)}else if(x.type==="product"){const ne=[...a];ne[x.index]={...ne[x.index],price:C.toString()},i(ne)}},we=x=>{const Q=[...e],C=Q[x];Q[x]={...C,unit_price_per_sqft:C.pending_price,pending_price:null,price_approval_status:"approved"},r(Q),$.success("Price change approved")},le=x=>{const Q=[...e];Q[x]={...Q[x],pending_price:null,price_approval_status:"rejected"},r(Q),$.info("Price change rejected")},me=(x,Q)=>{const C=x.type==="material"?e:x.type==="service"?s:a,ne=x.type==="material"?r:x.type==="service"?n:i,ce=x.index,te=Q==="up"?ce-1:ce+1;if(te<0||te>=C.length)return;const Ce=[...C];[Ce[ce],Ce[te]]=[Ce[te],Ce[ce]],ne(Ce)},De=x=>{x.type==="material"?r(e.filter((Q,C)=>C!==x.index)):x.type==="service"?n(s.filter((Q,C)=>C!==x.index)):i(a.filter((Q,C)=>C!==x.index))},Ge=(x,Q,C)=>{if(x==="material"){const ne=[...e];ne[Q]={...ne[Q],...C},r(ne)}else if(x==="service"){const ne=[...s];ne[Q]={...ne[Q],...C},n(ne)}else{const ne=[...a];ne[Q]={...ne[Q],...C},i(ne)}},Ue=e.reduce((x,Q)=>x+oe(Q),0),nt=s.reduce((x,Q)=>x+Ne(Q),0),lt=a.reduce((x,Q)=>x+ue(Q),0),dt=Ue+nt+lt,{discountAmount:fe,taxAmount:Ke,ccFeeAmount:et,finalTotal:it}=Ya({basePrice:dt,discountType:c,discountValue:d,taxRate:j,applyCreditCardFee:w,ccFeeRate:A}),Xe="h-8 text-xs border rounded-sm px-2",pt=(x,Q)=>{const C=x.type==="material"?x.data.unit_price_per_sqft||0:parseFloat(x.data.price)||0,ne=x.data.markup_pct||0;return t.jsxs("div",{className:"px-3 py-2.5 border-b border-border/50 last:border-b-0",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsxs("div",{className:"shrink-0",children:[x.type==="material"&&t.jsx(Wi,{material:l.find(ce=>ce.material_name===x.data.material_name)||x.data,size:"sm"}),x.type==="service"&&t.jsx("div",{className:"w-8 h-8 rounded-md bg-primary/10 flex items-center justify-center",children:t.jsx(da,{className:"w-4 h-4 text-primary"})}),x.type==="product"&&t.jsx(Va,{className:"w-4 h-4 text-muted-foreground/40"})]}),t.jsxs("div",{className:"flex-1 min-w-0 flex flex-wrap items-center gap-2",children:[x.type==="material"?t.jsxs(t.Fragment,{children:[t.jsx("input",{type:"text",value:x.data.area_name||"",onChange:ce=>{const te=[...e];te[x.index]={...te[x.index],area_name:ce.target.value},r(te)},placeholder:"Area/Room",className:`${Xe} w-24 sm:w-32`}),t.jsxs("div",{className:"relative inline-block w-16 sm:w-20",children:[t.jsx("input",{type:"number",value:x.data.sqft||"",onChange:ce=>{const te=[...e];te[x.index]={...te[x.index],sqft:parseFloat(ce.target.value)||0},r(te)},className:`${Xe} w-full pr-7`,min:"0",step:"0.1"}),t.jsx("span",{className:"absolute right-1.5 top-1/2 -translate-y-1/2 text-[10px] text-muted-foreground",children:"sqft"})]}),t.jsx("span",{className:"text-sm text-foreground truncate",children:x.data.name||x.data.material_name})]}):t.jsxs(t.Fragment,{children:[t.jsx("input",{type:"number",value:x.data.qty||1,onChange:ce=>{const te=x.type==="service"?s:a,Ce=x.type==="service"?n:i,Oe=[...te];Oe[x.index]={...Oe[x.index],qty:parseFloat(ce.target.value)||1},Ce(Oe)},className:`${Xe} w-14`,min:"0",step:"0.1"}),t.jsx("input",{type:"text",value:x.data.unit||"each",onChange:ce=>{const te=x.type==="service"?s:a,Ce=x.type==="service"?n:i,Oe=[...te];Oe[x.index]={...Oe[x.index],unit:ce.target.value},Ce(Oe)},className:`${Xe} w-16`}),t.jsx("span",{className:"text-sm text-foreground truncate",children:x.type==="service"?x.data.description:x.data.name})]}),x.type==="material"||B||x.type!=="material"?t.jsxs("div",{className:"flex flex-col gap-0.5",children:[t.jsxs("div",{className:"flex items-center gap-0.5",children:[t.jsx("span",{className:"text-xs text-muted-foreground",children:"@ $"}),t.jsx("input",{type:"number",step:"0.01",value:x.type==="material"&&!B?x.data.pending_price??(C||""):C||"",onChange:ce=>be(x,ce.target.value),className:`${Xe} w-16`,min:"0"}),t.jsx("span",{className:"text-xs text-muted-foreground",children:x.type==="material"?"/sqft":`/${x.data.unit||"each"}`})]}),x.type==="material"&&t.jsx(xc,{status:x.data.price_approval_status,pendingPrice:x.data.pending_price,currentPrice:C,requestedBy:x.data.price_approval_requested_by,onApprove:()=>we(x.index),onReject:()=>le(x.index),isAdmin:B})]}):t.jsxs("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:["@ $",C.toFixed(2),x.type==="material"?"/sqft":`/${x.data.unit||"each"}`]}),ne!==0&&t.jsxs("span",{className:"text-xs text-primary font-medium",children:["+",ne,"%"]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[t.jsxs("span",{className:"text-sm font-semibold tabular-nums text-right w-20",children:["$",x.total.toFixed(2)]}),t.jsxs("div",{className:"flex flex-col",children:[t.jsx("button",{onClick:()=>me(x,"up"),disabled:x.index===0,className:"p-0.5 hover:bg-accent rounded text-muted-foreground transition-colors disabled:opacity-30 disabled:pointer-events-none",title:"Move up",children:t.jsx(To,{className:"w-3.5 h-3.5"})}),t.jsx("button",{onClick:()=>me(x,"down"),disabled:x.index===(x.type==="material"?e:x.type==="service"?s:a).length-1,className:"p-0.5 hover:bg-accent rounded text-muted-foreground transition-colors disabled:opacity-30 disabled:pointer-events-none",title:"Move down",children:t.jsx(qi,{className:"w-3.5 h-3.5"})})]}),t.jsx("button",{onClick:()=>De(x),className:"p-1.5 hover:bg-destructive/10 rounded text-destructive transition-colors",title:"Delete",children:t.jsx(Fs,{className:"w-4 h-4"})})]})]}),t.jsx(gc,{line:x.data,type:x.type,index:x.index,isAdmin:B,user:z,onUpdateLine:Ge})]},`${x.type}-${Q}`)};return t.jsxs("div",{className:"rounded-xl border border-border overflow-hidden shadow-sm bg-[#fcfaf6] dark:bg-slate-800",children:[t.jsxs("div",{className:"bg-primary px-4 py-3 flex items-center justify-between gap-2 flex-wrap",children:[t.jsxs("h3",{className:"text-primary-foreground font-semibold text-sm flex items-center gap-2",children:[t.jsx(qs,{className:"w-4 h-4"}),Y]}),h]}),E.length>0&&t.jsx("div",{className:"bg-primary/90 text-primary-foreground px-4 py-2.5",children:t.jsx("div",{className:"flex flex-wrap items-center gap-x-6 gap-y-1.5 text-sm",children:q.map(x=>t.jsxs("div",{className:"flex flex-col",children:[t.jsx("span",{className:"text-[10px] uppercase tracking-wide opacity-70",children:x.label}),t.jsx("span",{className:"font-semibold capitalize",children:x.value})]},x.label))})}),J&&t.jsx("div",{className:"p-4 space-y-4",children:J}),t.jsx("div",{className:"divide-y divide-border",children:E.length===0?t.jsxs("div",{className:"text-center py-10",children:[t.jsx(da,{className:"w-12 h-12 mx-auto text-muted-foreground opacity-20 mb-2"}),t.jsx("p",{className:"text-sm text-muted-foreground",children:"No line items added yet"}),t.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Add materials, services, or products to build your quote"})]}):t.jsxs(t.Fragment,{children:[e.length>0&&t.jsxs("div",{children:[e.length>1&&t.jsx("div",{className:"px-3 py-1.5 bg-slate-50 dark:bg-slate-900/40",children:t.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wide text-muted-foreground",children:"Materials"})}),e.map((x,Q)=>pt(E[Q],Q))]}),(s.length>0||a.length>0)&&t.jsxs("div",{children:[t.jsx("div",{className:"px-3 py-1.5 bg-slate-50 dark:bg-slate-900/40",children:t.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wide text-muted-foreground",children:"Services & Products"})}),s.map((x,Q)=>pt(E[e.length+Q],e.length+Q)),a.map((x,Q)=>pt(E[e.length+s.length+Q],e.length+s.length+Q))]})]})}),E.length>0&&t.jsxs("div",{className:"px-4 py-3 bg-slate-50 dark:bg-slate-900/50 border-t border-border space-y-1.5 text-sm",children:[t.jsxs("div",{className:"flex justify-between font-semibold",children:[t.jsx("span",{children:"Subtotal:"}),t.jsxs("span",{className:"tabular-nums",children:["$",dt.toFixed(2)]})]}),c!=="none"&&fe>0&&t.jsxs("div",{className:"flex justify-between text-success",children:[t.jsxs("span",{children:["Discount (",c==="percentage"?`${d}
31%`:"$"+d,"):"]}),t.jsxs("span",{className:"tabular-nums",children:["-$",fe.toFixed(2)]})]}),t.jsxs("div",{className:"flex justify-between",children:[t.jsxs("span",{className:"text-sm",children:["Tax (",j||0,"%):"]}),t.jsxs("span",{className:"tabular-nums font-medium",children:["$",Ke.toFixed(2)]})]}),t.jsxs("div",{className:"flex justify-between",children:[t.jsxs("span",{className:"text-sm",children:["Credit Card Fee (",w?A:0,"%):"]}),t.jsxs("span",{className:"tabular-nums font-medium",children:["$",et.toFixed(2)]})]}),t.jsx("div",{className:"border-t-2 border-primary my-1"}),t.jsxs("div",{className:"flex justify-between text-xl font-bold text-primary",children:[t.jsx("span",{children:"Total Price:"}),t.jsxs("span",{className:"tabular-nums",children:["$",it.toFixed(2)]})]}),T.length>0&&t.jsxs("div",{className:"pt-2 space-y-1",children:[t.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Deposit Schedule"}),T.map((x,Q)=>t.jsxs("div",{className:"flex justify-between text-sm",children:[t.jsxs("span",{className:"text-muted-foreground",children:[x.label," (",x.percentage,"%)",x.due_date&&t.jsxs("span",{className:"text-xs ml-1 opacity-70",children:["· due ",x.due_date]})]}),t.jsxs("span",{className:"tabular-nums font-medium",children:["$",(it*x.percentage/100).toFixed(2)]})]},x.id||Q))]}),M>0&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex justify-between text-success",children:[t.jsx("span",{className:"text-sm",children:"Payments Received:"}),t.jsxs("span",{className:"tabular-nums font-medium",children:["-$",M.toFixed(2)]})]}),M>=it&&it>0?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex justify-between text-lg font-bold pt-1 text-success",children:[t.jsx("span",{children:"Paid in Full"}),t.jsx("span",{className:"tabular-nums",children:"$0.00"})]}),M>it&&t.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[t.jsx("span",{children:"Customer Credit (overpayment):"}),t.jsxs("span",{className:"tabular-nums",children:["$",(M-it).toFixed(2)]})]})]}):t.jsxs("div",{className:"flex justify-between text-lg font-bold pt-1",children:[t.jsx("span",{children:"Balance Due:"}),t.jsxs("span",{className:"tabular-nums",children:["$",Math.max(0,it-M).toFixed(2)]})]})]})]}),t.jsx("div",{className:"p-3",children:t.jsx(jc,{lineItems:e,services:s,products:a,onUpdateItems:r,onUpdateServices:n,onUpdateProducts:i,allMaterials:l})})]})}function zi({onSave:e,onSaveAndCreateJob:s,canCreateJob:a=!1,onEdit:r,onEmail:n,canEmail:i=!0,isEmailing:l=!1,onText:u,canText:c=!0,isTexting:d=!1,onWhatsApp:j,canWhatsApp:w=!0,isWhatsApping:A=!1,onPrint:M,canPrint:T=!0,isPrinting:D=!1,onPdf:Y,canPdf:P=!0,isExportingPdf:h=!1,onRevisions:J,onPayment:z,isCreatingPaymentLink:B=!1,paymentLinkUrl:U=null,onEsign:oe,isSendingContract:Ne=!1,contractSent:ue=!1,onRefreshCosts:je,isRefreshingCosts:ye=!1,onCreateSalesOrder:W,isCreatingSalesOrder:V=!1,onToggleTax:q,isSaved:E=!1}){return t.jsxs("div",{className:"flex items-center gap-1 flex-wrap justify-start sm:justify-end",children:[s&&a&&t.jsxs(X,{variant:"default",size:"sm",onClick:s,className:"gap-1.5 shrink-0 h-8",title:"Save & Create Job",children:[t.jsx(Ga,{className:"w-4 h-4"}),t.jsx("span",{className:"hidden sm:inline",children:"Create Job"})]}),e&&!E&&t.jsx(X,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",onClick:e,title:"Save Quote",children:t.jsx(Ka,{className:"w-4 h-4"})}),E&&r&&t.jsx(X,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",onClick:r,title:"Edit Quote",children:t.jsx(Ir,{className:"w-4 h-4"})}),n&&t.jsx(X,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",onClick:n,disabled:!i||l,title:"Email Quote",children:l?t.jsx("span",{className:"w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin"}):t.jsx($r,{className:"w-4 h-4"})}),u&&t.jsx(X,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",onClick:u,disabled:!c||d,title:"Text Quote",children:d?t.jsx("span",{className:"w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin"}):t.jsx(Fi,{className:"w-4 h-4"})}),j&&t.jsx(X,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",onClick:j,disabled:!w||A,title:"Send via WhatsApp",children:A?t.jsx("span",{className:"w-4 h-4 border-2 border-current border-t-transparent roun
31ded-full animate-spin"}):t.jsx(Li,{className:"w-4 h-4 text-green-600"})}),M&&t.jsx(X,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",onClick:M,disabled:!T||D,title:"Print & Sign",children:D?t.jsx("span",{className:"w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin"}):t.jsx(fo,{className:"w-4 h-4"})}),Y&&t.jsx(X,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",onClick:Y,disabled:!P||h,title:"Download PDF",children:h?t.jsx("span",{className:"w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin"}):t.jsx(Si,{className:"w-4 h-4"})}),E&&J&&t.jsx(X,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",onClick:J,title:"Revisions",children:t.jsx(Ps,{className:"w-4 h-4"})}),E&&z&&t.jsx(X,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",onClick:z,disabled:B,title:U?"Copy Payment Link":"Create Payment Link",children:B?t.jsx("span",{className:"w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin"}):t.jsx(la,{className:"w-4 h-4"})}),E&&oe&&t.jsx(X,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",onClick:oe,disabled:Ne||ue,title:ue?"Contract Sent":"Send E-Signature",children:Ne?t.jsx("span",{className:"w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin"}):t.jsx(qo,{className:"w-4 h-4"})}),E&&je&&t.jsx(X,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",onClick:je,disabled:ye,title:"Refresh costs from latest prices",children:ye?t.jsx("span",{className:"w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin"}):t.jsx(Fo,{className:"w-4 h-4"})}),E&&W&&t.jsx(X,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",onClick:W,disabled:V,title:"Create Draft Sales Order",children:V?t.jsx("span",{className:"w-4 h-4 border-2 border-current border-t-transparent rounded-full animate-spin"}):t.jsx(po,{className:"w-4 h-4"})}),q&&t.jsx(X,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",onClick:q,title:"Tax & Discount",children:t.jsx(xo,{className:"w-4 h-4"})})]})}function vc({open:e=!1,onOpenChange:s,onComplete:a,existingQuoteData:r={}}){const[n,i]=m.useState(1),[l,u]=m.useState(!1),[c,d]=m.useState({roomType:r.project_type||"",materialPreference:"",approximateSize:r.sqft||"",budget:""}),j=async()=>{u(!0);try{const D=`Based on these preferences:
32- Room Type: ${c.roomType}
33- Material Preference: ${c.materialPreference}
34- Approximate Size: ${c.approximateSize} sqft
35- Budget Range: ${c.budget}
36
37Provide a JSON response with recommended quote configuration:
38{
39  "material_type": "granite|quartz|marble|quartzite|laminate",
40  "material_name": "specific material name",
41  "edge_profile": "eased|bullnose|ogee|bevel",
42  "estimated_sqft": number
43}`,Y=await ge.integrations.Core.InvokeLLM({prompt:D,response_json_schema:{type:"object",properties:{material_type:{type:"string"},material_name:{type:"string"},edge_profile:{type:"string"},estimated_sqft:{type:"number"}},required:["material_type","material_name","edge_profile","estimated_sqft"]}});a({...c,...Y}),$.success("Quote configured with AI recommendations!")}catch(D){console.error("AI analysis failed:",D),$.error("Failed to analyze preferences. Please configure manually.")}finally{u(!1)}},w=()=>{n===3?j():i(n+1)},A=()=>{n>1&&i(n-1)},M=(D,Y)=>{d(P=>({...P,[D]:Y}))},T=()=>n===1?!!c.roomType:n===2?!!c.materialPreference:n===3?!!c.approximateSize:!1;return t.jsx(ts,{open:e,onOpenChange:s,children:t.jsxs(ss,{className:"max-w-md",children:[t.jsxs(as,{children:[t.jsxs(rs,{className:"flex items-center gap-2",children:[t.jsx(Or,{className:"w-5 h-5 text-primary"}),"Quick Quote Setup"]}),t.jsx(gs,{children:"Answer 3 quick questions and let AI configure your quote"})]}),t.jsxs("div",{className:"py-4",children:[t.jsx("div",{className:"flex items-center gap-2 mb-6",children:[1,2,3].map(D=>t.jsxs("div",{className:"flex items-center",children:[t.jsx("div",{className:`w-8 h-8 rounded-full flex items-center justify-center text-xs font-semibold ${D<=n?"bg-primary text-primary-foreground":"bg-slate-200 dark:bg-slate-700 text-slate-500"}`,children:D<n?t.jsx(qs,{className:"w-4 h-4"}):D}),D<3&&t.jsx("div",{className:`w-12 h-0.5 mx-1 ${D<n?"bg-primary":"bg-slate-200 dark:bg-slate-700"}`})]},D))}),n===1&&t.jsx(at,{children:t.jsx(rt,{className:"pt-6 space-y-4",children:t.jsxs("div",{className:"space-y-2",children:[t.jsx(Ze,{children:"What type of room is this for?"}),t.jsxs(Wt,{value:c.roomType,onValueChange:D=>M("roomType",D),children:[t.jsx(zt,{children:t.jsx(Ut,{placeholder:"Select room type"})}),t.jsxs(Ht,{children:[t.jsx(Ye,{value:"kitchen",children:"Kitchen"}),t.jsx(Ye,{value:"bathroom",children:"Bathroom"}),t.jsx(Ye,{value:"commercial",children:"Commercial"}),t.jsx(Ye,{value:"outdoor",children:"Outdoor Kitchen"}),t.jsx(Ye,{value:"other",children:"Other"})]})]})]})})}),n===2&&t.jsx(at,{children:t.jsx(rt,{className:"pt-6 space-y-4",children:t.jsxs("div",{className:"space-y-2",children:[t.jsx(Ze,{children:"What material are they interested in?"}),t.jsxs(Wt,{value:c.materialPreference,onValueChange:D=>M("materialPreference",D),children:[t.jsx(zt,{children:t.jsx(Ut,{placeholder:"Select material type"})}),t.jsxs(Ht,{children:[t.jsx(Ye,{value:"quartz",children:"Quartz (Engineered)"}),t.jsx(Ye,{value:"granite",children:"Granite (Natural)"}),t.jsx(Ye,{value:"marble",children:"Marble (Luxury)"}
43),t.jsx(Ye,{value:"quartzite",children:"Quartzite (Premium)"}),t.jsx(Ye,{value:"laminate",children:"Laminate (Budget)"}),t.jsx(Ye,{value:"not_sure",children:"Not Sure - Advise Me"})]})]})]})})}),n===3&&t.jsx(at,{children:t.jsx(rt,{className:"pt-6 space-y-4",children:t.jsxs("div",{className:"space-y-2",children:[t.jsx(Ze,{children:"Approximate square footage?"}),t.jsx(He,{type:"number",value:c.approximateSize,onChange:D=>M("approximateSize",D.target.value),placeholder:"e.g., 50"}),t.jsx("p",{className:"text-xs text-muted-foreground",children:"Average kitchen: 40-60 sqft | Bathroom: 20-30 sqft"})]})})})]}),t.jsxs($a,{children:[n>1&&t.jsx(X,{variant:"outline",onClick:A,className:"mr-auto",children:"Back"}),t.jsx(X,{onClick:w,disabled:!T()||l,className:"ml-auto",children:l?t.jsxs(t.Fragment,{children:[t.jsx(Bt,{className:"w-4 h-4 mr-2 animate-spin"}),"Analyzing..."]}):n===3?t.jsxs(t.Fragment,{children:[t.jsx(Jn,{className:"w-4 h-4 mr-2"}),"Configure Quote"]}):t.jsxs(t.Fragment,{children:["Next",t.jsx(Jn,{className:"w-4 h-4 ml-2"})]})})]})]})})}const yr=e=>(e||0).toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2});function Nc({totalCost:e,sellingPrice:s,marginPct:a,targetMargin:r=75}){const n=(s||0)-(e||0),i=n<0,l=(s||0)>0,u=l&&a>=r,c=l?a<10?{bar:"bg-red-500",text:"text-red-600",bg:"bg-red-50 dark:bg-red-900/20",border:"border-red-200 dark:border-red-800"}:a<25?{bar:"bg-orange-500",text:"text-orange-600",bg:"bg-orange-50 dark:bg-orange-900/20",border:"border-orange-200 dark:border-orange-800"}:a<r?{bar:"bg-yellow-500",text:"text-yellow-600",bg:"bg-yellow-50 dark:bg-yellow-900/20",border:"border-yellow-200 dark:border-yellow-800"}:{bar:"bg-green-500",text:"text-green-600",bg:"bg-green-50 dark:bg-green-900/20",border:"border-green-200 dark:border-green-800"}:{bar:"bg-muted",text:"text-muted-foreground",bg:"bg-muted/30",border:"border-border"},d=Math.min(Math.max(a||0,0),100),j=Math.min(Math.max(r,0),100);return t.jsxs("div",{className:`rounded-lg border ${c.border} ${c.bg} p-4`,children:[t.jsxs("div",{className:"flex items-center justify-between mb-3",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[i?t.jsx(Ai,{className:"w-4 h-4 text-red-600"}):t.jsx(Aa,{className:`w-4 h-4 ${c.text}`}),t.jsx("span",{className:"font-semibold text-sm",children:"Live Profit Margin"})]}),t.jsxs("span",{className:`text-2xl font-bold ${c.text}`,children:[(a||0).toFixed(1),"%"]})]}),t.jsxs("div",{className:"relative h-3 bg-muted rounded-full overflow-hidden mb-1",children:[t.jsx("div",{className:`h-full ${c.bar} rounded-full transition-all duration-300`,style:{width:`${d}%`}}),t.jsx("div",{className:"absolute top-0 h-full w-0.5 bg-foreground
43/50",style:{left:`${j}%`},title:`Target: ${r}%`})]}),t.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground mb-3",children:[t.jsx("span",{children:"0%"}),t.jsxs("span",{className:"flex items-center gap-1",children:[t.jsx(Lo,{className:"w-3 h-3"})," Target ",r,"%"]}),t.jsx("span",{children:"100%"})]}),t.jsxs("div",{className:"grid grid-cols-3 gap-2 text-center",children:[t.jsxs("div",{children:[t.jsx("p",{className:"text-xs text-muted-foreground",children:"Cost"}),t.jsxs("p",{className:"font-semibold text-sm",children:["$",yr(e)]})]}),t.jsxs("div",{children:[t.jsx("p",{className:"text-xs text-muted-foreground",children:"Price"}),t.jsxs("p",{className:"font-semibold text-sm",children:["$",yr(s)]})]}),t.jsxs("div",{children:[t.jsx("p",{className:"text-xs text-muted-foreground",children:"Profit"}),t.jsxs("p",{className:`font-semibold text-sm ${i?"text-red-600":"text-green-600"}`,children:[i?"−":"","$",yr(Math.abs(n))]})]})]}),l&&a<10&&t.jsxs("div",{className:"mt-2 flex items-center gap-1 text-xs text-red-600 font-medium",children:[t.jsx(Ci,{className:"w-3.5 h-3.5"}),a<5?"This quote will lose money!":"Very low profit margin — raise the price."]}),u&&t.jsxs("div",{className:"mt-2 flex items-center gap-1 text-xs text-green-600 font-medium",children:[t.jsx(Hs,{className:"w-3.5 h-3.5"})," Above target margin"]})]})}const kc=1200,Sc=700;function Cc(e){const s=Math.floor(e+.005),a=e-s,r=Math.round(a*16);if(r===0||r===16)return`${s+(r===16?1:0)}"`;const n=(l,u)=>u?n(u,l%u):l,i=n(r,16);return`${s} ${r/i}/${16/i}"`}function Mc(e,s,a){const r=e.length;if(r<3)return e;const n=e.map(P=>({...P})),i=n[s],l=(s+1)%r,u={...n[l]},c=a*10,d=u.x-i.x,j=u.y-i.y,w=Math.sqrt(d*d+j*j);if(w<1)return e;const A=d/w*c,M=j/w*c,T=A-d,D=M-j;n[l].x+=T,n[l].y+=D;const Y=Math.abs(d)>Math.abs(j);for(let P=1;P<r-1;P++){const h=(l+P)%r,J=n[h];if(Y)if(Math.abs(J.x-u.x)<1)J.x+=T;else break;else if(Math.abs(J.y-u.y)<1)J.y+=D;else break}return n}function Dc({piece:e,canvasRef:s,onDimensionChange:a}){const[r,n]=m.useState(null),[i,l]=m.useState(""),[u,c]=m.useState({w:0,h:0}),d=m.useRef(null);if(m.useEffect(()=>{const D=s.current;if(!D)return;const Y=()=>{d.current||(d.current=requestAnimationFrame(()=>{d.current=null;const h=D.getBoundingClientRect();c({w:h.width,h:h.height})}))};Y();const P=new ResizeObserver(Y);return P.observe(D),window.addEventListener("scroll",Y,!0),()=>{P.disconnect(),window.removeEventListener("scroll",Y,!0),d.current&&cancelAnimationFrame(d.current)}},[s]),!e||u.w===0)return null;const j=e.points||[];if(j.length<3)return null;const w=u.w/kc,A=u.h/Sc,M=[];for(let D=0;D<j.length;D++){const Y=j[D],P=j[(D+1)%j.length],h=(Y.x+P.x)/2,J=(Y.y+P.y)/2,z=Math.sqrt((P.x-Y.x)**2+(P.y-Y.y)**2)/10,B=P.x-Y.x,U=P.y-Y.y,oe=Math.sqrt(B*B+U*U)||1,Ne=-U/oe*22,ue=B/oe*22;M.push({index:D,x:(h+Ne)*w,y:(J+ue)*A,length:z})}const T=()=>{const D=parseFloat(i);D&&D>0&&a(r,D),n(null)};return t.jsx("div",{className:"absolute inset-0 pointer-events-none z-10",children:M.map(D=>t.jsx("div",{className:"absolute pointer-events-auto",style:{left:`${D.x}px`,top:`${D.y}px`,transform:"translate(-50%, -50%)"},children:r===D.index?t.jsxs("div",{className:"flex items-center gap-0.5 bg-white rounded-md border-2 border-primary shadow-lg px-1 py-0.5",children:[t.jsx("input",{autoFocus:!0,t
43ype:"number",step:"0.125",value:i,onChange:Y=>l(Y.target.value),onBlur:T,onKeyDown:Y=>{Y.key==="Enter"&&T(),Y.key==="Escape"&&n(null)},className:"w-14 text-center text-xs font-bold text-primary bg-transparent outline-none"}),t.jsx("span",{className:"text-xs text-muted-foreground",children:"in"})]}):t.jsx("button",{onClick:()=>{n(D.index),l(D.length.toFixed(1))},className:"text-[11px] font-bold text-primary bg-white/90 hover:bg-white px-1.5 py-0.5 rounded border border-primary/40 hover:border-primary shadow-sm transition-all cursor-pointer hover:scale-105",children:Cc(D.length)})},D.index))})}const Pc=1200,Tc=700,ri=15;function qc(e){let s=1/0,a=1/0,r=-1/0,n=-1/0;for(const i of e)i.x<s&&(s=i.x),i.x>r&&(r=i.x),i.y<a&&(a=i.y),i.y>n&&(n=i.y);return{minX:s,minY:a,maxX:r,maxY:n}}function ni(e,s,a,r){return Math.atan2(r-s,a-e)*(180/Math.PI)}function Fc({piece:e,canvasRef:s,onRotate:a}){const[r,n]=m.useState({w:0,h:0}),i=m.useRef(!1),l=m.useRef(0),u=m.useRef(0),[c,d]=m.useState(!1);if(m.useEffect(()=>{const B=s.current;if(!B)return;const U=()=>{const Ne=B.getBoundingClientRect();n({w:Ne.width,h:Ne.height})};U();const oe=new ResizeObserver(U);return oe.observe(B),window.addEventListener("scroll",U,!0),()=>{oe.disconnect(),window.removeEventListener("scroll",U,!0)}},[s]),!e||r.w===0)return null;const j=e.points||[];if(j.length<3)return null;const w=qc(j),A=r.w/Pc,M=r.h/Tc,T=(w.minX+w.maxX)/2*A,D=(w.minY+w.maxY)/2*M,Y=w.minY*M,P=Math.max(28,Y-32),h=B=>{B.preventDefault(),B.stopPropagation(),i.current=!0,d(!0);const U=s.current.getBoundingClientRect(),oe=B.clientX-U.left,Ne=B.clientY-U.top;l.current=ni(T,D,oe,Ne),u.current=0,window.addEventListener("pointermove",J),window.addEventListener("pointerup",z)},J=B=>{if(!i.current)return;const U=s.current.getBoundingClientRect(),oe=B.clientX-U.left,Ne=B.clientY-U.top;let je=ni(T,D,oe,Ne)-l.current;B.shiftKey||(je=Math.round(je/ri)*ri);const ye=je-u.current;Math.abs(ye)>.1&&(a(ye),u.current=je)},z=()=>{i.current=!1,d(!1),window.removeEventListener("pointermove",J),window.removeEventListener("pointerup",z)};return t.jsx("div",{onPointerDown:h,className:"absolute z-20 pointer-events-auto flex items-center justify-center cursor-grab active:cursor-grabbing",style:{left:`${T}px`,top:`${P}px`,transform:"translate(-50%, -50%)"},children:t.jsxs("div",{className:`flex items-center gap-1 px-2 py-1 rounded-full border-2 shadow-lg transition-colors ${c?"bg-primary text-primary-foreground border-primary":"bg-white text-primary border-primary hover:bg-primary/10"}`,children:[t.jsx(Ao,{className:"w-3.5 h-3.5"}),t.jsx("span",{className:"text-[10px] font-bold",children:"Rotate"})]})})}const Lc=[{id:"rect",label:"Rectangle",Icon:Cr},{id:"polygon",label:"Free Draw",Icon:Oa},{id:"angle",label:"Angle",Icon:$o},{id:"seam",label:"Seam",Icon:$i},{id:"edge",label:"Edge",Icon:Yo},{id:"sink",label:"Cutout",Icon:Va},{id:"beam",label:"Beam",Icon:ua},{id:"waterfall",label:"Waterfall",Icon:qi},{id:"comment",label:"Comment",Icon:Fi},{id:"slab",label:"Slab",Icon:dc}],Ac=[{id:"sink",label:"Sink"},{id:"cooktop",label:"Cooktop"},{id:"faucet",label:"Faucet"},{id:"dishwasher",label:"Dishwasher"},{id:"fireplace",label:"Fireplace"},{id:"bathtub",label:"Bathtub"}],$c=[{id:"straight",label:"Straight"},{id:"l-shape",label:"L-shape"},{id:"u-shape",label:"U-shape"},{id:"island",label:"Island"}];function Oc({drawMode:e,setDrawMode:s,addQuickShape:a,isDragging:r,onCancel:n,pieceCount:i,totalSqft:l,selectedId:u,deleteSelected:c,undo:d,redo:j,canRedo:w,canUndo:A,duplicateSelected:M,exportImage:T,clearAll:D,showGrid:Y,setShowGrid:P,helpText:h,zoom:J,onZoomIn:z,onZoomOut:B,onZoomReset:U,cutoutType:oe="sink",onCutoutTypeChange:Ne}){return t.jsxs("div",{className:"bg-slate-900 rounded-xl p-3 space-y-2.5 border border-slate-800 shadow-sm",children:[t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx("div",{className:"flex gap-0.5 bg-slate-950/60 p-1 rounded-lg border border-slate-800",children:Lc.map(({id:ue,label:je,Icon:ye})=>t.jsxs("button",{onClick:()=>s(ue),className:`flex items-center gap-1.5 px-2.5 py-1.5 rounded-md text-xs font-medium transition-colors ${e===ue?"bg-primary text-primary-foreground shadow":"text-slate-400 hover:text-white hover:bg-slate-800"}`,children:[t.jsx(ye,{className:"w-3.5 h-3.5"}),je]},ue))}),t.jsx("div",{className:"h-6 w-px bg-slate-700/80"}),t.jsx("div",{className:"flex gap-1",children:$c.map(ue=>
43t.jsx("button",{onClick:()=>a(ue.id),className:"px-2.5 py-1.5 rounded-md text-[11px] font-medium text-slate-300 bg-slate-800 hover:bg-slate-700 border border-slate-700/70 transition-colors",children:ue.label},ue.id))}),t.jsx("div",{className:"flex-1"}),u&&t.jsxs("button",{onClick:c,className:"flex items-center gap-1 text-red-400 hover:text-red-300 px-2 py-1.5 rounded-md bg-red-500/10 hover:bg-red-500/20 transition-colors text-xs font-medium",children:[t.jsx(Fs,{className:"w-3.5 h-3.5"})," Delete"]}),i>0&&t.jsxs("div",{className:"flex items-center gap-0.5",children:[t.jsx("button",{onClick:d,disabled:!A,className:"text-slate-400 hover:text-white p-1.5 rounded-md hover:bg-slate-800 transition-colors disabled:opacity-30 disabled:cursor-not-allowed",title:"Undo (Ctrl+Z)",children:t.jsx(Ro,{className:"w-3.5 h-3.5"})}),t.jsx("button",{onClick:j,disabled:!w,className:"text-slate-400 hover:text-white p-1.5 rounded-md hover:bg-slate-800 transition-colors disabled:opacity-30 disabled:cursor-not-allowed",title:"Redo (Ctrl+Shift+Z)",children:t.jsx(Io,{className:"w-3.5 h-3.5"})}),u&&t.jsx("button",{onClick:M,className:"text-slate-400 hover:text-white p-1.5 rounded-md hover:bg-slate-800 transition-colors",title:"Duplicate (Ctrl+D)",children:t.jsx(Er,{className:"w-3.5 h-3.5"})}),t.jsx("button",{onClick:T,className:"text-slate-400 hover:text-white p-1.5 rounded-md hover:bg-slate-800 transition-colors",title:"Export PNG",children:t.jsx(Si,{className:"w-3.5 h-3.5"})}),t.jsx("div",{className:"h-5 w-px bg-slate-700/80 mx-0.5"}),t.jsx("button",{onClick:D,className:"text-slate-400 hover:text-red-400 p-1.5 rounded-md hover:bg-slate-800 transition-colors",title:"Clear all",children:t.jsx(Fs,{className:"w-3.5 h-3.5"})}),t.jsx("button",{onClick:()=>P(!Y),className:`p-1.5 rounded-md hover:bg-slate-800 transition-colors ${Y?"text-primary":"text-slate-400"}`,title:"Toggle grid",children:t.jsx(Eo,{className:"w-3.5 h-3.5"})})]}),t.jsxs("div",{className:"flex items-center gap-0.5 bg-slate-950/60 p-1 rounded-lg border border-slate-800",children:[t.jsx("button",{onClick:B,className:"text-slate-400 hover:text-white p-1.5 rounded-md hover:bg-slate-800 transition-colors",title:"Zoom out",children:t.jsx(Wo,{className:"w-3.5 h-3.5"})}),t.jsxs("button",{onClick:U,className:"text-slate-400 hover:text-white px-1.5 py-1 rounded-md hover:bg-slate-800 transition-colors text-[11px] font-medium min-w-[36px] text-center",title:"Reset zoom",children:[Math.round(J*100),"%"]}),t.jsx("button",{onClick:z,className:"text-slate-400 hover:text-white p-1.5 rounded-md hover:bg-slate-800 transition-colors",title:"Zoom in",children:t.jsx(zo,{className:"w-3.5 h-3.5"})})]})]}),e==="sink"&&t.jsxs("div",{className:"flex items-center gap-1 flex-wrap pt-0.5",children:[t.jsx("span",{className:"text-[11px] text-slate-500 mr-1",children:"Type:"}),Ac.map(ue=>t.jsx("button",{onClick:()=>Ne==null?void 0:Ne(ue.id),className:`px-2 py-1 rounded text-[11px] font-medium transition-colors ${oe===ue.id?"bg-primary text-primary-foreground":"bg-slate-800 text-slate-400 hover:text-white hover:bg-slate-700"}`,children:ue.label},ue.id))]}),t.jsxs("div",{className:"flex items-center justify-between gap-3",children:[t.jsx("p",{className:"text-slate-400 text-xs leading-relaxed flex-1 min-w-0",children:h}),t.jsxs("div",{className:"flex items-center gap-2.5 shrink-0",children:[r&&t.jsxs("button",{onClick:n,className:"flex items-center gap-1 text-red-300 hover:text-red-200 px-2 py-1 rounded-md bg-red-500/15 hover:bg-red-500/25 transition-colors text-xs font-medium",children:[t.jsx(ca,{className:"w-3.5 h-3.5"})," Cancel"]}),t.jsxs("span",{className:"text-slate-400 text-xs whitespace-nowrap",children:[i," piece",i!==1?"s":""]}),l>0&&t.jsxs("span",{className:"text-primary text-xs font-semibold whitespace-nowrap",children:[l.toFixed(1)," sq ft"]})]})]})]})}function Ui(e,s,a,r,n,i){const l=n-a,u=i-r,c=l*l+u*u;if(c===0)return{dist:Math.hypot(e-a,s-r),cx:a,cy:r,t:0};let d=((e-a)*l+(s-r)*u)/c;d=Math.max(0,Math.min(1,d));const j=a+d*l,w=r+d*u;return{dist:Math.hypot(e-j,s-w),cx:j,cy:w,t:d}}function ii(e,s,a=18){let r=-1,n=a;for(let i=0;i<e.length;i++){const l=e[i],u=e[(i+1)%e.length],{dist:c}=Ui(s.x,s.y,l.x,l.y,u.x,u.y);c<n&&(n=c,r=i)}return r}function Yc(e,s,a,r,n,i,l,u){const c=a-e,d=r-s,j=l-n,w=u-i,A=c*w-d*j;if(Math.abs(A)<1e-9)return null;const M=((n-e)*w-(i-s)*j)/A,T=((n-e)*d-(i-s)*c)/A;return T<0||T>1?null:{x:e+M*c,y:s+M*d,u:T}}function li(e,s,a){const r=e.length;if(r<4)return null;const n=[];for(let D=0;D<r;D++){const Y=e[D],P=e[(D+1)%r],h=Yc(s.x,s.y,a.x,a.y,Y.x,Y.y,P.x,P.y);h&&n.push({x:h.x,y:h.y,edgeIndex:D,u:h.u})}if(n.length<2)return null;const i=D=>(D.x-s.x)*(a.x-s.x)+(D.y-s.y)*(a.y-s.y);n.sort((D,Y)=>i(D)-i(Y));const l=n[0],u=n[n.length-1],c=[],d=[];c.push({x:l.x,y:l.y});let j=(l.edgeIndex+1)%r,w=0;for(;j!==(u.edgeIndex+1)%r&&w<r;)c.push({...e[j]}),j=(j+1)%r,w++;for(c.push({x:u.x,y:u.y}),d.push({x:u.x,y:u.y}),j=(u.edgeIndex+1)%r,w=0;j!==(l.edgeIndex+1)%r&&w<r;)d.push({...e[j]}),j=(j+1)%r,w++;if(d.push({x:l.x,y:l.y}),c.length<3||d.length<3)return null;const A=D=>D.filter((Y,P)=>{if(P===0)return!0;const h=D[P-1];return Math.abs(Y.x-h.x)>.5||Math.abs(Y.y-h.y)>.5}),M=A(c),T=A(d);return M.length<3||T.length<3?null:{polyA:M,polyB:T}}function Rc(e,s,a=20){let r=null,n=a;const i=[];for(const u of e)for(const c of s){const d=c.points||[];for(const j of d){const w=Math.hypot(u.x-j.x,u.y-j.y);w<n&&(n=w,r={dx:j.x-u.x,dy:j.y-u.y},i.length=0,i.push({x1:j.x,y1:j.y,x2:j.x,y2:j.y,type:"vertex"}))}for(let j=0;j<d.length;
43j++){const w=d[j],A=d[(j+1)%d.length],{dist:M,cx:T,cy:D}=Ui(u.x,u.y,w.x,w.y,A.x,A.y);M<n&&(n=M,r={dx:T-u.x,dy:D-u.y},i.length=0,i.push({x1:u.x+r.dx,y1:u.y+r.dy,x2:T,y2:D,type:"edge"}))}}const l=u=>{const c=new Set(e.map(d=>Math.round(d[u])));for(const d of s)for(const j of d.points||[]){const w=Math.round(j[u]);for(const A of c){const M=w-A;Math.abs(M)>0&&Math.abs(M)<n&&(n=Math.abs(M),r=u==="x"?{dx:M,dy:0}:{dx:0,dy:M},i.length=0)}}};return l("x"),l("y"),r?{...r,guides:i}:null}const Nt=1200,Dt=700,_t=20,oi=35,Cs=10,_r=12,Ic=1190,Ec=550,ci={sink:{label:"Sink",w:330,h:190,shape:"rect"},cooktop:{label:"Cooktop",w:300,h:210,shape:"rect"},faucet:{label:"Faucet",w:20,h:20,shape:"circle"},dishwasher:{label:"Dishwasher",w:240,h:240,shape:"rect"},fireplace:{label:"Fireplace",w:360,h:160,shape:"rect"},bathtub:{label:"Bathtub",w:600,h:320,shape:"rect"}},Wc=240,zc=60,Uc=360,Hc=30,Bc={straight:[{x:100,y:200},{x:1100,y:200},{x:1100,y:460},{x:100,y:460}],"l-shape":[{x:100,y:100},{x:700,y:100},{x:700,y:360},{x:1100,y:360},{x:1100,y:620},{x:100,y:620}],"u-shape":[{x:100,y:100},{x:1100,y:100},{x:1100,y:620},{x:900,y:620},{x:900,y:360},{x:300,y:360},{x:300,y:620},{x:100,y:620}],island:[{x:250,y:150},{x:950,y:150},{x:950,y:550},{x:250,y:550}]};function $s(e){return Math.round(e/_t)*_t}function br(e){const s=Math.floor(e+.005),a=e-s,r=Math.round(a*16);if(r===0||r===16)return`${s+(r===16?1:0)}"`;const n=(l,u)=>u?n(u,l%u):l,i=n(r,16);return`${s} ${r/i}/${16/i}"`}function ra(e){if(!e||e.length<3)return 0;let s=0;for(let a=0;a<e.length;a++){const r=(a+1)%e.length;s+=e[a].x*e[r].y,s-=e[r].x*e[a].y}return Math.abs(s/2)/14400}function di(e){const s=e.length;if(s<3)return e;const a=[];for(let r=0;r<s;r++){const n=e[(r-1+s)%s],i=e[r],l=e[(r+1)%s];n.x===i.x&&i.x===l.x||n.y===i.y&&i.y===l.y||a.push(i)}return a.length>=3?a:e}function Ca(e,s){let a=!1;for(let r=0,n=s.length-1;r<s.length;n=r++){const i=s[r].x,l=s[r].y,u=s[n].x,c=s[n].y;l>e.y!=c>e.y&&e.x<(u-i)*(e.y-l)/(c-l)+i&&(a=!a)}return a}typeof CanvasRenderingContext2D<"u"&&!CanvasRenderingContext2D.prototype.roundRect&&(CanvasRenderingContext2D.prototype.roundRect=function(e,s,a,r,n){return typeof n=="number"&&(n=[n,n,n,n]),this.beginPath(),this.moveTo(e+n[0],s),this.arcTo(e+a,s,e+a,s+r,n[1]),this.arcTo(e+a,s+r,e,s+r,n[2]),this.arcTo(e,s+r,e,s,n[3]),this.arcTo(e,s,e+a,s,n[0]),this.closePath(),this});function Vc({countertops:e,onCountertopsChange:s,onLayoutImageChange:a,edgeProfile:r="eased",cutoutType:n="sink",onCutoutTypeChange:i}){const l=m.useRef(null),[u,c]=m.useState(!0),[d,j]=m.useState("polygon"),w=m.useRef(d);w.current=d;const A=m.useRef(!1),[M,T]=m.useState(!1),[D,Y]=m.useState(null),P=m.useRef(null);P.current=D;const h=m.useRef({path:[],lastDir:null,previewPos:null,dragMoved:!1}),J=m.useRef(null),z=m.useRef([]),B=m.useRef([]),U=m.useRef(null),[oe,Ne]=m.useState(1),ue=m.useRef(null),[je,ye]=m.useState(0),W=m.useRef(e),V=m.useRef(u),q=m.useRef(a),E=m.useRef(s),be=m.useRef(r),we=m.useRef(n);W.current=e,V.current=u,q.current=a,E.current=s,be.current=r,we.current=n;const le=m.useCallback(F=>{z.current.push(JSON.parse(JSON.stringify(W.current))),z.current.length>50&&z.current.shift(),B.current=[],E.current(F)},[]),me=m.useRef(null),De=m.useRef(null);m.useEffect(()=>{const F=document.createElement("canvas");return F.width=Nt,F.height=Dt,me.current=F,Xe(),()=>{J.current&&cancelAnimationFrame(J.current)}},[]),m.useEffect(()=>{if(!ue.current)return;const F=new ResizeObserver(o=>{ye(o[0].contentRect.width)});return F.observe(ue.current),()=>F.disconnect()},[]);const Ge=je>0?je/Nt:1,Ue=oe*Ge,nt=Nt*Ue,lt=Dt*Ue,dt=je>0?je*(Dt/Nt):500,fe=()=>Ne(F=>Math.min(4,+(F+.25).toFixed(2))),Ke=()=>Ne(F=>Math.max(.25,+(F-.25).toFixed(2))),et=()=>Ne(1),it=F=>{if(F.ctrlKey||F.metaKey){F.preventDefault();const o=F.deltaY>0?-.15:.15;Ne(_=>Math.max(.25,Math.min(4,+(_+o).toFixed(2))))}},Xe=m.useCallback(()=>{const F=me.current;if(!F)return;const o=F.getContext("2d"),_=W.current,O=V.current;if(o.clearRect(0,0,Nt,Dt),o.fillStyle="#f8fafc",o.fillRect(0,0,Nt,Dt),O){if(!De.current){const f=document.createElement("canvas");f.width=Cs*_r,f.height=Cs*_r;const I=f.getContext("2d");I.strokeStyle="#e2e8f0",I.lineWidth=.5,I.beginPath();for(let N=0;N<=_r;N++){const p=N*Cs;I.moveTo(p,0),I.lineTo(p,f.height),I.moveTo(0,p),I.lineTo(f.width,p)}I.stroke(),I.strokeStyle="#94a3b8",I.lineWidth=1,I.setLineDash([6,4]),I.strokeRect(0,0,f.width,f.height),I.setLineDash([]),De.current=f}o.fillStyle=o.createPattern(De.current,"repeat"),o.fillRect(0,0,Nt,Dt),o.font="9px sans-serif",o.fillStyle="#64748b",o.textAlign="center",o.textBaseline="top";for(let f=1;f*12<=Nt/Cs;f++)o.fillText(`${f*12}"`,f*12*Cs,2);o.textAlign="left",o.textBaseline="middle";for(let f=1;f*12<=Dt/Cs;f++)o.fillText(`${f*12}"`,2,f*12*Cs)}_.forEach((f,I)=>{if(f.type!=="slab")return;const N=f.points||[];if(N.length<4)return;o.save(),o.beginPath(),o.moveTo(N[0].x,N[0].y);for(let ie=1;ie<N.length;ie++)o.lineTo(N[ie].x,N[ie].y);o.closePath(),o.fillStyle="rgba(234, 179, 8, 0.06)",o.fill(),o.strokeStyle="#ca8a04",o.lineWidth=2,o.setLineDash([10,6]),o.stroke(),o.setLineDash([]);let p=1/0,L=-1/0,K=1/0,ae=-1/0;for(const ie of N)ie.x<p&&(p=ie.x),ie.x>L&&(L=ie.x),ie.y<K&&(K=ie.y),ie.y>ae&&(ae=ie.y);const pe=f.name||`Slab ${I+1}`;o.font="bold 13px Inter, sans-serif",o.textAlign="left",o.textBaseline="top",o.fillStyle="rgba(202, 138, 4, 0.85)",o.fillText(pe,p+8,K+8);const xe=Math.sqrt((N[1].x-N[0].x)**2+(N[1].y-N[0].y)**2)/10;o.font="bold 11px Inter, sans-serif",o.textAlign="center",o.textBaseline="middle",o.fillStyle="#92400e",o.fillText(`${xe.toFixed(0)}
43"`,(p+L)/2,K-12),o.restore()}),_.forEach((f,I)=>{if(f.type==="slab")return;const N=f.points||[];if(N.length<3)return;const p=P.current===f.id;o.save(),p&&(o.shadowColor="rgba(99, 102, 241, 0.35)",o.shadowBlur=14),o.beginPath(),o.moveTo(N[0].x,N[0].y);for(let H=1;H<N.length;H++)o.lineTo(N[H].x,N[H].y);o.closePath(),o.fillStyle=p?f.type==="beam"?"rgba(20, 184, 166, 0.25)":f.type==="waterfall"?"rgba(59, 130, 246, 0.25)":"rgba(99, 102, 241, 0.16)":f.type==="beam"?"rgba(20, 184, 166, 0.15)":f.type==="waterfall"?"rgba(59, 130, 246, 0.15)":"rgba(148, 163, 184, 0.14)",o.fill(),o.shadowBlur=0,o.lineJoin="round",o.lineCap="round";for(let H=0;H<N.length;H++){const Me=N[H],Pe=N[(H+1)%N.length],We=f.edgeProfiles&&f.edgeProfiles[String(H)];o.beginPath(),o.moveTo(Me.x,Me.y),o.lineTo(Pe.x,Pe.y),o.strokeStyle=We?"#f59e0b":f.type==="beam"?"#14b8a6":f.type==="waterfall"?"#3b82f6":p?"#6366f1":"#64748b",o.lineWidth=We?4:p?3:2,o.stroke()}if(o.restore(),p)for(const H of N)o.beginPath(),o.arc(H.x,H.y,5.5,0,Math.PI*2),o.fillStyle="#fff",o.fill(),o.strokeStyle="#6366f1",o.lineWidth=2,o.stroke();o.font="bold 12px Inter, sans-serif",o.textAlign="center",o.textBaseline="middle";for(let H=0;H<N.length;H++){const Me=N[H],Pe=N[(H+1)%N.length],We=(Me.x+Pe.x)/2,gt=(Me.y+Pe.y)/2,wt=Math.sqrt((Pe.x-Me.x)**2+(Pe.y-Me.y)**2)/10,Lt=Pe.x-Me.x,St=Pe.y-Me.y,Rt=Math.sqrt(Lt*Lt+St*St)||1,vs=-St/Rt*16,Zt=Lt/Rt*16,Ns=br(wt);o.save(),o.translate(We+vs,gt+Zt),Math.abs(St)>Math.abs(Lt)&&o.rotate(-Math.PI/2);const ks=o.measureText(Ns).width;o.fillStyle="rgba(255,255,255,0.9)",o.beginPath(),o.roundRect(-ks/2-5,-9,ks+10,18,4),o.fill(),o.fillStyle=p?"#4338ca":"#475569",o.fillText(Ns,0,0),o.restore()}if(!p)for(let H=0;H<N.length;H++){const Me=N[H],Pe=N[(H+1)%N.length],We=N[(H+2)%N.length],gt=Me.x-Pe.x,wt=Me.y-Pe.y,Lt=We.x-Pe.x,St=We.y-Pe.y;Math.abs(gt*Lt+wt*St)<1&&(o.beginPath(),o.arc(Pe.x,Pe.y,8,0,Math.PI*2),o.fillStyle="rgba(99, 102, 241, 0.12)",o.fill(),o.strokeStyle="rgba(99, 102, 241, 0.45)",o.lineWidth=1,o.stroke())}if(f.cutouts&&f.cutouts.length>0)for(const H of f.cutouts){if(H.shape==="circle"){const Pe=H.w/2,We=H.x+Pe,gt=H.y+Pe;o.save(),o.beginPath(),o.arc(We,gt,Pe,0,Math.PI*2),o.fillStyle="rgba(255, 255, 255, 0.9)",o.fill(),o.strokeStyle="#475569",o.lineWidth=2,o.setLineDash([3,2]),o.stroke(),o.setLineDash([]),o.font="bold 8px Inter, sans-serif",o.textAlign="center",o.textBaseline="middle",o.fillStyle="#475569",o.fillText(H.label||"Faucet",We,gt),o.restore();continue}o.save(),o.beginPath(),o.rect(H.x,H.y,H.w,H.h),o.fillStyle="rgba(255, 255, 255, 0.85)",o.fill(),o.beginPath(),o.rect(H.x,H.y,H.w,H.h),o.clip(),o.strokeStyle="rgba(100, 116, 139, 0.5)",o.lineWidth=1;const Me=12;for(let Pe=H.x-H.h;Pe<H.x+H.w+H.h;Pe+=Me)o.beginPath(),o.moveTo(Pe,H.y),o.lineTo(Pe+H.h,H.y+H.h),o.stroke();
43o.restore(),o.save(),o.strokeStyle="#475569",o.lineWidth=2,o.setLineDash([5,3]),o.beginPath(),o.roundRect(H.x,H.y,H.w,H.h,8),o.stroke(),o.setLineDash([]),o.font="bold 11px Inter, sans-serif",o.textAlign="center",o.textBaseline="middle",o.fillStyle="#475569",o.fillText(H.label||"Sink",H.x+H.w/2,H.y+H.h/2),o.restore()}let L=1/0,K=-1/0,ae=1/0,pe=-1/0;for(const H of N)H.x<L&&(L=H.x),H.x>K&&(K=H.x),H.y<ae&&(ae=H.y),H.y>pe&&(pe=H.y);const xe=(L+K)/2,ie=(ae+pe)/2,Ee=f.name||`Piece ${I+1}`;o.font="bold 15px Inter, sans-serif",o.textAlign="center",o.textBaseline="middle";const Ae=o.measureText(Ee).width;if(o.fillStyle="rgba(15, 23, 42, 0.05)",o.beginPath(),o.roundRect(xe-Ae/2-10,ie-12,Ae+20,24,6),o.fill(),o.fillStyle="#334155",o.fillText(Ee,xe,ie),f.hasMillDown||f.hasLamination){const H=[];f.hasMillDown&&H.push("MILL DOWN"),f.hasLamination&&H.push("LAMINATION");const Me=H.join(" + ");o.font="bold 9px Inter, sans-serif",o.textAlign="center",o.textBaseline="middle";const Pe=o.measureText(Me).width;o.fillStyle="rgba(245, 158, 11, 0.92)",o.beginPath(),o.roundRect(xe-Pe/2-7,ie+14,Pe+14,16,3),o.fill(),o.fillStyle="#fff",o.fillText(Me,xe,ie+22)}}),_.filter(f=>{var I;return f.type==="comment"&&((I=f.points)==null?void 0:I[0])}).forEach(f=>{const I=f.points[0],N=P.current===f.id;o.save(),o.beginPath(),o.arc(I.x,I.y,14,0,Math.PI*2),o.fillStyle=N?"#6366f1":"#8b5cf6",o.fill(),o.strokeStyle="#fff",o.lineWidth=2,o.stroke();const p=(f.name||"").replace("Comment ","");if(o.font="bold 11px Inter, sans-serif",o.textAlign="center",o.textBaseline="middle",o.fillStyle="#fff",o.fillText(p,I.x,I.y),f.text){const L=f.text.length>35?f.text.slice(0,35)+"…":f.text;o.font="11px Inter, sans-serif",o.textAlign="left";const K=o.measureText(L).width;o.fillStyle="rgba(139, 92, 246, 0.92)",o.beginPath(),o.roundRect(I.x+18,I.y-10,K+12,20,4),o.fill(),o.fillStyle="#fff",o.fillText(L,I.x+24,I.y)}o.restore()})},[]),pt=m.useCallback(()=>{const F=l.current,o=me.current;if(!F||!o)return;const _=F.getContext("2d");_.drawImage(o,0,0);const O=h.current;if(O.snapGuides&&O.snapGuides.length>0){_.save(),_.strokeStyle="#ff6b35",_.lineWidth=1.5,_.setLineDash([4,4]);for(const p of O.snapGuides)_.beginPath(),_.moveTo(p.x1,p.y1),_.lineTo(p.x2,p.y2),_.stroke();_.setLineDash([]);for(const p of O.snapGuides)_.beginPath(),_.arc(p.x2,p.y2,6,0,Math.PI*2),_.fillStyle="#ff6b35",_.fill();_.restore()}if(O.path.length===0)return;const f=O.path[0];if(w.current==="rect"&&O.previewPos){const p=f,L=O.previewPos,K=[{x:p.x,y:p.y},{x:L.x,y:p.y},{x:L.x,y:L.y},{x:p.x,y:L.y}];_.beginPath(),_.moveTo(K[0].x,K[0].y);for(let pe=1;pe<K.length;pe++)_.lineTo(K[pe].x,K[pe].y);_.closePath(),_.fillStyle="rgba(99, 102, 241, 0.12)",_.fill(),_.strokeStyle="#6366f1",_.lineWidth=3,_.stroke();const ae=ra(K);if(ae>.01){const pe=(p.x+L.x)/2,xe=(p.y+L.y)/2,ie=`${ae.toFixed(1)} sq ft`;_.font="bold 15px Inter, sans-serif",_.textAlign="center",_.textBaseline="middle";const Ee=_.measureText(ie).width;_.fillStyle="rgba(99, 102, 241, 0.85)",_.beginPath(),_.roundRect(pe-Ee/2-8,xe-12,Ee+16,24,6),_.fill(),_.fillStyle="#fff",_.fillText(ie,pe,xe)}return}let I=O.previewPos,N=!1;if(I&&O.path.length>=3&&Math.sqrt((I.x-f.x)**2+(I.y-f.y)**2)<oi&&(I={x:f.x,y:f.y},N=!0),I&&O.path.length>=2){_.beginPath(),_.moveTo(O.path[0].x,O.path[0].y);for(let p=1;p<O.path.length;p++)_.lineTo(O.path[p].x,O.path[p].y);_.lineTo(I.x,I.y),_.closePath(),_.fillStyle=N?"rgba(74, 156, 90, 0.18)":"rgba(99, 102, 241, 0.12)",_.fill()}_.beginPath(),_.moveTo(O.path[0].x,O.path[0].y);for(let p=1;p<O.path.length;p++)_.lineTo(O.path[p].x,O.path[p].y);I&&_.lineTo(I.x,I.y),N&&_.lineTo(f.x,f.y),_.strokeStyle=N?"#4a9c5a":"#6366f1",_.lineWidth=3,_.setLineDash(N?[]:[8,4]),_.stroke(),_.setLineDash([]),_.beginPath(),_.arc(f.x,f.y,N?12:8,0,Math.PI*2),_.fillStyle=N?"rgba(74, 156, 90, 0.3)":"rgba(99, 102, 241, 0.2)",_.fill(),_.strokeStyle=N?"#4a9c5a":"#6366f1",_.lineWidth=N?3:2,_.stroke(),N&&(_.beginPath(),_.arc(f.x,f.y,4,0,Math.PI*2),_.fillStyle="#4a9c5a",_.fill()),_.fillStyle=N?"#4a9c5a":"#6366f1";for(const p of O.path)_.beginPath(),_.arc(p.x,p.y,5,0,Math.PI*2),_.fill();_.font="bold 12px Inter, sans-serif",_.textAlign="center",_.textBaseline="middle";for(let p=0;p<O.path.length-1;p++){const L=O.path[p],K=O.path[p+1],ae=(L.x+K.x)/2,pe=(L.y+K.y)/2,xe=M
43ath.sqrt((K.x-L.x)**2+(K.y-L.y)**2)/10;if(xe<1)continue;const ie=K.x-L.x,Ee=K.y-L.y,Ae=Math.sqrt(ie*ie+Ee*Ee)||1,H=-Ee/Ae*14,Me=ie/Ae*14;_.save(),_.translate(ae+H,pe+Me),Math.abs(Ee)>Math.abs(ie)&&_.rotate(-Math.PI/2),_.fillStyle="rgba(99, 102, 241, 0.7)",_.fillText(br(xe),0,0),_.restore()}if(I){const p=O.path[O.path.length-1],L=(p.x+I.x)/2,K=(p.y+I.y)/2,ae=Math.sqrt((I.x-p.x)**2+(I.y-p.y)**2)/10;_.fillStyle=N?"#4a9c5a":"#6366f1",_.font="bold 13px Inter, sans-serif",_.textAlign="center",_.textBaseline="middle",_.fillText(br(ae),L,K-14)}if(I&&O.path.length>=2){const p=[...O.path,I],L=ra(p);if(L>.01){let K=1/0,ae=-1/0,pe=1/0,xe=-1/0;for(const Me of p)Me.x<K&&(K=Me.x),Me.x>ae&&(ae=Me.x),Me.y<pe&&(pe=Me.y),Me.y>xe&&(xe=Me.y);const ie=(K+ae)/2,Ee=(pe+xe)/2,Ae=`${L.toFixed(1)} sq ft`;_.font="bold 15px Inter, sans-serif",_.textAlign="center",_.textBaseline="middle";const H=_.measureText(Ae).width;_.fillStyle=N?"rgba(74, 156, 90, 0.9)":"rgba(99, 102, 241, 0.85)",_.beginPath(),_.roundRect(ie-H/2-8,Ee-12,H+16,24,6),_.fill(),_.fillStyle="#fff",_.fillText(Ae,ie,Ee)}}},[]),x=m.useCallback(()=>{J.current||(J.current=requestAnimationFrame(()=>{J.current=null,pt()}))},[pt]);m.useEffect(()=>{if(Xe(),x(),q.current&&me.current&&W.current.length>0)try{q.current(me.current.toDataURL("image/png"))}catch{}},[e,u,D,Xe,x]);const Q=(F,o)=>{const _=U.current;return _?{x:(F-_.left)*(Nt/_.width),y:(o-_.top)*(Dt/_.height)}:{x:0,y:0}},C=(F,o)=>{var I;const _=l.current;if(!_)return;U.current=_.getBoundingClientRect();const O=Q(F,o),f={x:$s(O.x),y:$s(O.y)};if(w.current==="seam"){for(let N=W.current.length-1;N>=0;N--){const p=W.current[N],L=p.points||[];if(L.length<4)continue;const K=ii(L,O,22);if(K>=0){const ae=L[K],pe=L[(K+1)%L.length],xe=pe.x-ae.x,ie=pe.y-ae.y,Ee=Math.sqrt(xe*xe+ie*ie)||1,Ae=Math.max(.05,Math.min(.95,((O.x-ae.x)*xe+(O.y-ae.y)*ie)/(Ee*Ee))),H=ae.x+Ae*xe,Me=ae.y+Ae*ie,Pe=-ie/Ee,We=xe/Ee,gt=H+Pe*2e3,wt=Me+We*2e3,Lt=H-Pe*2e3,St=Me-We*2e3;let Rt=li(L,{x:H,y:Me},{x:gt,y:wt});if(Rt||(Rt=li(L,{x:H,y:Me},{x:Lt,y:St})),Rt){const vs=p.name||`Piece ${N+1}`,Zt={...JSON.parse(JSON.stringify(p)),id:`ct-${Date.now()}-a`,name:`${vs} A`,points:Rt.polyA},Ns={...JSON.parse(JSON.stringify(p)),id:`ct-${Date.now()}-b`,name:`${vs} B`,points:Rt.polyB},ks=W.current.slice();ks.splice(N,1,Zt,Ns),le(ks);return}}}return}if(w.current==="slab"){const N=Ic/2,p=Ec/2,L=Math.max(N,Math.min(Nt-N,f.x)),K=Math.max(p,Math.min(Dt-p,f.y)),ae=[{x:L-N,y:K-p},{x:L+N,y:K-p},{x:L+N,y:K+p},{x:L-N,y:K+p}],pe=W.current.filter(ie=>ie.type==="slab").length+1,xe={id:`ct-${Date.now()}`,type:"slab",name:`Slab ${pe}`,points:ae};le([...W.current,xe]);return}if(w.current==="beam"){const N=Wc/2,p=zc/2,L=Math.max(N,Math.min(Nt-N,f.x)),K=Math.max(p,Math.min(Dt-p,f.y)),ae=[{x:L-N,y:K-p},{x:L+N,y:K-p},{x:L+N,y:K+p},{x:L-N,y:K+p}],pe=W.current.filter(ie=>ie.type==="beam").length+1,xe={id:`ct-${Date.now()}`,type:"beam",name:`Beam ${pe}`,points:ae};le([...W.current,xe]);return}if(w.current==="waterfall"){const N=Uc/2,p=Hc/2,L=Math.max(N,Math.min(Nt-N,f.x)),K=Math.max(p,Math.min(Dt-p,f.y)),ae=[{x:L-N,y:K-p},{x:L+N,y:K-p},{x:L+N,y:K+p},{x:L-N,y:K+p}],pe=W.current.filter(ie=>ie.type==="waterfall").length+1,xe={id:`ct-${Date.now()}`,type:"waterfall",name:`Waterfall ${pe}`,points:ae};le([...W.current,xe]);return}if(w.current==="comment"){const N=W.current.filter(L=>L.type==="comment").length+1,p={id:`ct-${Date.now()}`,type:"comment",name:`Comment ${N}`,points:[{x:f.x,y:f.y}],text:""};le([...W.current,p]),Y(p.id);return}if(w.current==="sink"){const N=ci[we.current||"sink"]||ci.sink;for(let p=W.current.length-1;p>=0;p--){const L=W.current[p];if(!(L.type==="slab"||!L.cutouts))for(let K=L.cutouts.length-1;K>=0;K--){const ae=L.cutouts[K];if(O.x>=ae.x&&O.x<=ae.x+ae.w&&O.y>=ae.y&&O.y<=ae.y+ae.h){const pe=L.cutouts.filter((ie,Ee)=>Ee!==K),xe=[...W.current];xe[p]={...L,cutouts:pe},le(xe);return}}}for(let p=W.current.length-1;p>=0;p--){const L=W.current[p];if(L.type==="slab")continue;const K=L.points||[];if(K.length<3||!Ca(f,K))continue;let ae=1/0,pe=-1/0,xe=1/0,ie=-1/0;for(const We of K)We.x<ae&&(ae=We.x),We.x>pe&&(pe=We.x),We.y<xe&&(xe=We.y),We.y>ie&&(ie=We.y);const Ee=Math.max(ae+N.w/2,Math.min(pe-N.w/2,f.x)),Ae=Math.max(xe+N.h/2,Math.min(ie-N.h/2,f.y)),H={id:`cutout-${Date.now()}`,type:we.current||"sink",shape:N.shape,x:Ee-N.w/2,y:Ae-N.h/2,w:N.w,h:N.h,label:N.label},Me=[...L.cutouts||[],H],Pe=[...W.current];Pe[p]={...L,cutouts:Me},le(Pe);return}return}if(w.current==="edge"){for(let N=W.current.length-1;N>=0;N--){const p=W.current[N],L=p.points||[];if(L.length<2)continue;const K=ii(L,O,22);if(K>=0){const ae={...p.edgeProfiles||{}},pe=String(K);ae[pe]?delete ae[pe]:ae[pe]=be.current||"eased";const xe=[...W.current];xe[N]={...p,edgeProfiles:ae},le(xe);return}}return}if(P.current&&w.current!=="seam"&&w.current!=="edge"&&w.current!=="sink"&&w.current!=="slab"&&w.current!=="beam"&&w.current!=="waterfall"&&w.current!=="comment"){const N=W.current.find(p=>p.id===P.current);if(N&&N.points)for(let p=0;p<N.points.length;p++){const L=N.points[p];if(Math.hypot(O.x-L.x,O.y-L.y)<18){z.current.push(JSON.parse(JSON.stringify(W.current))),z.current.length>50&&z.current.shift(),B.current=[],h.current={mode:"vertex",vertexPieceId:N.id,vertexIndex:p,path:[],lastDir:null,previewPos:null,dragMoved:!1},A.current=!0,T(!0),_.style.cursor="grabbing",x();return}}}for(let N=W.current.length-1;N>=0;N--){const p=W.current[N];if(p.type==="comment"&&((I=p.points)!=null&&I[0])){const L=p.points[0];if(Math.hypot(O.x-L.x,O.y-L.y)<18){Y(p.id),z.current.push(JSON.parse(JSON.stringify(W.current))),z.current.length>50&&z.current.shift(),B.current=[],h.current={mode:"move",moveId:p.id,moveLastPos:f,path:[],lastDir:null,previewPos:null,dragMoved:!1},A.current=!0,T(!0),_.style.cursor="grabbing",x();return}}}for(let N=W.current.length-1;N>=0;N--){const p=W.current[N];if(p.type==="slab"){const L=p.points||[];if(L.length<4)continue;let K=1/0,ae=-1/0,pe=1/0,xe=-1/0;for(const ie of L)ie.x<K&&(K=ie.x),ie.x>ae&&(ae=ie.x),ie.y<pe&&(pe=ie.y),ie.y>xe&&(xe=ie.y);if(O.x>=K&&O.x<=ae&&O.y>=pe&&O.y<=xe){Y(p.id),h.current={mode:"move",moveId:p.id,moveLastPos:f,path:[],lastDir:null,previewPos:null,dragMoved:!1},A.current=!0,T(!0),_.style.cursor="grabbing",x();return}continue}if(p.points&&p.points.length>=3&&Ca(f,p.points)){Y(p.id),z.current.push(JSON.parse(JSON.stringify(W.current))),z.current.length>50&&z.current.shift(),B.current=[],h.current={mode:"move",moveId:p.id,moveLastPos:f,path:[],lastDir:null,previewPos:null,dragMoved:!1},A.current=!0,T(!0),_.style.cursor="grabbing",x();return}}h.current={mode:"draw",path:[f],lastDir:null,previewPos:null,dragMoved:!1},A.current=!0,T(!0),x()},ne=(F,o)=>
43{if(!A.current)return;const _=Q(F,o),O={x:$s(_.x),y:$s(_.y)},f=h.current;if(f.mode==="move"){let L=O.x-f.moveLastPos.x,K=O.y-f.moveLastPos.y;if(L===0&&K===0)return;f.dragMoved=!0,f.moveLastPos=O;const ae=W.current.find(Ae=>Ae.id===f.moveId);if(!ae)return;const pe=ae.points.map(Ae=>({x:Ae.x+L,y:Ae.y+K})),xe=W.current.filter(Ae=>Ae.id!==f.moveId),ie=Rc(pe,xe,22);f.snapGuides=null,ie&&(L+=ie.dx,K+=ie.dy,f.snapGuides=ie.guides||[]);const Ee=W.current.map(Ae=>Ae.id===f.moveId?{...Ae,points:Ae.points.map(H=>({x:H.x+L,y:H.y+K})),cutouts:(Ae.cutouts||[]).map(H=>({...H,x:H.x+L,y:H.y+K}))}:Ae);E.current(Ee);return}if(f.mode==="vertex"){if(!W.current.find(ae=>ae.id===f.vertexPieceId))return;const K=W.current.map(ae=>ae.id===f.vertexPieceId?{...ae,points:ae.points.map((pe,xe)=>xe===f.vertexIndex?{x:O.x,y:O.y}:pe)}:ae);E.current(K);return}if(w.current==="rect"){const L=f.path[0];if(Math.abs(O.x-L.x)<_t/2&&Math.abs(O.y-L.y)<_t/2)return;f.dragMoved=!0,f.previewPos=O,x();return}if(w.current==="angle"){const L=f.path[f.path.length-1],K=O.x-L.x,ae=O.y-L.y;if(Math.abs(K)<_t/2&&Math.abs(ae)<_t/2)return;f.dragMoved=!0;const pe=Math.atan2(ae,K),xe=Math.round(pe/(Math.PI/4))*(Math.PI/4),ie=Math.sqrt(K*K+ae*ae),Ee=Math.round(xe/(Math.PI/4)),Ae={x:L.x+Math.cos(xe)*ie,y:L.y+Math.sin(xe)*ie};if(f.lastDir!==null&&Ee!==f.lastDir){f.path.push(f.previewPos),f.lastDir=Ee;const H=f.path[f.path.length-1],Me=O.x-H.x,Pe=O.y-H.y,We=Math.sqrt(Me*Me+Pe*Pe),gt=Math.atan2(Pe,Me),wt=Math.round(gt/(Math.PI/4))*(Math.PI/4);f.previewPos={x:H.x+Math.cos(wt)*We,y:H.y+Math.sin(wt)*We},f.lastDir=Math.round(wt/(Math.PI/4))}else f.lastDir=Ee,f.previewPos=Ae;x();return}const I=f.path[f.path.length-1],N=O.x-I.x,p=O.y-I.y;Math.abs(N)<_t/2&&Math.abs(p)<_t/2||(f.dragMoved=!0,f.lastDir===null?Math.abs(N)>=Math.abs(p)?(f.lastDir="h",f.previewPos={x:O.x,y:I.y}):(f.lastDir="v",f.previewPos={x:I.x,y:O.y}):f.lastDir==="h"?Math.abs(p)>Math.abs(N)&&Math.abs(p)>_t/2?(f.path.push(f.previewPos),f.lastDir="v",f.previewPos={x:f.previewPos.x,y:O.y}):f.previewPos={x:O.x,y:I.y}:Math.abs(N)>Math.abs(p)&&Math.abs(N)>_t/2?(f.path.push(f.previewPos),f.lastDir="h",f.previewPos={x:O.x,y:f.previewPos.y}):f.previewPos={x:I.x,y:O.y},x())},ce=()=>{var O;if(!A.current)return;A.current=!1,T(!1),U.current=null;const F=h.current;if(F.mode==="move"||F.mode==="vertex"){h.current={mode:null,path:[],lastDir:null,previewPos:null,dragMoved:!1},l.current&&(l.current.style.cursor="crosshair"),x();return}if(!F.dragMoved){const f=F.path[0];let I=null;for(let N=W.current.length-1;N>=0;N--){const p=W.current[N];if(p.type==="comment"&&((O=p.points)!=null&&O[0])){const L=p.points[0];if(Math.hypot(f.x-L.x,f.y-L.y)<18){I=p.id;break}}}if(!I){for(let N=W.current.length-1;N>=0;N--)if(Ca(f,W.current[N].points||[])){I=W.current[N].id;break}}Y(I),h.current={path:[],lastDir:null,previewPos:null,dragMoved:!1},x();return}if(w.current==="rect"&&F.previewPos){const f=F.path[0],I=F.previewPos,N=[{x:f.x,y:f.y},{x:I.x,y:f.y},{x:I.x,y:I.y},{x:f.x,y:I.y}],p=di(N);if(p.length>=3&&ra(p)>.1){const L={id:`ct-${Date.now()}`,type:"countertop",name:`Piece ${W.current.length+1}`,points:p,edgeProfiles:{},backsplash:{},backsplashHeight:{},cornerRadii:{},seams:[],material:"",globalEdgeProfile:"eased",globalBacksplash:!1,globalBacksplashHeight:4};le([...W.current,L])}h.current={path:[],lastDir:null,previewPos:null,dragMoved:!1},x();return}let o=F.path.map(f=>({x:f.x,y:f.y}));if(F.previewPos){const f=F.previewPos,I=o[o.length-1];(f.x!==I.x||f.y!==I.y)&&o.push({x:f.x,y:f.y})}o=o.filter((f,I)=>I===0||f.x!==o[I-1].x||f.y!==o[I-1].y);const _=o[0];if(o.length>=4){const f=o[o.length-1];Math.sqrt((f.x-_.x)**2+(f.y-_.y)**2)<oi&&(o=o.slice(0,-1))}if(o.length>=3){const f=di(o);if(f.length>=3&&ra(f)>.1){const I={id:`ct-${Date.now()}`,type:"countertop",name:`Piece ${W.current.length+1}`,points:f,edgeProfiles:{},backsplash:{},backsplashHeight:{},cornerRadii:{},seams:[],material:"",globalEdgeProfile:"eased",globalBacksplash:!1,globalBacksplashHeight:4};le([...W.current,I])}}h.current={path:[],lastDir:null,previewPos:null},x()},te=F=>{const o=Bc[F];if(!o)return;const _={id:`ct-${Date.now()}`,type:"countertop",name:`Piece ${W.current.length+1}`,points:o.map(O=>({...O})),edgeProfiles:{},backsplash:{},backsplashHeight:{},cornerRadii:{},seams:[],material:"",globalEdgeProfile:"eased",globalBacksplash:!1,globalBacksplashHeight:4};le([...W.current,_])},Ce=()=>{if(z.current.length===0)return;const F=z.current.pop();B.current.push(JSON.parse(JSON.stringify(W.current))),Y(null),E.current(F)},Oe=()=>{if(B.current.length===0)return;const F=B.current.pop();z.current.push(JSON.parse(JSON.stringify(W.current))),Y(null),E.current(F)},b=()=>{Y(null),le([])},tt=()=>{D&&(le(W.current.filter(F=>F.id!==D)),Y(null))},ms=()=>
43{if(!D)return;const F=W.current.find(_=>_.id===D);if(!F)return;const o={...JSON.parse(JSON.stringify(F)),id:`ct-${Date.now()}`,name:`${F.name||"Piece"} copy`,points:F.points.map(_=>({x:_.x+40,y:_.y+40})),cutouts:(F.cutouts||[]).map(_=>({..._,id:`cutout-${Date.now()}-${Math.random()}`}))};le([...W.current,o]),Y(o.id)},ws=()=>{if(!me.current)return;const F=document.createElement("a");F.download=`countertop-layout-${Date.now()}.png`,F.href=me.current.toDataURL("image/png"),F.click()},ee=F=>{F.preventDefault(),F.currentTarget.setPointerCapture(F.pointerId),C(F.clientX,F.clientY)},k=F=>{if(A.current)F.preventDefault(),ne(F.clientX,F.clientY);else{const o=l.current;if(!o)return;U.current||(U.current=o.getBoundingClientRect());const _=Q(F.clientX,F.clientY),O={x:$s(_.x),y:$s(_.y)};let f=!1;for(let L=W.current.length-1;L>=0;L--)if(Ca(O,W.current[L].points||[])){f=!0;break}const I=w.current;let N=!1;if(P.current&&I!=="seam"&&I!=="edge"&&I!=="sink"&&I!=="slab"&&I!=="beam"&&I!=="waterfall"&&I!=="comment"){const L=W.current.find(K=>K.id===P.current);if(L&&L.points){for(const K of L.points)if(Math.hypot(_.x-K.x,_.y-K.y)<18){N=!0;break}}}const p=N?"grab":I==="edge"||I==="sink"||I==="slab"||I==="beam"||I==="waterfall"||I==="comment"?"pointer":I==="seam"||I==="angle"?"crosshair":f?"grab":"crosshair";o.style.cursor=p}},Z=F=>{F.preventDefault(),ce()};m.useEffect(()=>{const F=o=>{var O;if(o.key==="Escape"){if(!A.current)return;o.preventDefault(),A.current=!1,T(!1),U.current=null,h.current={mode:null,path:[],lastDir:null,previewPos:null},l.current&&(l.current.style.cursor="crosshair"),x();return}if(o.key==="Enter"&&A.current){const f=h.current;if(f.mode==="draw"&&f.path.length>=2){o.preventDefault(),ce();return}}const _=(O=o.target)==null?void 0:O.tagName;if(!(_==="INPUT"||_==="TEXTAREA"||_==="SELECT")){if((o.ctrlKey||o.metaKey)&&!o.shiftKey&&o.key.toLowerCase()==="z"){if(o.preventDefault(),A.current)return;Ce();return}if((o.ctrlKey||o.metaKey)&&o.shiftKey&&o.key.toLowerCase()==="z"||(o.ctrlKey||o.metaKey)&&o.key.toLowerCase()==="y"){if(o.preventDefault(),A.current)return;Oe();return}if((o.ctrlKey||o.metaKey)&&o.key.toLowerCase()==="d"){o.preventDefault(),ms();return}if((o.key==="Delete"||o.key==="Backspace")&&P.current){o.preventDefault(),tt();return}if(P.current&&!A.current){const I={ArrowLeft:[-_t,0],ArrowRight:[_t,0],ArrowUp:[0,-_t],ArrowDown:[0,_t]}[o.key];if(I){o.preventDefault();const N=W.current.map(p=>p.id===P.current?{...p,points:p.points.map(L=>({x:L.x+I[0],y:L.y+I[1]})),cutouts:(p.cutouts||[]).map(L=>({...L,x:L.x+I[0],y:L.y+I[1]}))}:p);le(N);return}}}};return window.addEventListener("keydown",F),()=>window.removeEventListener("keydown",F)},[x]);const _e=e.filter(F=>F.type!=="slab"&&F.type!=="comment").reduce((F,o)=>{let _=ra(o.points);if(o.cutouts)for(const O of o.cutouts)_-=O.w*O.h/14400;return F+Math.max(0,_)},0),Se=d==="rect"?"Rectangle: drag corner-to-corner. Drag vertices to reshape · tap dimensions to edit · Enter closes.":d==="seam"?"Seam: click any edge to split a piece into two. Drag pieces to move & snap.":d==="edge"?"Edge: click any edge to toggle a finished edge profile. Amber = finished edge. Linear feet auto-calculated.":d==="angle"?"Angle: drag to trace — segments snap to 45° for diagonal cuts & miters. Enter to close · drag vertices to reshape.":d==="sink"?"Cutout: click inside a piece to place a cutout (select type below). Click an existing cutout to remove it.":d==="beam"?'Beam: click to place a 24" support beam/footing. Drag to reposition.':d==="waterfall"?"Waterfall: click to place a vertical waterfall panel. Drag next to a countertop edge.":d==="comment"?"Comment: click anywhere to drop a numbered pin. Select it to type your note in the properties panel.":d==="slab"?'Slab: click to place a 119"×55" slab reference. Drag slabs to reposition · drag pieces onto slabs for nesting.':"Free Draw: drag to trace — segments lock to 90°. Enter to close · drag vertices to reshape · drag pieces to move & snap.";return t.jsxs("div",{className:"flex flex-col gap-3",children:[t.jsxs("div",{ref:ue,onWheel:it,className:"relative rounded-xl overflow-auto border-2 border-slate-300 bg-slate-100 flex shadow-inner",style:{height:`${dt}px`,maxHeight:"70vh"},children:[t.jsx("canvas",{ref:l,width:Nt,height:Dt,onPointerDown:ee,onPointerMove:k,onPointerUp:Z,onPointerCancel:Z,style:{width:`${nt}px`,height:`${lt}px`,margin:"auto",flexShrink:0,touchAction:"none",cursor:"crosshair",display:"block"}}),D&&!M&&(()=>{const F=e.find(o=>o.id===D);return F?t.jsxs(t.Fragment,{children:[t.jsx(Dc,{piece:F,canvasRef:l,onDimensionChange:(o,_)=>{const O=e.map(f=>f.id===D?{...f,points:Mc(f.points,o,_)}:f);le(O)}}),d!=="seam"&&t.jsx(Fc,{piece:F,canvasRef:l,onRotate:o=>{const _=e.map(O=>O.id===D?{...O,points:Oo(O.points,o)}:O);le(_)}})]}):null})(),e.length===0&&!M&&t.jsx("div",{className:"absolute inset-0 flex items-center justify-center pointer-events-none",children:t.jsxs("div",{className:"text-center px-4",children:[t.jsx(Uo,{className:"w-10 h-10 text-muted-foreground
43/40 mx-auto mb-2"}),t.jsx("p",{className:"text-sm text-muted-foreground",children:d==="rect"?"Drag corner-to-corner to draw a rectangle":d==="seam"?"Draw a piece first, then use the seam tool to split it":d==="edge"?"Draw a piece first, then use the edge tool to select finished edges":d==="angle"?"Drag to trace — segments snap to 45° for diagonal cuts":d==="sink"?"Draw a piece first, then click inside it to place a cutout":d==="beam"?"Click anywhere to place a structural support beam":d==="waterfall"?"Click anywhere to place a waterfall panel":d==="comment"?"Click anywhere to drop a comment pin":d==="slab"?"Click anywhere to place a standard material slab":"Drag to trace — 90° corners, straight lines"}),t.jsx("p",{className:"text-xs text-muted-foreground/60 mt-1",children:"Esc cancels · Enter closes · Delete removes · drag vertices to reshape · or pick a shape below"})]})})]}),t.jsx(Oc,{drawMode:d,setDrawMode:j,addQuickShape:te,isDragging:M,zoom:oe,onZoomIn:fe,onZoomOut:Ke,onZoomReset:et,onCancel:()=>{A.current=!1,T(!1),U.current=null,h.current={mode:null,path:[],lastDir:null,previewPos:null},l.current&&(l.current.style.cursor="crosshair"),x()},pieceCount:e.filter(F=>F.type!=="slab"&&F.type!=="comment").length,totalSqft:_e,selectedId:D,deleteSelected:tt,undo:Ce,redo:Oe,canRedo:B.current.length>0,canUndo:z.current.length>0,duplicateSelected:ms,exportImage:ws,clearAll:b,showGrid:u,setShowGrid:c,helpText:Se,cutoutType:n,onCutoutTypeChange:i})]})}const Gc=[{value:"eased",label:"Eased (Standard)"},{value:"bevel",label:"Bevel"},{value:"bullnose",label:"Bullnose"},{value:"ogee",label:"Ogee (Premium)"},{value:"mitered",label:"Mitered"}],Kc=["granite","quartz","marble","quartzite","soapstone","laminate","butcher_block"];function Zc(e){if(!e||e.length<3)return 0;let s=0;for(let a=0;a<e.length;a++){const r=(a+1)%e.length;s+=e[a].x*e[r].y,s-=e[r].x*e[a].y}return Math.abs(s/2)/14400}function jr(e,s){if(!e||e.length<2)return 0;const a=s&&Object.keys(s).length>0;let r=0;for(let n=0;n<e.length;n++){if(a&&!s[String(n)])continue;const i=e[n],l=e[(n+1)%e.length];r+=Math.sqrt(Math.pow(l.x-i.x,2)+Math.pow(l.y-i.y,2))/10}return r/12}function wr(e){if(!e||e.type==="slab")return 0;let s=Zc(e.points);if(e.cutouts&&e.cutouts.length>0)for(const a of e.cutouts)s-=a.w*a.h/14400;return Math.max(0,s)}function Xc({allMaterials:e=[],onLineItemsChange:s,onLayoutImageChange:a,pricingConfig:r={}}){const[n,i]=m.useState([]),[l,u]=m.useState("quartz"),[c,d]=m.useState(""),[j,w]=m.useState("eased"),[A,M]=m.useState(""),[T,D]=m.useState("sink"),Y=m.useMemo(()=>{let V=e.filter(q=>q.material_type===l&&q.material_name);if(A){const q=A.toLowerCase();V=V.filter(E=>{var be,we,le;return((be=E.material_name)==null?void 0:be.toLowerCase().includes(q))||((we=E.color)==null?void 0:we.toLowerCase().includes(q))||((le=E.supplier)==null?void 0:le.toLowerCase().includes(q))})}return V},[e,l,A]),P=e.find(V=>V.material_name===c),h=n.filter(V=>V.type!=="slab"&&V.type!=="comment");n.filter(V=>V.type==="slab").length;const J=n.filter(V=>V.type==="beam").length,z=n.filter(V=>V.type==="waterfall").length,B=h.filter(V=>V.hasLamination).length,U=h.filter(V=>V.hasMillDown).length,oe=n.filter(V=>V.type==="comment").length,Ne=h.reduce((V,q)=>{var E;return V+(((E=q.cutouts)==null?void 0:E.length)||0)},0),ue=h.reduce((V,q)=>V+wr(q),0),je=h.reduce((V,q)=>V+jr(q.points,q.edgeProfiles),0);ue*((P==null?void 0:P.selling_price_per_sqft)||0);const ye=m.useMemo(()=>{if(!P||ue<=0)return{total:0,material:0,edges:0,sinks:0,buildUp:0,cost:0,margin:0};const V=r||{},q=V.minimum_sqft||0,E=P.selling_price_per_sqft||0,be=P.cost_per_sqft||0;let we=0,le=0,me=0,De=0,Ge=0,Ue=0;for(const fe of h){const Ke=Math.max(wr(fe),q),et=jr(fe.points,fe.edgeProfiles),it=fe.cutouts||[];for(const Xe of it)Xe.type==="sink"?me+=V.sink_cutout_flat_fee||0:Xe.type==="cooktop"?me+=V.cooktop_cutout_flat_fee||0:me+=V.generic_cutout_flat_fee||0;fe.hasMillDown&&(Ue+=et*(V.mitered_edge_rate_per_sqft||0)),fe.hasLamination&&(Ue+=Ke*(V.mitered_edge_rate_per_sqft||0)),we+=E*Ke,le+=et*(V.finished_edge_rate_per_linear_ft||0),De+=(V.labor_rate_per_sqft||0)*Ke,Ge+=be*Ke}const nt=we+le+me+Ue,lt=Ge+De+le+me+Ue,dt=nt>0?(nt-lt)/nt*100:0;return{total:nt,material:we,edges:le,sinks:me,buildUp:Ue,cost:lt,margin:dt}},[h,P,r,ue]),W=m.useRef("");return m.useEffect(()=>{if(!P||ue<=0)return;const V=h.map((E,be)=>{const we=E.cutouts||[],le=we.some(De=>De.type==="sink")?"undermount":we.some(De=>De.type==="cooktop")?"cooktop":"none",me=we.some(De=>De.type==="cooktop");return{...ga,name:P.material_name,area_name:E.name||`Piece ${be+1}`,sqft:wr(E).toFixed(2),material_name:P.material_name,material_type:P.material_type,color:P.color||"",unit_price_per_sqft:P.selling_price_per_sqft||0,edge_profile:j,edge_linear_ft:parseFloat(jr(E.points,E.edgeProfiles).toFixed(2)),sink_type:le,cooktop_included:me,markup_pct:0,notes:[we.length>0?`Cutouts: ${we.map(De=>De.label||De.type).join(", ")}`:"",E.hasMillDown?"Mill Down":"",E.hasLamination?"Lamination":""].filter(
43Boolean).join(" · ")}}),q=JSON.stringify(V);if(q!==W.current){W.current=q;const E=setTimeout(()=>s(V),200);return()=>clearTimeout(E)}},[n,P,j,ue,s]),t.jsxs("div",{className:"rounded-lg border border-primary/30 bg-primary/5 p-3 space-y-3",children:[t.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-semibold text-primary",children:[t.jsx(Oi,{className:"w-3.5 h-3.5"}),"Live Draw-to-Quote — pieces you draw become line items instantly"]}),t.jsxs("div",{className:"flex flex-wrap items-end gap-2",children:[t.jsxs("div",{className:"min-w-[110px]",children:[t.jsx(Ze,{className:"text-[11px]",children:"Type"}),t.jsxs(Wt,{value:l,onValueChange:V=>{u(V),d("")},children:[t.jsx(zt,{className:"h-8 text-xs",children:t.jsx(Ut,{})}),t.jsx(Ht,{children:Kc.map(V=>t.jsx(Ye,{value:V,className:"capitalize",children:V.replace("_"," ")},V))})]})]}),t.jsxs("div",{className:"flex-1 min-w-[160px]",children:[t.jsx(Ze,{className:"text-[11px]",children:"Material"}),t.jsxs("div",{className:"relative",children:[t.jsx(Yr,{className:"absolute left-2 top-1/2 -translate-y-1/2 w-3 h-3 text-muted-foreground"}),t.jsx(He,{value:A,onChange:V=>M(V.target.value),placeholder:"Search material…",className:"h-8 pl-7 text-xs"})]})]}),t.jsxs("div",{className:"min-w-[110px]",children:[t.jsx(Ze,{className:"text-[11px]",children:"Edge"}),t.jsxs(Wt,{value:j,onValueChange:w,children:[t.jsx(zt,{className:"h-8 text-xs",children:t.jsx(Ut,{})}),t.jsx(Ht,{children:Gc.map(V=>t.jsx(Ye,{value:V.value,children:V.label},V.value))})]})]})]}),A&&t.jsx("div",{className:"max-h-32 overflow-y-auto rounded-md border divide-y bg-background",children:Y.length===0?t.jsx("p",{className:"p-2 text-xs text-muted-foreground text-center",children:"No materials found."}):Y.slice(0,8).map(V=>{var q;return t.jsxs("button",{type:"button",onClick:()=>{d(V.material_name),M("")},className:`w-full flex items-center justify-between px-2 py-1.5 text-left text-xs hover:bg-accent ${c===V.material_name?"bg-primary/10":""}`,children:[t.jsx("span",{className:"font-medium truncate",children:V.material_name}),t.jsxs("span",{className:"text-primary font-semibold ml-2",children:["$",((q=V.selling_price_per_sqft)==null?void 0:q.toFixed(0))||0,"/sf"]})]},V.id)})}),P&&t.jsxs("div",{className:"text-[11px] text-muted-foreground flex items-center justify-between rounded bg-muted/60 px-2 py-1",children:[t.jsxs("span",{children:["Selected: ",t.jsx("span",{className:"font-medium text-foreground",children:P.material_name})]}),t.jsxs("span",{className:"font-semibold text-primary",children:["$",(P.selling_price_per_sqft||0).toFixed(2),"/sf"]})]}),t.jsx("div",{className:"rounded-md border overflow-hidden bg-slate-50 dark:bg-slate-900",children:t.jsx(Vc,{countertops:n,onCountertopsChange:i,onLayoutImageChange:a,edgeProfile:j,cutoutType:T,onCutoutTypeChange:D})}),t.jsxs("div",{className:"grid grid-cols-5 gap-2",children:[t.jsxs("div",{className:"rounded-lg bg-muted/60 p-2 text-center",children:[t.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Pieces"}),t.jsx("p",{className:"text-lg font-bold",children:h.length})]}),t.jsxs("div",{className:"rounded-lg bg-muted/60 p-2 text-center",children:[t.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Sqft"}),t.jsx("p",{className:"text-lg font-bold text-primary",children:ue.toFixed(1)})]}),t.jsxs("div",{className:"rounded-lg bg-muted/60 p-2 text-center",children:[t.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Edge (lf)"}),t.jsx("p",{className:"text-lg font-bold text-amber-600",children:je.toFixed(0)})]}),t.jsxs("div",{className:"rounded-lg bg-muted/60 p-2 text-center",children:[t.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Sinks"}),t.jsx("p",{className:"text-lg font-bold text-blue-600",children:Ne})]}),t.jsxs("div",{className:"rounded-lg bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 p-2 text-center",children:[t.jsx("p",{className:"text-[10px] text-green-700 dark:text-green-400",children:"Live Total"}),t.jsxs("p",{className:"text-lg font-bold text-green-700 dark:text-green-400",children:["$",ye.total>
430?ye.total.toLocaleString(void 0,{maximumFractionDigits:0}):"—"]})]})]}),ye.total>0&&t.jsxs("div",{className:"flex flex-wrap items-center gap-x-3 gap-y-0.5 text-[10px] text-muted-foreground px-1",children:[t.jsxs("span",{children:["Material $",ye.material.toFixed(0)]}),t.jsx("span",{className:"text-muted-foreground/30",children:"•"}),t.jsxs("span",{children:["Edges $",ye.edges.toFixed(0)]}),t.jsx("span",{className:"text-muted-foreground/30",children:"•"}),t.jsxs("span",{children:["Sinks $",ye.sinks.toFixed(0)]}),ye.buildUp>0&&t.jsxs(t.Fragment,{children:[t.jsx("span",{className:"text-muted-foreground/30",children:"•"}),t.jsxs("span",{children:["Build-Up $",ye.buildUp.toFixed(0)]})]}),t.jsx("span",{className:"text-muted-foreground/30",children:"•"}),t.jsxs("span",{className:ye.margin<20?"text-red-500 font-medium":"text-green-600 font-medium",children:["Margin ",ye.margin.toFixed(0),"%"]})]}),(J>0||z>0||B>0||U>0||oe>0)&&t.jsxs("div",{className:"flex gap-3 text-[10px] text-muted-foreground px-1 flex-wrap",children:[J>0&&t.jsxs("span",{className:"text-teal-600",children:["● Beams: ",J]}),z>0&&t.jsxs("span",{className:"text-blue-600",children:["● Waterfalls: ",z]}),U>0&&t.jsxs("span",{className:"text-amber-600",children:["● Mill Down: ",U]}),B>0&&t.jsxs("span",{className:"text-orange-600",children:["● Lamination: ",B]}),oe>0&&t.jsxs("span",{className:"text-purple-600",children:["● Comments: ",oe]})]}),!P&&h.length>0&&t.jsx("p",{className:"text-[11px] text-amber-600 text-center",children:"Select a material to generate line items from your drawing."})]})}const Jc=55,Qc=.78;function ed(e,s,a){if(a&&/^#[0-9A-Fa-f]{6}$/.test(a))return a;const r=(e||"").toLowerCase();return r.includes("black")||r.includes("negro")||r.includes("galaxy")?"#1a1a1a":r.includes("white")||r.includes("bianco")||r.includes("blanco")?"#ededed":r.includes("calacatta")||r.includes("carrara")?"#e0e0e0":r.includes("gold")||r.includes("oro")?"#c8a96a":r.includes("green")||r.includes("verde")?"#4a6b4a":r.includes("blue")||r.includes("azul")?"#3a5a7a":r.includes("red")||r.includes("rosso")?"#8a3a3a":r.includes("brown")||r.includes("marron")||r.includes("walnut")?"#5a3a1a":s==="granite"?"#8a8a8a":s==="marble"?"#e0e0e0":s==="quartzite"?"#b0b0b0":s==="soapstone"?"#2a2a2a":"#a0a0a0"}function td({totalSqft:e,materialName:s,slabSizeSqft:a,slabColor:r,materialType:n,colorField:i,costPerSqft:l}){const[u,c]=m.useState(null),[d,j]=m.useState(!1),w=a>0?a:Jc,A=r||ed(s,n,i),M=m.useMemo(()=>{const J=w*Qc,z=Math.max(1,Math.ceil(e/J)),B=z*w,U=Math.max(0,B-e),oe=B>0?U/B*100:0,Ne=(l||0)*B;return{slabsNeeded:z,wastePct:oe,usedPct:100-oe,slabCost:Ne}},[e,w,l]),T=async()=>{if(!e||e<=0){$.error("Add pieces to the quote first");return}j(!0);try{const J=Math.sqrt(w*144),z=await ge.functions.invoke("aiNestSlabs",{pieces:[{sqft:e,material_name:s||"default"}],slab_length:Math.round(J),slab_width:Math.round(J)});c(z.data),$.success("AI nesting complete!")}catch{$.error("AI nesting unavailable — showing estimate")}finally{j(!1)}};if(!e||e<=0)return null;const D=(u==null?void 0:u.slabs_used)||M.slabsNeeded,Y=(u==null?void 0:u.waste_pct)??M.wastePct,P=Math.max(0,100-Y),h=D*w*(l||0);return t.jsxs("div",{className:"rounded-xl border border-slate-200 bg-white p-4 shadow-sm dark:bg-slate-900 dark:border-slate-700",children:[t.jsxs("div",{className:"flex items-center justify-between mb-3",children:[t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx(si,{className:"w-4 h-4 text-blue-600"}),t.jsx("span",{className:"text-sm font-bold text-slate-800 dark:text-slate-200",children:"Live Nesting Preview"})]}),t.jsx(X,{variant:"ghost",size:"sm",className:"h-6 text-[10px]",onClick:T,disabled:d,children:d?t.jsxs(t.Fragment,{children:[t.jsx(Bt,{className:"w-3 h-3 animate-spin"})," Nesting…"]}):t.jsxs(t.Fragment,{children:[t.jsx($i,{className:"w-3 h-3"})," AI Nest"]})})]}),t.jsxs("div",{className:"relative rounded-lg overflow-hidden border-2 border-slate-300 dark:border-slate-600 mb-3",style:{height:"48px"},children:[t.jsx("div",{className:"absolute inset-0",style:{background:`linear-gradient(90deg, ${A}, ${A}cc)`},children:t.jsx("div",{className:"absolute inset-0 opacity-25",style:{backgroundImage:"repeating-linear-gradient(90deg, transparent, transparent 10
43px, rgba(255,255,255,0.15) 10px, rgba(255,255,255,0.15) 20px)"}})}),t.jsx("div",{className:"absolute top-0 bottom-0 left-0 bg-gradient-to-r from-blue-500/50 to-blue-400/30 border-r-2 border-blue-600 transition-all",style:{width:`${P}%`}}),t.jsxs("div",{className:"absolute inset-0 flex items-center justify-between px-2",children:[t.jsxs("span",{className:"text-[9px] font-bold text-blue-700 dark:text-blue-200",children:["USED ",P.toFixed(0),"%"]}),t.jsxs("span",{className:"text-[9px] font-bold text-slate-600 dark:text-slate-300",children:["WASTE ",Y.toFixed(0),"%"]})]})]}),t.jsxs("div",{className:"flex gap-2",children:[t.jsxs("div",{className:"inline-flex items-center gap-1.5 bg-blue-600 text-white rounded-lg px-2.5 py-1 shadow-sm",children:[t.jsx(si,{className:"w-3 h-3"}),t.jsx("span",{className:"text-xs font-bold",children:D}),t.jsx("span",{className:"text-[9px] opacity-90",children:"slabs"})]}),t.jsxs("div",{className:"inline-flex items-center gap-1.5 bg-amber-500 text-white rounded-lg px-2.5 py-1 shadow-sm",children:[t.jsxs("span",{className:"text-xs font-bold",children:[Y.toFixed(0),"%"]}),t.jsx("span",{className:"text-[9px] opacity-90",children:"waste"})]}),t.jsxs("div",{className:"inline-flex items-center gap-1.5 bg-slate-600 text-white rounded-lg px-2.5 py-1 shadow-sm ml-auto",children:[t.jsx("span",{className:"text-xs font-bold",children:w.toFixed(0)}),t.jsx("span",{className:"text-[9px] opacity-90",children:"sqft"})]}),h>0&&t.jsxs("div",{className:"inline-flex items-center gap-1.5 bg-green-600 text-white rounded-lg px-2.5 py-1 shadow-sm",children:[t.jsxs("span",{className:"text-xs font-bold",children:["$",h.toLocaleString(void 0,{minimumFractionDigits:0,maximumFractionDigits:0})]}),t.jsx("span",{className:"text-[9px] opacity-90",children:"slab cost"})]})]}),s&&t.jsxs("p",{className:"text-[10px] text-muted-foreground mt-2 text-center truncate",children:[e.toFixed(1)," sqft · ",s]})]})}function sd({onLineItemsAdd:e,allMaterials:s=[]}){const[a,r]=m.useState(!1),n=m.useRef(null),i=async l=>{var c;const u=(c=l.target.files)==null?void 0:c[0];if(u){r(!0);try{const{file_url:d}=await ge.integrations.Core.UploadFile({file:u}),j=await ge.integrations.Core.InvokeLLM({prompt:`You are a professional stone countertop estimator. Analyze this document — it may be a cabinet layout plan (PDF from a kitchen designer), a hand-drawn sketch, or a photo of a countertop space.
44
45YOUR JOB: Identify every distinct countertop section/run shown and calculate the square footage for each.
46
47MEASUREMENT RULES:
48- Wall runs (base cabinets against a wall): counter depth = 25.5" (24" cabinet + 1.5" overhang). sqft = length_inches × 25.5 / 144
49- Island countertops: full length × width. sqft = length × width / 144
50- Peninsula: treat as a run, note it in area_name.
51- If dimensions are in feet, convert: sqft = length_ft × depth_ft.
52- If the plan shows cabinet labels (e.g. "B36" = 36" base, "W24" = 24" wide), use the stated width as that section's length.
53- Vanity tops (bathrooms): depth typically 22". sqft = length × 22 / 144.
54- Standard height is 36" — height does not affect sqft unless it's a full-height splash.
55- L-shaped or U-shaped runs: return ONE item with shape "l_shape"/"u_shape" and the total combined sqft.
56
57CUTOUTS: Detect sink cutouts, cooktop cutouts, and faucet holes. List each with type and a short description.
58
59CONFIDENCE:
60- "high": printed/typed dimensions on a cabinet plan PDF, or clear labeled measurements.
61- "medium": legible handwritten dimensions, or dimensions inferred from cabinet labels.
62- "low": blurry photo, no scale reference, or pure visual estimation.
63
64Return ONLY valid JSON:
65{
66  "items": [
67    {
68      "area_name": "e.g. Wall Run A, Island, Vanity",
69      "length_inches": number,
70      "depth_inches": number,
71      "sqft": number (1 decimal),
72      "shape": "rectangular | l_shape | u_shape | other",
73      "cutouts": [{ "type": "sink | cooktop | faucet | other", "description": "string" }],
74      "confidence": "high | medium | low",
75      "notes": "short observation, e.g. 'handwritten dimensions — verify', 'island has curved edge'"
76    }
77  ],
78  "overall_confidence": "high | medium | low",
79  "summary": "one-sentence overview of what was detected"
80}`,file_urls:[d],model:"gemini_3_flash",response_json_schema:{type:"object",properties:{items:{type:"array",items:{type:"object",properties:{area_name:{type:"string"},length_inches:{type:"number"},depth_inches:{type:"number"},sqft:{type:"number"},shape:{type:"string"},cutouts:{type:"array",items:{type:"object"}},confidence:{type:"string"},notes:{type:"string"}}}},overall_confidence:{type:"string"},summary:{type:"string"}},required:["items"]}}),w=j.items||[];if(w.length===0){$.error("Could not detect any countertop sections. Try a clearer photo or a cabinet plan PDF.");return}const A=w.map((T,D)=>{var B,U,oe;const Y=T.sqft||(T.length_inches||0)*(T.depth_inches||0)/144,P=(B=T.cutouts)==null?void 0:B.some(Ne=>Ne.type==="sink"),h=(U=T.cutouts)==null?void 0:U.some(Ne=>Ne.type==="cooktop"),z=[`AI-extracted (${T.confidence||"medium"} confidence)`];if(T.notes&&z.push(T.notes),(oe=T.cutouts)!=null&&oe.length){const Ne=T.cutouts.map(ue=>ue.type).join(", ");z.push(`cutouts: ${Ne}`)}return{...ga,name:T.area_name||`Section ${D+1}`,area_name:T.area_name||`Section ${D+1}`,length_inches:T.length_inches||"",width_inches:T.depth_inches||"",sqft:Y.toFixed(1),edge_profile:"eased",sink_type:P?"top_mount":"none",co
80oktop_included:h,notes:z.join(" · "),markup_pct:0}});e(A);const M=j.overall_confidence||"medium";$.success(`Imported ${A.length} section${A.length!==1?"s":""} from plan (${M} confidence)`)}catch(d){$.error("Failed to read plan: "+(d.message||"Unknown error"))}finally{r(!1),n.current&&(n.current.value="")}}};return t.jsxs(t.Fragment,{children:[t.jsx("input",{ref:n,type:"file",accept:".pdf,.jpg,.jpeg,.png,.webp",onChange:i,className:"hidden"}),t.jsxs(X,{variant:"outline",size:"sm",onClick:()=>{var l;return(l=n.current)==null?void 0:l.click()},disabled:a,title:"Upload a cabinet plan PDF or photo of a sketch",children:[a?t.jsx(Bt,{className:"w-4 h-4 animate-spin"}):t.jsx(Yi,{className:"w-4 h-4"}),a?"Reading...":"Import Plan"]})]})}const ps=1200,xs=800,Rs=20,ad=10;let Ma=null;function rd(){return Ma||(Ma=new Promise((e,s)=>{if(window.pdfjsLib){window.pdfjsLib.GlobalWorkerOptions.workerSrc="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js",e(window.pdfjsLib);return}const a=document.createElement("script");a.src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js",a.onload=()=>{window.pdfjsLib.GlobalWorkerOptions.workerSrc="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js",e
80(window.pdfjsLib)},a.onerror=()=>s(new Error("Failed to load PDF viewer")),document.head.appendChild(a)}),Ma)}async function ui(e,s){const r=await(await rd()).getDocument(e).promise,n=await r.getPage(s),i=n.getViewport({scale:2}),l=document.createElement("canvas");l.width=i.width,l.height=i.height,await n.render({canvasContext:l.getContext("2d"),viewport:i}).promise;const u=new Image;return u.src=l.toDataURL("image/png"),await new Promise(c=>u.onload=c),{img:u,totalPages:r.numPages}}function fs(e){return Math.round(e/Rs)*Rs}function mi(e,s){const a=s.getBoundingClientRect();return{x:(e.clientX-a.left)/a.width*ps,y:(e.clientY-a.top)/a.height*xs}}function Ta(e,s){return Math.sqrt((s.x-e.x)**2+(s.y-e.y)**2)}function hi(e){const s=e.map(r=>r.x),a=e.map(r=>r.y);return{minX:Math.min(...s),minY:Math.min(...a),maxX:Math.max(...s),maxY:Math.max(...a)}}function nd(e){let s=0;for(let a=0;a<e.length;a++){const r=(a+1)%e.length;s+=e[a].x*e[r].y,s-=e[r].x*e[a].y}return Math.abs(s/2)}function id(e){return e.reduce((s,a,r)=>{const n=e[r],i=e[(r+1)%e.length];return s+Ta(n,i)},0)}function fi(e,s){const a=ad/(s*12);return{...e,points:e.points.map(r=>({x:r.x*a,y:r.y*a})),cutouts:(e.cutouts||[]).map(r=>({...r,x:r.x*a,y:r.y*a,radius:r.radius*a}))}}function ld({countertops:e,onCountertopsChange:s}){const a=m.useRef(null),r=m.useRef(null),[n,i]=m.useState(null),[l,u]=m.useState(null),[c,d]=m.useState(.45),[j,w]=m.useState(null),[A,M]=m.useState(1),[T,D]=m.useState(1),[Y,P]=m.useState(!1),[h,J]=m.useState(null),[z,B]=m.useState([]),[U,oe]=m.useState(""),[Ne,ue]=m.useState("ft"),[je,ye]=m.useState("calibrate"),[W,V]=m.useState([]),[q,E]=m.useState(null),[be,we]=m.useState(!1),[le,me]=m.useState([]),[De,Ge]=m.useState(null),[Ue,nt]=m.useState(!1),[lt,dt]=m.useState(!1),fe=m.useRef(null),Ke=m.useRef(null),et=async ee=>{if(ee){nt(!0),Ke.current=ee;try{const k=URL.createObjectURL(ee);let Z=null;if(ee.type==="application/pdf"||ee.name.toLowerCase().endsWith(".pdf")){w(k);const _e=await ui(k,1);Z=_e.img,D(_e.totalPages),M(1)}else if(ee.type.startsWith("image/"))w(null),Z=new Image,Z.src=k,await new Promise(_e=>Z.onload=_e),D(1);else{$.error("Please upload a PDF or image file");return}i(Z),it(Z),J(null),B([]),oe(""),ye("calibrate"),$.success("Plan loaded — calibrate the scale to start tracing")}catch(k){console.error(k),$.error("Failed to load file. Try an image instead.")}finally{nt(!1)}}},it=ee=>{const Z=ps-80,_e=xs-80,Se=ee.width/ee.height;let F,o;Z/_e>Se?(o=_e,F=o*Se):(F=Z,o=F/Se),u({x:(ps-F)/2,y:(xs-o)/2,w:F,h:o})};m.useEffect(()=>{n&&!l&&it(n)},[n,l]);const Xe=async ee=>{const k=A+ee;if(!(k<1||k>T||!j)){P(!0);try{const{img:Z}=await ui(j,k);i(Z),M(k),it(Z),J(null),B([]),ye("calibrate")}catch{$.error("Failed to load page")}finally{P(!1)}}},pt=ee=>{B(k=>k.length>=2?[ee]:[...k,ee])},x=()=>{if(z.length!==2||!U){$.error("Click two points on the plan and enter the known distance");return}const ee=Ta(z[0],z[1]);if(ee<5){$.error("Points are too close together");return}const k=Ne==="ft"?parseFloat(U)*12:parseFloat(U);if(!k||k<=0){$.error("Enter a valid distance");return}const Z=ee/k;J(Z),ye("rectangle"),$.success(`Scale set: ${Z.toFixed(1)} px/inch (${(Z*12).toFixed(0)} px/ft)`)},Q=async()=>{const ee=Ke.current;if(!ee){$.error("Upload a plan first");return}if(!l){$.error("Plan is still loading");return}dt(!0);try{const{file_url:k}=await ge.integrations.Core.UploadFile({file:ee}),_e=(await ge.functions.invoke("autoDetectScale",{file_url:k})).data;if(!(_e!=null&&_e.found)){$.info("No scale indicator found — calibrate manually with two clicks");return}if(_e.type==="scale_ratio"&&_e.scaleRatio){$.info("Found a scale notation, but pixel-based detection needs a scale bar or dimension line. Try manual calibration.");return}if(!_e.bbox||!_e.realLengthInches){$.info("Scale indicator found but couldn't get precise measurements — try manual calibration");return}const{x1:Se,y1:F,x2:o,y2:_}=_e.bbox,O={x:l.x+Se*l.w,y:l.y+F*l.h},f={x:l.x+o*l.w,y:l.y+_*l.h},I=Ta(O,f);if(I<10){$.error("Detected dimension is too small to calibrate reliably");return}const N=I/_e.realLengthInches;J(N),B([O,f]),oe(_e.realLengthInches.toString()),ue("in"),ye("rectangle"),$.success(`Scale auto-detected: ${N.toFixed(1)} px/in (${(N*12).toFixed(0)} px/ft) — ${_e.description||"verified"}`)}catch(k){console.error(k),$.error("Auto-detect failed — try manual calibration")}finally{dt(!1)}},C=ee=>{if(V(k=>[...k,ee]),h){const k=fi(ee,h);s([...e,k])}E(ee.id)},ne=ee=>{V(k=>k.filter(Z=>Z.id!==ee)),s(e.filter(k=>k.id!==ee)),q===ee&&E(null)},ce=(ee,k,Z)=>{V(_e=>_e.map(Se=>Se.id!==ee?Se:{...Se,points:Se.points.map(F=>({x:F.x+k,y:F.y+Z})),cutouts:(Se.cutouts||[]).map(F=>({...F,x:F.x+k,y:F.y+Z}))}))},te=()=>{if(h){const ee=e.filter(Z=>!W.some(_e=>_e.id===Z.id)),k=W.map(Z=>fi(Z,h));s([...ee,...k])}},Ce=m.useCallback(()=>{const ee=a.current;if(!ee)return;const k=ee.getContext("2d");k.clearRect(0,0,ps,xs),k.fillStyle="#ffffff",k.fillRect(0,0,ps,xs),n&&l&&(k.globalAlpha=c,k.drawImage(n,l.x,l.y,l.w,l.h),k.globalAlpha=1),k.strokeStyle="#e8e8e8",k.lineWidth=.5,k.beginPath();for(let Z=0;Z<=ps;Z+=Rs)k.moveTo(Z,0),k.lineTo(Z,xs);for(let Z=0;Z<=xs;Z+=Rs)k.moveTo(0,Z),k.lineTo(ps,Z);if(k.stroke(),z.length>0&&(k.strokeStyle="#ef4444",k.lineWidth=2,k.setLineDash([8,4]),k.beginPath(),k.moveTo(z[0].x,z[0].y),z.forEach(Z=>k.lineTo(Z.x,Z.y)),z.length===2&&k.stroke(),k.setLineDash([]),z.forEach((Z,_e)=>{k.beginPath(),k.arc(Z.x,Z.y,6,0,Math.PI*2),k.fillStyle=_e===0?"#dc2626":"#2563eb",k.fill(),k.strokeStyle="#ffffff",k.lineWidth=2,k.stroke()}),z.length===2)){const Z={x:(z[0].x+z[1].x)/2,y:(z[0].y+z[1].y)/2},_e=Ta(z[0],z[1]);k.fillStyle="#dc2626",k.font="bold 13px Inter, sans-serif",k.textAlign="center",k.fillText(`${_e.toFixed(0)} px`,Z.x,Z.y-12),k.textAlign="left"}W.forEach(Z=>{const _e=Z.id===q,Se=Z.points;if(Se.length<3)return;k.beginPath(),k.moveTo(Se[0].x,Se[0].y);for(let _=1;_<Se.length;_++)k.lineTo(Se[_].x,Se[_].y);if(k.closePath(),k.fillStyle=_e?"rgba(132,204,22,0.4)":"rgba(132,204,22,0.2)",k.fill(),k.strokeStyle=_e?"#4d7c0f":"#84cc16",k.lineWidth=_e?2.5:1.5,k.stroke(),h&&Se.length>=4){const _=hi(Se),O=(_.maxX-_.minX)/h,f=(_.maxY-_.minY)/h,I=(O/12).toFixed(1),N=(f/12).toFixed(1);k.fillStyle="#1e293b",k.font="bold 12px Inter, sans-serif",k.textAlign="center",k.fillText(`${I}'`,_.minX+(_.maxX-_.minX)/2,_.minY-7),k.save(),k.translate(_.maxX+14,_.minY+(_.maxY-_.minY)/2),k.rotate(Math.PI/2),k.fillText(`${N}
80'`,0,0),k.restore(),k.textAlign="left"}const F=Se.reduce((_,O)=>_+O.x,0)/Se.length,o=Se.reduce((_,O)=>_+O.y,0)/Se.length;k.fillStyle=_e?"#3f6212":"#374151",k.font=`${_e?"bold ":""}12px Inter, sans-serif`,k.textAlign="center",k.fillText(Z.name,F,o+4),k.textAlign="left",(Z.cutouts||[]).forEach(_=>{k.beginPath(),k.arc(_.x,_.y,_.radius||25,0,Math.PI*2),k.fillStyle="#f8fafc",k.fill(),k.strokeStyle="#ef4444",k.lineWidth=2,k.stroke()})}),be&&le.length>0&&(k.beginPath(),k.moveTo(le[0].x,le[0].y),le.forEach(Z=>k.lineTo(Z.x,Z.y)),De&&(k.lineTo(De.x,De.y),je==="rectangle"&&k.lineTo(le[0].x,De.y)),je==="polygon"&&le.length>2&&k.lineTo(le[0].x,le[0].y),k.strokeStyle="#84cc16",k.lineWidth=2,k.setLineDash([6,4]),k.stroke(),k.setLineDash([]),k.beginPath(),k.arc(le[0].x,le[0].y,5,0,Math.PI*2),k.fillStyle="#65a30d",k.fill())},[n,l,c,z,W,q,be,le,De,h,je]);m.useEffect(()=>{Ce()},[Ce]);const Oe=ee=>{const k=a.current;if(!k)return;const Z=mi(ee,k);if(je==="calibrate"){pt(Z);return}if(je==="select"){const _e=[...W].reverse().find(Se=>{const F=hi(Se.points);return Z.x>=F.minX&&Z.x<=F.maxX&&Z.y>=F.minY&&Z.y<=F.maxY});_e?(E(_e.id),fe.current={id:_e.id,startX:Z.x,startY:Z.y}):E(null);return}if(je==="rectangle"){const _e=fs(Z.x),Se=fs(Z.y);if(!be)we(!0),me([{x:_e,y:Se}]);else{const F=le[0].x,o=le[0].y;if(Math.abs(_e-F)<Rs||Math.abs(Se-o)<Rs)return;const _={id:Date.now().toString(),type:"rectangle",name:`Piece ${W.length+1}`,points:[{x:F,y:o},{x:_e,y:o},{x:_e,y:Se},{x:F,y:Se}],material:"",edge_profile:"eased",cutouts:[]};C(_),we(!1),me([]),Ge(null)}return}if(je==="polygon"){const _e=fs(Z.x),Se=fs(Z.y);if(ee.shiftKey&&le.length>=2){const F={id:Date.now().toString(),type:"polygon",name:`Piece ${W.length+1}`,points:[...le,{x:_e,y:Se}],material:"",edge_profile:"eased",cutouts:[]};C(F),we(!1),me([]),Ge(null)}else we(!0),me(F=>[...F,{x:_e,y:Se}]);return}},b=ee=>{const k=a.current;if(!k)return;const Z=mi(ee,k);if(fe.current&&je==="select"){const _e=fs(Z.x-fe.current.startX),Se=fs(Z.y-fe.current.startY);(_e||Se)&&(ce(fe.current.id,_e,Se),fe.current.startX=Z.x,fe.current.startY=Z.y);return}be&&Ge({x:fs(Z.x),y:fs(Z.y)})},tt=()=>{fe.current&&(te(),fe.current=null)},ms=h?W.reduce((ee,k)=>ee+nd(k.points)/h**2/144,0):0,ws=h?W.reduce((ee,k)=>ee+id(k.points)/h/12,0):0;return n?t.jsxs("div",{className:"space-y-2",children:[t.jsx(at,{children:t.jsx(rt,{className:"py-2 px-3",children:t.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[t.jsxs("div",{className:"flex items-center gap-1",children:[t.jsxs(X,{size:"sm",variant:je==="calibrate"?"default":"outline",onClick:()=>{ye("calibrate"),we(!1),me([])},children:[t.jsx(ua,{className:"w-4 h-4 mr-1"})," Calibrate"]}),t.jsxs(X,{size:"sm",variant:je==="select"?"default":"outline",onClick:()=>{ye("select"),we(!1),me([])},children:[t.jsx(Ho,{className:"w-4 h-4 mr-1"})," Select"]}),t.jsxs(X,{size:"sm",variant:je==="rectangle"?"default":"outline",onClick:()=>{ye("rectangle"),we(!1),me([])},disabled:!h,children:[t.jsx(Cr,{className:"w-4 h-4 mr-1"})," Rectangle"]}),t.jsxs(X,{size:"sm",variant:je==="polygon"?"default":"outline",onClick:()=>{ye("polygon"),we(!1),me([])},disabled:!h,children:[t.jsx(Oa,{className:"w-4 h-4 mr-1"})," Polygon"]}),q&&t.jsxs(X,{size:"sm",variant:"destructive",onClick:()=>ne(q),children:[t.jsx(Fs,{className:"w-4 h-4 mr-1"})," Delete"]}),je==="polygon"&&be&&le.length>=3&&t.jsx(X,{size:"sm",variant:"default",onClick:()=>{const ee={id:Date.now().toString(),type:"polygon",name:`Piece ${W.length+1}`,points:[...le],material:"",edge_profile:"eased",cutouts:[]};C(ee),we(!1),me([]),Ge(null)},children:"Close Polygon"}),be&&t.jsxs(X,{size:"sm",variant:"ghost",onClick:()=>{we(!1),me([]),Ge(null)},children:[t.jsx(ca,{className:"w-3.5 h-3.5 mr-1"})," Cancel"]})]}),t.jsxs("div",{className:"flex items-center gap-2",children:[T>1&&t.jsxs("div",{className:"flex items-center gap-1",children:[t.jsx(X,{size:"icon",variant:"outline",className:"h-7 w-7",onClick:()=>Xe(-1),disabled:A<=1||Y,children:t.jsx(go,{className:"w-4 h-4"})}),t.jsx("span",{className:"text-xs font-medium whitespace-nowrap",children:Y?"…":`${A} / ${T}`}),t.jsx(X,{size:"icon",variant:"outline",className:"h-7 w-7",onClick:()=>Xe(1),disabled:A>=T||Y,children:t.jsx(Mi,{className:"w-4 h-4"})})]}),t.jsxs("div",{className:"flex items-center gap-1",children:[t.jsx(Oi,{className:"w-3.5 h-3.5 text-muted-foreground"}
80),t.jsx("input",{type:"range",min:0,max:1,step:.05,value:c,onChange:ee=>d(parseFloat(ee.target.value)),className:"w-20 h-1"})]}),t.jsx("input",{ref:r,type:"file",accept:"application/pdf,image/*",className:"hidden",onChange:ee=>{var k;return et((k=ee.target.files)==null?void 0:k[0])}}),t.jsxs(X,{size:"sm",variant:"outline",onClick:()=>{var ee;return(ee=r.current)==null?void 0:ee.click()},children:[t.jsx(fr,{className:"w-3.5 h-3.5 mr-1"})," New Plan"]})]})]})})}),!h&&t.jsx(at,{className:"border-orange-300 bg-orange-50 dark:bg-orange-950/30",children:t.jsx(rt,{className:"py-2 px-3",children:t.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[t.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[t.jsx("p",{className:"text-sm font-medium text-orange-700 dark:text-orange-400",children:z.length===0?"① Click two points on a known dimension (e.g., a wall labeled 10')":z.length===1?"② Click the second point":"③ Enter the real-world distance between the two points"}),t.jsx(X,{size:"sm",variant:"outline",onClick:Q,disabled:lt,className:"h-7 text-xs border-orange-400 text-orange-700 hover:bg-orange-100 dark:text-orange-400 dark:hover:bg-orange-950",children:lt?t.jsxs(t.Fragment,{children:[t.jsx(Bt,{className:"w-3.5 h-3.5 mr-1 animate-spin"})," Detecting…"]}):t.jsxs(t.Fragment,{children:[t.jsx(Or,{className:"w-3.5 h-3.5 mr-1"})," Auto-Detect Scale"]})})]}),z.length===2&&t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(He,{type:"number",placeholder:"Distance",value:U,onChange:ee=>oe(ee.target.value),className:"w-24 h-8",onKeyDown:ee=>ee.key==="Enter"&&x()}),t.jsxs("select",{value:Ne,onChange:ee=>ue(ee.target.value),className:"h-8 border rounded-md text-sm px-1",children:[t.jsx("option",{value:"ft",children:"ft"}),t.jsx("option",{value:"in",children:"in"})]}),t.jsx(X,{size:"sm",onClick:x,children:"Set Scale"})]})]})})}),h&&t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsxs(Tt,{variant:"secondary",className:"text-xs",children:[t.jsx(ua,{className:"w-3 h-3 mr-1"}),h.toFixed(1)," px/in (",(h*12).toFixed(0)," px/ft)"]}),t.jsx(X,{size:"sm",variant:"ghost",className:"h-6 text-xs",onClick:()=>{J(null),B([]),ye("calibrate")},children:"Recalibrate"})]}),t.jsx("div",{className:"relative rounded-xl overflow-hidden border bg-white",children:t.jsx("canvas",{ref:a,width:ps,height:xs,onMouseDown:Oe,onMouseMove:b,onMouseUp:tt,onMouseLeave:tt,onTouchStart:ee=>{ee.preventDefault();const k=ee.touches[0];Oe({clientX:k.clientX,clientY:k.clientY})},onTouchMove:ee=>{ee.preventDefault();const k=ee.touches[0];b({clientX:k.clientX,clientY:k.clientY})},onTouchEnd:tt,style:{display:"block",width:"100%",height:"auto",cursor:je==="calibrate"?"crosshair":je==="select"?"default":"crosshair",touchAction:"none"}})}),t.jsxs("div",{className:"flex items-center gap-4 flex-wrap text-sm",children:[t.jsxs("span",{className:"font-medium",children:[t.jsx(Cr,{className:"w-4 h-4 inline mr-1 text-muted-foreground"}),W.length," piece",W.length!==1?"s":""]}),h&&t.jsxs(t.Fragment,{children:[t.jsxs("span",{className:"font-medium",children:[ms.toFixed(1)," sqft"]}),t.jsxs("span",{className:"font-medium",children:[ws.toFixed(1),"' edge"]})]}),je==="polygon"&&be&&t.jsx("span",{className:"text-xs text-muted-foreground",children:"Click to add points · Shift+click to close"}),je==="rectangle"&&be&&t.jsx("span",{className:"text-xs text-muted-foreground",children:"Click the opposite corner"})]})]}):t.jsx("div",{className:"flex flex-col items-center justify-center border-2 border-dashed border-border rounded-xl py-20 px-4 text-center",children:Ue?t.jsxs(t.Fragment,{children:[t.jsx(Bt,{className:"w-12 h-12 text-primary animate-spin mb-4"}),t.jsx("p",{className:"text-lg font-semibold",children:"Loading plan…"})]}):t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[t.jsx(Yi,{className:"w-12 h-12 text-muted-foreground"}),t.jsx(fr,{className:"w-8 h-8 text-muted-foreground"})]}),t.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Upload a Plan to Start Takeoff"}),t.jsx("p",{className:"text-sm text-muted-foreground mb-6 max-w-md",children:"Drop in a PDF blueprint, a screenshot, or even a photo a customer texted you. You'll trace the tops over it and get accurate square footage."}),t.jsx("input",{ref:r,type:"file",accept:"application/pdf,image/*",className:"hidden",onChange:ee=>{var k;return et((k=ee.target.files)==null?void 0:k[0])}}),t.jsxs(X,{size:"lg",onClick:()=>{var ee;return(ee=r.current)==null?void 0:ee.click()},children:[t.jsx(fr,{className:"w-4 h-4 mr-2"})," Choose File"]}),t.jsx("p",{className:"text-xs text-muted-foreground mt-3",children:"PDF, PNG, JPG supported"})]})})}const od=[{value:"eased",label:"Eased (Standard)"},{value:"bevel",label:"Bevel"},{value:"bullnose",label:"Bullnose"},{value:"ogee",label:"Ogee (Premium)"},{value:"mitered",label:"Mitered"}],cd=["granite","quartz","marble","quartzite","soapstone","laminate","butcher_block"];function dd(e){if(!e||e.length<3)return 0;let s=0;for(let a=0;a<e.length;a++){const r=(a+1)%e.length;s+=e[a].x*e[r].y,s-=e[r].x*e[a].y}return Math.abs(s/2)/14400}function pi(e){if(!e||e.type==="slab")return 0;let s=dd(e.points);if(e.cutouts&&e.cutouts.length>0)for(const a of e.cutouts)s-=a.width*a.height/14400;return Math.max(0,s)}function ud(e,s){if(!e||e.length<2)return 0;const a=s&&Object.keys(s).length>0;let r=0;for(let n=0;n<e.length;n++){if(a&&!s[String(n)])continue;const i=e[n],l=e[(n+1)%e.length];r+=Math.sqrt(Math.pow(l.x-i.x,2)+Math.pow(l.y-i.y,2))/10}return r/12}function md({allMaterials:e=[],onLineItemsChange:s}){const[a,r]=m.useState([]),[n,i]=m.useState("quartz"),[l,u]=m.useState(""),[c,d]=m.useState("eased"),[j,w]=m.useState(""),A=m.useMemo(()=>{let h=e.filter(J=>J.material_type===n&&J.material_name);if(j){const J=j.toLowerCase();h=h.filter(z=>{var B,U,oe;return((B=z.material_name)==null?void 0:B.toLowerCase().includes(J))||((U=z.color)==null?void 0:U.toLowerCase().includes(J))||((oe=z.supplier)==null?void 0:oe.toLowerCase().includes(J))})}return h},[e,n,j]),M=e.find(h=>h.material_name===l),T=a.filter(h=>h.type!=="slab"),D=T.reduce((h,J)=>
80h+pi(J),0),Y=D*((M==null?void 0:M.selling_price_per_sqft)||0),P=m.useRef("");return m.useEffect(()=>{if(!M||D<=0)return;const h=T.map((z,B)=>({...ga,name:M.material_name,area_name:`Piece ${B+1}`,sqft:pi(z).toFixed(2),material_name:M.material_name,material_type:M.material_type,color:M.color||"",unit_price_per_sqft:M.selling_price_per_sqft||0,edge_profile:c,edge_linear_ft:parseFloat(ud(z.points,z.edgeProfiles).toFixed(2)),markup_pct:0})),J=JSON.stringify(h);if(J!==P.current){P.current=J;const z=setTimeout(()=>s(h),200);return()=>clearTimeout(z)}},[a,M,c,D,s]),t.jsxs("div",{className:"rounded-lg border border-primary/30 bg-primary/5 p-3 space-y-3",children:[t.jsxs("div",{className:"flex items-center gap-1.5 text-xs font-semibold text-primary",children:[t.jsx(Ps,{className:"w-3.5 h-3.5"}),"PDF Takeoff — upload a plan, trace countertops, get instant line items"]}),t.jsxs("div",{className:"flex flex-wrap items-end gap-2",children:[t.jsxs("div",{className:"min-w-[110px]",children:[t.jsx(Ze,{className:"text-[11px]",children:"Type"}),t.jsxs(Wt,{value:n,onValueChange:h=>{i(h),u("")},children:[t.jsx(zt,{className:"h-8 text-xs",children:t.jsx(Ut,{})}),t.jsx(Ht,{children:cd.map(h=>t.jsx(Ye,{value:h,className:"capitalize",children:h.replace("_"," ")},h))})]})]}),t.jsxs("div",{className:"flex-1 min-w-[160px]",children:[t.jsx(Ze,{className:"text-[11px]",children:"Material"}),t.jsxs("div",{className:"relative",children:[t.jsx(Yr,{className:"absolute left-2 top-1/2 -translate-y-1/2 w-3 h-3 text-muted-foreground"}),t.jsx(He,{value:j,onChange:h=>w(h.target.value),placeholder:"Search material…",className:"h-8 pl-7 text-xs"})]})]}),t.jsxs("div",{className:"min-w-[110px]",children:[t.jsx(Ze,{className:"text-[11px]",children:"Edge"}),t.jsxs(Wt,{value:c,onValueChange:d,children:[t.jsx(zt,{className:"h-8 text-xs",children:t.jsx(Ut,{})}),t.jsx(Ht,{children:od.map(h=>t.jsx(Ye,{value:h.value,children:h.label},h.value))})]})]})]}),j&&t.jsx("div",{className:"max-h-32 overflow-y-auto rounded-md border divide-y bg-background",children:A.length===0?t.jsx("p",{className:"p-2 text-xs text-muted-foreground text-center",children:"No materials found."}):A.slice(0,8).map(h=>{var J;return t.jsxs("button",{type:"button",onClick:()=>{u(h.material_name),w("")},className:`w-full flex items-center justify-between px-2 py-1.5 text-left text-xs hover:bg-accent ${l===h.material_name?"bg-primary/10":""}`,children:[t.jsx("span",{className:"font-medium truncate",children:h.material_name}),t.jsxs("span",{className:"text-primary font-semibold ml-2",children:["$",((J=h.selling_price_per_sqft)==null?void 0:J.toFixed(0))||0,"/sf"]})]},h.id)})}),M&&t.jsxs("div",{className:"text-[11px] text-muted-foreground flex items-center justify-between rounded bg-muted/60 px-2 py-1",children:[t.jsxs("span",{children:["Selected: ",t.jsx("span",{className:"font-medium text-foreground",children:M.material_name})]}),t.jsxs("span",{className:"font-semibold text-primary",children:["$",(M.selling_price_per_sqft||0).toFixed(2),"/sf"]})]}),t.jsx("div",{className:"rounded-md border overflow-hidden bg-slate-50 dark:bg-slate-900",children:t.jsx(ld,{countertops:a,onCountertopsChange:r})}),t.jsxs("div",{className:"grid grid-cols-4 gap-2",children:[t.jsxs("div",{className:"rounded-lg bg-muted/60 p-2 text-center",children:[t.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Pieces"}),t.jsx("p",{className:"text-lg font-bold",children:T.length})]}),t.jsxs("div",{className:"rounded-lg bg-muted/60 p-2 text-center",children:[t.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Sqft"}),t.jsx("p",{className:"text-lg font-bold text-primary",children:D.toFixed(1)})]}),t.jsxs("div",{className:"rounded-lg bg-green-50 dark:bg-green-900/20 border border-green-200 dark:border-green-800 p-2 text-center",children:[t.jsx("p",{className:"text-[10px] text-green-700 dark:text-green-400",children:"Est. Cost"}),t.jsxs("p",{className:"text-lg font-bold text-green-700 dark:text-green-400",children:["$",Y.toFixed(0)]})]}),t.jsxs("div",{className:"rounded-lg bg-muted/60 p-2 text-center",children:[t.jsx("p",{className:"text-[10px] text-muted-foreground",children:"$/sf"}),t.jsx("p",{className:"text-lg font-bold",children:D>0?`$${(Y/D).toFixed(0)}`:"$0"})]})]}),!M&&T.length>0&&t.jsx("p",{className:"text-[11px] text-amber-600 text-center",children:"Select a material to generate line items from your takeoff."})]})}function xi({expiryDate:e,onSetExpiry:s,isEditing:a=!0}){const r=e?Math.ceil((new Date(e).getTime()-Date.now())/864e5):null;if(a)return t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx(Di,{className:"w-4 h-4 text-muted-foreground shrink-0"}),t.jsx(He,{type:"date",value:e||"",onChange:i=>s(i.target.value),className:"h-9 w-auto"}),r!==null&&r>=0&&t.jsxs("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:[r,"d left"]})]});if(!e)return null;const n=r<0?"bg-red-50 text-red-700 border-red-200 dark:bg-red-900/20 dark:text-red-400":r<=3?"bg-amber-50 text-amber-700 border-amber-200 dark:bg-amber-900/20 dark:text-amber-400":"bg-green-50 text-green-700 border-green-200 dark:bg-green-900/20 dark:text-green-400";return t.jsxs("div",{className:`inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-xs font-medium border ${n}`,children:[t.jsx(js,{className:"w-3.5 h-3.5"}),r<0?`Expired ${Math.abs(r)}d ago`:`${r} days to accept`]})}const gi=`1. This quote is valid for 30 days from the date issued.
812. A 50% deposit is required to begin fabrication.
823. Final measurements will be taken at time of template.
834. Any changes after template may incur additional charges.
845. Natural stone variation is not a defect — each slab is unique.
856. Customer is responsible for ensuring cabinets are level and secured prior to installation.
867. Sink cutouts require the sink on-site at time of template.`;function hd({terms:e,onChange:s,editable:a=!0}){const[r,n]=m.useState(!1),i=e||gi;return a?t.jsxs("div",{className:"rounded-xl border border-border bg-white dark:bg-slate-800 p-4",children:[t.jsxs("div",{className:"flex items-center justify-between mb-2",children:[t.jsxs("p",{className:"text-xs font-semibold flex items-center gap-1.5",children:[t.jsx(Ps,{className:"w-3.5 h-3.5"})," Terms & Conditions"]}),t.jsx(X,{variant:"ghost",size:"sm",className:"h-6 text-xs",onClick:()=>n(!r),children:r?t.jsxs(t.Fragment,{children:[t.jsx(Ba,{className:"w-3 h-3 mr-1"})," Done"]}):t.jsxs(t.Fragment,{children:[t.jsx(Ir,{className:"w-3 h-3 mr-1"})," Edit"]})})]}),r?t.jsx(Po,{value:e||"",onChange:l=>s(l.target.value),placeholder:gi,className:"text-xs min-h-[120px]"}):t.jsx("p",{className:"text-[11px] text-muted-foreground whitespace-pre-line leading-relaxed",children:i})]}):e?t.jsxs("div",{className:"rounded-xl border border-border bg-slate-50 dark:bg-slate-900/40 p-4",children:[t.jsxs("p",{className:"text-xs font-semibold mb-2 flex items-center gap-1.5",children:[t.jsx(Ps,{className:"w-3.5 h-3.5"})," Terms & Conditions"]}),t.jsx("p",{className:"text-[11px] text-muted-foreground whitespace-pre-line leading-relaxed",children:i})]}):null}function fd({quoteData:e,lineItems:s,onApplyTemplate:a}){const r=xa(),{data:n=[]}=jt({queryKey:["quote-templates"],queryFn:()=>ge.entities.QuoteTemplate.list("-created_date",50)}),i=async()=>{var c;const u=window.prompt("Template name:",`Standard ${e.project_type||"Kitchen"}`);if(u)try{await ge.entities.QuoteTemplate.create({template_name:u,description:`${s.length} line item${s.length!==1?"s":""}`,project_type:e.project_type||"kitchen",material_type:((c=s[0])==null?void 0:c.material_type)||"",default_line_items:s.map(d=>({name:d.name,material_type:d.material_type,material_name:d.material_name,edge_profile:d.edge_profile,sink_type:d.sink_type,cooktop_included:d.cooktop_included,backsplash:d.backsplash,special_features:d.special_features,notes:d.notes}))}),r.invalidateQueries({queryKey:["quote-templates"]}),$.success("Template saved!")}catch(d){$.error("Failed to save template"),console.error(d)}},l=u=>{const c=n.find(d=>d.id===u);c&&(a(c),$.success(`Applied template: ${c.template_name}`))};return t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsxs(X,{variant:"outline",size:"sm",onClick:i,disabled:s.length===0,children:[t.jsx(Ka,{className:"w-3.5 h-3.5 mr-1.5"})," Save Template"]}),n.length>0&&t.jsxs(Wt,{onValueChange:l,children:[t.jsxs(zt,{className:"h-8 w-48 text-xs",children:[t.jsx(oc,{className:"w-3.5 h-3.5 mr-1"}),t.jsx(Ut,{placeholder:"Load template"})]}),t.jsx(Ht,{children:n.map(u=>t.jsx(Ye,{value:u.id,children:u.template_name},u.id))})]})]})}function pd({versions:e=[]}){const[s,a]=m.useState(!1);return e.length?t.jsxs("div",{className:"rounded-xl border border-border bg-white dark:bg-slate-800",children:[t.jsxs("button",{onClick:()=>a(!s),className:"w-full flex items-center justify-between px-4 py-2.5",children:[t.jsxs("span",{className:"text-xs font-semibold flex items-center gap-1.5",children:[t.jsx(Bo,{className:"w-3.5 h-3.5"})," Version History (",e.length,")"]}),s?t.jsx(yo,{className:"w-3.5 h-3.5"}):t.jsx(Mi,{className:"w-3.5 h-3.5"})]}),s&&t.jsx("div",{className:"divide-y divide-border border-t border-border",children:e.slice().reverse().map(r=>
86t.jsxs("div",{className:"px-4 py-2 flex items-center justify-between text-xs",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsxs("span",{className:"font-medium",children:["v",r.version]}),t.jsx("span",{className:"text-muted-foreground",children:new Date(r.saved_at).toLocaleString()})]}),t.jsxs("div",{className:"flex items-center gap-3",children:[r.selling_price!=null&&t.jsxs("span",{className:"tabular-nums font-medium",children:["$",r.selling_price.toLocaleString()]}),r.status&&t.jsx("span",{className:"text-muted-foreground capitalize",children:r.status}),r.saved_by&&t.jsx("span",{className:"text-muted-foreground",children:r.saved_by})]})]},r.version))})]}):null}function xd({quoteData:e,updateQuoteData:s,checkTaxExemptAccount:a,isTaxExemptAccount:r,accounts:n=[],selectedAccountId:i,onSelectAccount:l,onCreateAccount:u,isCreatingAccount:c,matchedAccount:d}){const[j,w]=m.useState(!1),[A,M]=m.useState("retail"),[T,D]=m.useState(!1),Y=n.find(P=>P.id===i);return t.jsxs(at,{children:[t.jsx(Ua,{className:"pb-3",children:t.jsxs(Ha,{className:"flex items-center gap-2 text-base",children:[t.jsx(tc,{className:"w-4 h-4 text-primary"})," Customer Info"]})}),t.jsxs(rt,{className:"space-y-3",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsx(Ze,{className:"text-xs",children:"Account"}),t.jsxs(Go,{open:T,onOpenChange:D,children:[t.jsx(Ko,{asChild:!0,children:t.jsxs(X,{variant:"outline",role:"combobox",className:"h-9 w-full justify-between font-normal",children:[Y?t.jsxs("span",{className:"truncate",children:[Y.account_name,Y.account_type==="contractor"?" (Contractor)":""]}):t.jsx("span",{className:"text-muted-foreground",children:"Search or select an account…"}),t.jsx(ic,{className:"w-4 h-4 shrink-0 opacity-50"})]})}),t.jsx(Zo,{className:"p-0",align:"start",children:t.jsxs(Xo,{children:[t.jsx(Jo,{placeholder:"Type to search customers…"}),t.jsxs(Qo,{children:[t.jsx(ec,{children:"No accounts found."}),t.jsx(Qn,{children:n.map(P=>t.jsxs(ei,{value:`${P.account_name} ${P.email||""} ${P.phone||""}`,onSelect:()=>{w(!1),l(P.id),D(!1)},children:[t.jsx(qs,{className:`w-3.5 h-3.5 mr-2 shrink-0 ${i===P.id?"opacity-100":"opacity-0"}`}),t.jsxs("span",{className:"truncate",children:[P.account_name,P.account_type==="contractor"?" (Contractor)":""]})]},P.id))}),t.jsx(Qn,{children:t.jsxs(ei,{value:"create new account",onSelect:()=>{w(!0),D(!1)},children:[t.jsx(It,{className:"w-3.5 h-3.5 mr-2 shrink-0"}),"Create New Account"]})})]})]})})]})]}),j&&t.jsxs("div",{className:"flex gap-2 items-end p-2 bg-primary/5 border border-primary/20 rounded-md",children:[t.jsxs("div",{className:"space-y-1 flex-1",children:[t.jsx(Ze,{className:"text-xs",children:"Account Type"}),t.jsxs(Wt,{value:A,onValueChange:M,children:[t.jsx(zt,{className:"h-9",children:t.jsx(Ut,{})}),t.jsxs(Ht,{children:[t.jsx(Ye,{value:"retail",children:"Retail"}),t.jsx(Ye,{value:"contractor",children:"Contractor"}),t.jsx(Ye,{value:"commercial",children:"Commercial"}),t.jsx(Ye,{value:"other",children:"Other"})]})]})]}),t.jsxs(X,{size:"sm",onClick:()=>u(A),disabled:c,className:"gap-1",children:[c?t.jsx(Bt,{className:"w-4 h-4 animate-spin"}):t.jsx(It,{className:"w-4 h-4"}),"Save Account"]}),t.jsx(X,{size:"sm",variant:"ghost",onClick:()=>w(!1),children:"Cancel"})]}),d&&!j&&t.jsxs("div",{className:"flex items-center gap-2 text-xs text-green-700 bg-green-50 dark:bg-green-900/20 border border-green-200 rounded-md px-3 py-1.5",children:[t.jsx(qs,{className:"w-3.5 h-3.5 shrink-0"}),"Linked to account: ",t.jsx("span",{className:"font-semibold",children:d.account_name}),t.jsxs("span",{className:"text-muted-foreground",children:["(",d.account_type,")"]})]}),t.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[t.jsxs("div",{className:"space-y-1",children:[t.jsx(Ze,{className:"text-xs",children:"Name *"}),t.jsx(He,{value:e.customer_name,onChange:P=>{s("customer_name",P.target.value),a(P.target.value)},placeholder:"John Smith",className:"h-9"})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx(Ze,{className:"text-xs",children:"Phone"}),t.jsx(He,{value:e.customer_phone,onChange:P=>s("customer_phone",P.target.value),placeholder:"(555) 123-4567",className:"h-9"})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx(Ze,{className:"text-xs",children:"Email"}),t.jsx(He,{type:"email",value:e.customer_email,onChange:P=>s("customer_email",P.target.value),placeholder:"[email protected]",className:"h-9"})]})]}),t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[t.jsxs("div",{className:"space-y-1 sm:col-span-2",children:[t.jsx(Ze,{className:"text-xs",children:"Job Address"}),t.jsx(He,{value:e.job_address,onChange:P=>s("job_address",P.target.value),placeholder:"123 Main St, City, State 12345",className:"h-9"})]}),t.jsxs("div",{className:"space-y-1",children:[t.jsx(Ze,{className:"text-xs",children:"Project"}),t.jsxs(Wt,{value:e.project_type,onValueChange:P=>s("project_type",P),children:[t.jsx(zt,{className:"h-9",children:t.jsx(Ut,{})}),t.jsxs(Ht,{children:[t.jsx(Ye,{value:"kitchen",children:"Kitchen"}),t.jsx(Ye,{value:"bathroom",children:"Bathroom"}),t.jsx(Ye,{value:"commercial",children:"Commercial"}),t.jsx(Ye,{value:"outdoor",children:"Outdoor"}),t.jsx(Ye,{value:"other",children:"Other"})]})]})]})]})]})]})}//! moment.js
87//! version : 2.30.1
88//! authors : Tim Wood, Iskren Chernev, Moment.js contributors
89//! license : MIT
90//! momentjs.com
91var Hi;function se(){return Hi.apply(null,arguments)}function gd(e){Hi=e}function $t(e){return e instanceof Array||Object.prototype.toString.call(e)==="[object Array]"}function Ts(e){return e!=null&&Object.prototype.toString.call(e)==="[object Object]"}function Re(e,s){return Object.prototype.hasOwnProperty.call(e,s)}function zr(e){if(Object.getOwnPropertyNames)return Object.getOwnPropertyNames(e).length===0;var s;for(s in e)if(Re(e,s))return!1;return!0}function bt(e){return e===void 0}function cs(e){return typeof e=="number"||Object.prototype.toString.call(e)==="[object Number]"}function ya(e){return e instanceof Date||Object.prototype.toString.call(e)==="[object Date]"}function Bi(e,s){var a=[],r,n=e.length;for(r=0;r<n;++r)a.push(s(e[r],r));return a}function ys(e,s){for(var a in s)Re(s,a)&&(e[a]=s[a]);return Re(s,"toString")&&(e.toString=s.toString),Re(s,"valueOf")&&(e.valueOf=s.valueOf),e}function Gt(e,s,a,r){return pl(e,s,a,r,!0).utc()}function yd(){return{empty:!1,unusedTokens:[],unusedInput:[],overflow:-2,charsLeftOver:0,nullInput:!1,invalidEra:null,invali
vendor: 24,289 bytes, lines 91-94
91dMonth:null,invalidFormat:!1,userInvalidated:!1,iso:!1,parsedDateParts:[],era:null,meridiem:null,rfc2822:!1,weekdayMismatch:!1}}function Te(e){return e._pf==null&&(e._pf=yd()),e._pf}var Mr;Array.prototype.some?Mr=Array.prototype.some:Mr=function(e){var s=Object(this),a=s.length>>>0,r;for(r=0;r<a;r++)if(r in s&&e.call(this,s[r],r,s))return!0;return!1};function Ur(e){var s=null,a=!1,r=e._d&&!isNaN(e._d.getTime());if(r&&(s=Te(e),a=Mr.call(s.parsedDateParts,function(n){return n!=null}),r=s.overflow<0&&!s.empty&&!s.invalidEra&&!s.invalidMonth&&!s.invalidWeekday&&!s.weekdayMismatch&&!s.nullInput&&!s.invalidFormat&&!s.userInvalidated&&(!s.meridiem||s.meridiem&&a),e._strict&&(r=r&&s.charsLeftOver===0&&s.unusedTokens.length===0&&s.bigHour===void 0)),Object.isFrozen==null||!Object.isFrozen(e))e._isValid=r;else return r;return e._isValid}function Za(e){var s=Gt(NaN);return e!=null?ys(Te(s),e):Te(s).userInvalidated=!0,s}var yi=se.momentProperties=[],vr=!1;function Hr(e,s){var a,r,n,i=yi.length;if(bt(s._isAMomentObject)||(e._isAMomentObject=s._isAMomentObject),bt(s._i)||(e._i=s._i),bt(s._f)||(e._f=s._f),bt(s._l)||(e._l=s._l),bt(s._strict)||(e._strict=s._strict),bt(s._tzm)||(e._tzm=s._tzm),bt(s._isUTC)||(e._isUTC=s._isUTC),bt(s._offset)||(e._offset=s._offset),bt(s._pf)||(e._pf=Te(s)),bt(s._locale)||(e._locale=s._locale),i>0)for(a=0;a<i;a++)r=yi[a],n=s[r],bt(n)||(e[r]=n);return e}function _a(e){Hr(this,e),this._d=new Date(e._d!=null?e._d.getTime():NaN),this.isValid()||(this._d=new Date(NaN)),vr===!1&&(vr=!0,se.updateOffset(this),vr=!1)}function Ot(e){return e instanceof _a||e!=null&&e._isAMomentObject!=null}function Vi(e){se.suppressDeprecationWarnings===!1&&typeof console<"u"&&console.warn&&console.warn("Deprecation warning: "+e)}function qt(e,s){var a=!0;return ys(function(){if(se.deprecationHandler!=null&&se.deprecationHandler(null,e),a){var r=[],n,i,l,u=arguments.length;for(i=0;i<u;i++){if(n="",typeof arguments[i]=="object"){n+=`
92[`+i+"] ";for(l in arguments[0])Re(arguments[0],l)&&(n+=l+": "+arguments[0][l]+", ");n=n.slice(0,-2)}else n=arguments[i];r.push(n)}Vi(e+`
93Arguments: `+Array.prototype.slice.call(r).join("")+`
94`+new Error().stack),a=!1}return s.apply(this,arguments)},s)}var _i={};function Gi(e,s){se.deprecationHandler!=null&&se.deprecationHandler(e,s),_i[e]||(Vi(s),_i[e]=!0)}se.suppressDeprecationWarnings=!1;se.deprecationHandler=null;function Kt(e){return typeof Function<"u"&&e instanceof Function||Object.prototype.toString.call(e)==="[object Function]"}function _d(e){var s,a;for(a in e)Re(e,a)&&(s=e[a],Kt(s)?this[a]=s:this["_"+a]=s);this._config=e,this._dayOfMonthOrdinalParseLenient=new RegExp((this._dayOfMonthOrdinalParse.source||this._ordinalParse.source)+"|"+/\d{1,2}/.source)}function Dr(e,s){var a=ys({},e),r;for(r in s)Re(s,r)&&(Ts(e[r])&&Ts(s[r])?(a[r]={},ys(a[r],e[r]),ys(a[r],s[r])):s[r]!=null?a[r]=s[r]:delete a[r]);for(r in e)Re(e,r)&&!Re(s,r)&&Ts(e[r])&&(a[r]=ys({},a[r]));return a}function Br(e){e!=null&&this.set(e)}var Pr;Object.keys?Pr=Object.keys:Pr=function(e){var s,a=[];for(s in e)Re(e,s)&&a.push(s);return a};var bd={sameDay:"[Today at] LT",nextDay:"[Tomorrow at] LT",nextWeek:"dddd [at] LT",lastDay:"[Yesterday at] LT",lastWeek:"[Last] dddd [at] LT",sameElse:"L"};function jd(e,s,a){var r=this._calendar[e]||this._calendar.sameElse;return Kt(r)?r.call(s,a):r}function Vt(e,s,a){var r=""+Math.abs(e),n=s-r.length,i=e>=0;return(i?a?"+":"":"-")+Math.pow(10,Math.max(0,n)).toString().substr(1)+r}var Vr=/(\[[^\[]*\])|(\\)?([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,Da=/(\[[^\[]*\])|(\\)?(LTS|LT|LL?L?L?|l{1,4})/g,Nr={},Ws={};function he(e,s,a,r){var n=r;typeof r=="string"&&(n=function(){return this[r]()}),e&&(Ws[e]=n),s&&(Ws[s[0]]=function(){return Vt(n.apply(this,arguments),s[1],s[2])}),a&&(Ws[a]=function(){return this.localeData().ordinal(n.apply(this,arguments),e)})}function wd(e){return e.match(/\[[\s\S]/)?e.replace(/^\[|\]$/g,""):e.replace(/\\/g,"")}function vd(e){var s=e.match(Vr),a,r;for(a=0,r=s.length;a<r;a++)Ws[s[a]]?s[a]=Ws[s[a]]:s[a]=wd(s[a]);return function(n){var i="",l;for(l=0;l<r;l++)i+=Kt(s[l])?s[l].call(n,e):s[l];return i}}function qa(e,s){return e.isValid()?(s=Ki(s,e.localeData()),Nr[s]=Nr[s]||vd(s),Nr[s](e)):e.localeData().invalidDate()}function Ki(e,s){var a=5;function r(n){return s.longDateFormat(n)||n}for(Da.lastIndex=0;a>=0&&Da.test(e);)e=e.replace(Da,r),Da.lastIndex=0,a-=1;return e}var Nd={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 kd(e){var s=this._longDateFormat[e],a=this._longDateFormat[e.toUpperCase()];return s||!a?s:(this._longDateFormat[e]=a.match(Vr).map(function(r){return r==="MMMM"||r==="MM"||r==="DD"||r==="dddd"?r.slice(1):r}).join(""),this._longDateFormat[e])}var Sd="Invalid date";function Cd(){return this._invalidDate}var Md="%d",Dd=/\d{1,2}/;function Pd(e){return this._ordinal.replace("%d",e)}var Td={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 qd(e,s,a,r){var n=this._relativeTime[a];return Kt(n)?n(e,s,a,r):n.replace(/%d/i,e)}function Fd(e,s){var a=this._relativeTime[e>0?"future":"past"];return Kt(a)?a(s):a.replace(/%s/i,s)}var bi={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 Ft(e){return typeof e=="string"?bi[e]||bi[e.toLowerCase()]:void 0}function Gr(e){var s={},a,r;for(r in e)Re(e,r)&&(a=Ft(r),a&&(s[a]=e[r]));return s}var Ld={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 Ad(e){var s=[],a;for(a in e)Re(e,a)&&s.push({unit:a,priority:Ld[a]});return s.sort(function(r,n){return r.priority-n.priority}),s}var Zi=/\d/,kt=/\d\d/,Xi=/\d{3}/,Kr=/\d{4}/,Xa=/[+-]?\d{6}/,Qe=/\d\d?/,Ji=/\d\d\d\d?/,Qi=/\d\d\d\d\d\d?/,Ja=/\d{1,3}/,Zr=/\d{1,4}/,Qa=/[+-]?\d{1,6}/,Vs=/\d+/,er=/[+-]?\d+/,$d=/Z|[+-]\d\d:?\d\d/gi,tr=/Z|[+-]\d\d(?::?\d\d)?/gi,Od=/[+-]?\d+(\.\d{1,3})?/,ba=/[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,Gs=/^[1-9]\d?/,Xr=/^([1-9]\d|\d)/,Ra;Ra={};function re(e,s,a){Ra[e]=Kt(s)?s:function(r,n){return r&&a?a:s}}function Yd(e,s){return Re(Ra,e)?Ra[e](s._strict,s._locale):new RegExp(Rd(e))}function Rd(e){return ls(e.replace("\\","").replace(/\\(\[)|\\(\])|\[([^\]\[]*)\]|\\(.)/g,function(s,a,r,n,i){return a||r||n||i}))}function ls(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")}function Pt(e){return e<0?Math.ceil(e)||0:Math.floor(e)}function Le(e){var s=+e,a=0;return s!==0&&isFinite(s)&&(a=Pt(s)),a}var Tr={};function Be(e,s){var a,r=s,n;for(typeof e=="string"&&(e=[e]),cs(s)&&(r=function(i,l){l[s]=Le(i)}),n=e.length,a=0;a<n;a++)Tr[e[a]]=r}function ja(e,s){Be(e,function(a,r,n,i){n._w=n._w||{},s(a,n._w,n,i)})}function Id(e,s,a){s!=null&&Re(Tr,e)&&Tr[e](s,a._a,a,e)}function sr(e){return e%4===0&&e%100!==0||e%400===0}var xt=0,ns=1,Et=2,ht=3,At=4,is=5,Ds=6,Ed=7,Wd=8;he("Y",0,0,function(){var e=this.year();return e<=9999?Vt(e,4):"+"+e});he(0,["YY",2],0,function(){return this.year()%100});he(0,["YYYY",4],0,"year");he(0,["YYYYY",5],0,"year");he(0,["YYYYYY",6,!0],0,"year");re("Y",er);re("YY",Qe,kt);re("YYYY",Zr,Kr);re("YYYYY",Qa,Xa);re("YYYYYY",Qa,Xa);Be(["YYYYY","YYYYYY"],xt);Be("YYYY",function(e,s){s[xt]=e.length===2?se.parseTwoDigitYear(e):Le(e)});Be("YY",function(e,s){s[xt]=se.parseTwoDigitYear(e)});Be("Y",function(e,s){s[xt]=parseInt(e,10)});function oa(e){return sr(e)?366:365}se.parseTwoDigitYear=function(e){return Le(e)+(Le(e)>68?1900:2e3)};var el=Ks("FullYear",!0);function zd(){return sr(this.year())}function Ks(e,s){return function(a){return a!=null?(tl(this,e,a),se.updateOffset(this,s),this):ma(this,e)}}function ma(e,s){if(!e.isValid())return NaN;var a=e._d,r=e._isUTC;switch(s){case"Milliseconds":return r?a.getUTCMilliseconds():a.getMilliseconds();case"Seconds":return r?a.getUTCSeconds():a.getSeconds();case"Minutes":return r?a.getUTCMinutes():a.getMinutes();case"Hours":return r?a.getUTCHours():a.getHours();case"Date":return r?a.getUTCDate():a.getDate();case"Day":return r?a.getUTCDay():a.getDay();case"Month":return r?a.getUTCMonth():a.getMonth();case"FullYear":return r?a.getUTCFullYear():a.getFullYear();default:return NaN}}function tl(e,s,a){var r,n,i,l,u;if(!(!e.isValid()||isNaN(a))){switch(r=e._d,n=e._isUTC,s){case"Milliseconds":return void(n?r.setUTCMilliseconds(a):r.setMilliseconds(a));case"Seconds":return void(n?r.setUTCSeconds(a):r.setSeconds(a));case"Minutes":return void(n?r.setUTCMinutes(a):r.setMinutes(a));case"Hours":return void(n?r.setUTCHours(a):r.setHours(a));case"Date":return void(n?r.setUTCDate(a):r.setDate(a));case"FullYear":break;default:return}i=a,l=e.month(),u=e.date(),u=u===29&&l===1&&!sr(i)?28:u,n?r.setUTCFullYear(i,l,u):r.setFullYear(i,l,u)}}function Ud(e){return e=Ft(e),Kt(this[e])?this[e]():this}function Hd(e,s){if(typeof e=="object"){e=Gr(e);var a=Ad(e),r,n=a.length;for(r=0;r<n;r++)this[a[r].unit](e[a[r].unit])}else if(e=Ft(e),Kt(this[e]))return this[e](s);return this}function Bd(e,s){return(e%s+s)%s}var ct;Array.prototype.indexOf?ct=Array.prototype.indexOf:ct=function(e){var s;for(s=0;s<this.length;++s)if(this[s]===e)return s;return-1};function Jr(e,s){if(isNaN(e)||isNaN(s))return NaN;var a=Bd(s,12);return e+=(s-a)/12,a===1?sr(e)?29:28:31-a%7%2}he("M",["MM",2],"Mo",function(){return this.month()+1});he("MMM",0,0,function(e){return this.localeData().monthsShort(this,e)});he("MMMM",0,0,function(e){return this.localeData().months(this,e)});re("M",Qe,Gs);re("MM",Qe,kt);re("MMM",function(e,s){return s.monthsShortRegex(e)});re("MMMM",function(e,s){return s.monthsRegex(e)});Be(["M","MM"],function(e,s){s[ns]=Le(e)-1});Be(["MMM","MMMM"],function(e,s,a,r){var n=a._locale.monthsParse(e,r,a._strict);n!=null?s[ns]=n:Te(a).invalidMonth=e});var Vd="January_February_March_April_May_June_July_August_September_October_November_December".split("_"),sl="Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"),al=/D[oD]?(\[[^\[\]]*\]|\s)+MMMM?/,Gd=ba,Kd=ba;function Zd(e,s){return e?$t(this._months)?this._months[e.month()]:this._months[(this._months.isFormat||al).test(s)?"format":"standalone"][e.month()]:$t(this._months)?this._months:this._months.standalone}function Xd(e,s){return e?$t(this._monthsShort)?this._monthsShort[e.month()]:this._monthsShort[al.test(s)?"format":"standalone"][e.month()]:$t(this._monthsShort)?this._monthsShort:this._monthsShort.standalone}function Jd(e,s,a){var r,n,i,l=e.toLocaleLowerCase();if(!this._monthsParse)for(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[],r=0;r<12;++r)i=Gt([2e3,r]),this._shortMonthsParse[r]=this.monthsShort(i,"").toLocaleLowerCase(),this._longMonthsParse[r]=this.months(i,"").toLocaleLowerCase();return a?s==="MMM"?(n=ct.call(this._shortMonthsParse,l),n!==-1?n:null):(n=ct.call(this._longMonthsParse,l),n!==-1?n:null):s==="MMM"?(n=ct.call(this._shortMonthsParse,l),n!==-1?n:(n=ct.call(this._longMonthsParse,l),n!==-1?n:null)):(n=ct.call(this._longMonthsParse,l),n!==-1?n:(n=ct.call(this._shortMonthsParse,l),n!==-1?n:null))}function Qd(e,s,a){var r,n,i;if(this._monthsParseExact)return Jd.call(this,e,s,a);for(this._monthsParse||(this._monthsParse=[],this._longMonthsParse=[],this._shortMonthsParse=[]),r=0;r<12;r++){if(n=Gt([2e3,r]),a&&!this._longMonthsParse[r]&&(this._longMonthsParse[r]=new RegExp("^"+this.months(n,"").replace(".","")+"$","i"),this._shortMonthsParse[r]=new RegExp("^"+this.monthsShort(n,"").replace(".","")+"$","i")),!a&&!this._monthsParse[r]&&(i="^"+this.months(n,"")+"|^"+this.monthsShort(n,""),this._monthsParse[r]=new RegExp(i.replace(".",""),"i")),a&&s==="MMMM"&&this._longMonthsParse[r].test(e))return r;if(a&&s==="MMM"&&this._shortMonthsParse[r].test(e))return r;if(!a&&this._monthsParse[r].test(e))return r}}function rl(e,s){if(!e.isValid())return e;if(typeof s=="string"){if(/^\d+$/.test(s))s=Le(s);else if(s=e.localeData().monthsParse(s),!cs(s))return e}var a=s,r=e.date();return r=r<29?r:Math.min(r,Jr(e.year(),a)),e._isUTC?e._d.setUTCMonth(a,r):e._d.setMonth(a,r),e}function nl(e){return e!=null?(rl(this,e),se.updateOffset(this,!0),this):ma(this,"Month")}function eu(){return Jr(this.year(),this.month())}function tu(e){return this._monthsParseExact?(Re(this,"_monthsRegex")||il.call(this),e?this._monthsShortStrictRegex:this._monthsShortRegex):(Re(this,"_monthsShortRegex")||(this._monthsShortRegex=Gd),this._monthsShortStrictRegex&&e?this._monthsShortStrictRegex:this._monthsShortRegex)}function su(e){return this._monthsParseExact?(Re(this,"_monthsRegex")||il.call(this),e?this._monthsStrictRegex:this._monthsRegex):(Re(this,"_monthsRegex")||(this._monthsRegex=Kd),this._monthsStrictRegex&&e?this._monthsStrictRegex:this._monthsRegex)}function il(){function e(c,d){return d.length-c.length}var s=[],a=[],r=[],n,i,l,u;for(n=0;n<12;n++)i=Gt([2e3,n]),l=ls(this.monthsShort(i,"")),u=ls(this.months(i,"")),s.push(l),a.push(u),r.push(u),r.push(l);s.sort(e),a.sort(e),r.sort(e),this._monthsRegex=new RegExp("^("+r.join("|")+")","i"),this._monthsShortRegex=this._monthsRegex,this._monthsStrictRegex=new RegExp("^("+a.join("|")+")","i"),this._monthsShortStrictRegex=new RegExp("^("+s.join("|")+")","i")}function au(e,s,a,r,n,i,l){var u;return e<100&&e>=0?(u=new Date(e+400,s,a,r,n,i,l),isFinite(u.getFullYear())&&u.setFullYear(e)):u=new Date(e,s,a,r,n,i,l),u}function ha(e){var s,a;return e<100&&e>=0?(a=Array.prototype.slice.call(arguments),a[0]=e+400,s=new Date(Date.UTC.apply(null,a)),isFinite(s.getUTCFullYear())&&s.setUTCFullYear(e)):s=new Date(Date.UTC.apply(null,arguments)),s}function Ia(e,s,a){var r=7+s-a,n=(7+ha(e,0,r).getUTCDay()-s)%7;return-n+r-1}function ll(e,s,a,r,n){var i=(7+a-r)%7,l=Ia(e,r,n),u=1+7*(s-1)+i+l,c,d;return u<=0?(c=e-1,d=oa(c)+u):u>oa(e)?(c=e+1,d=u-oa(e)):(c=e,d=u),{year:c,dayOfYear:d}}function fa(e,s,a){var r=Ia(e.year(),s,a),n=Math.floor((e.dayOfYear()-r-1)/7)+1,i,l;return n<1?(l=e.year()-1,i=n+os(l,s,a)):n>os(e.year(),s,a)?(i=n-os(e.year(),s,a),l=e.year()+1):(l=e.year(),i=n),{week:i,year:l}}function os(e,s,a){var r=Ia(e,s,a),n=Ia(e+1,s,a);return(oa(e)-r+n)/7}he("w",["ww",2],"wo","week");he("W",["WW",2],"Wo","isoWeek");re("w",Qe,Gs);re("ww",Qe,kt);re("W",Qe,Gs);re("WW",Qe,kt);ja(["w","ww","W","WW"],function(e,s,a,r){s[r.substr(0,1)]=Le(e)});function ru(e){return fa(e,this._week.dow,this._week.doy).week}var nu={dow:0,doy:6};function iu(){return this._week.dow}function lu(){return this._week.doy}function ou(e){var s=this.localeData().week(this);return e==null?s:this.add((e-s)*7,"d")}function cu(e){var s=fa(this,1,4).week;return e==null?s:this.add((e-s)*7,"d")}he("d",0,"do","day");he("dd",0,0,function(e){return this.localeData().weekdaysMin(this,e)});he("ddd",0,0,function(e){return this.localeData().weekdaysShort(this,e)});he("dddd",0,0,function(e){return this.localeData().weekdays(this,e)});he("e",0,0,"weekday");he("E",0,0,"isoWeekday");re("d",Qe);re("e",Qe);re("E",Qe);re("dd",function(e,s){return s.weekdaysMinRegex(e)});re("ddd",function(e,s){return s.weekdaysShortRegex(e)});re("dddd",function(e,s){return s.weekdaysRegex(e)});ja(["dd","ddd","dddd"],function(e,s,a,r){var n=a._locale.weekdaysParse(e,r,a._strict);n!=null?s.d=n:Te(a).invalidWeekday=e});ja(["d","e","E"],function(e,s,a,r){s[r]=Le(e)});function du(e,s){return typeof e!="string"?e:isNaN(e)?(e=s.weekdaysParse(e),typeof e=="number"?e:null):parseInt(e,10)}function uu(e,s){return typeof e=="string"?s.weekdaysParse(e)%7||7:isNaN(e)?null:e}function Qr(e,s){return e.slice(s,7).concat(e.slice(0,s))}var mu="Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"),ol="Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"),hu="Su_Mo_Tu_We_Th_Fr_Sa".split("_"),fu=ba,pu=ba,xu=ba;function gu(e,s){var a=$t(this._weekdays)?this._weekdays:this._weekdays[e&&e!==!0&&this._weekdays.isFormat.test(s)?"format":"standalone"];return e===!0?Qr(a,this._week.dow):e?a[e.day()]:a}function yu(e){return e===!0?Qr(this._weekdaysShort,this._week.dow):e?this._weekdaysShort[e.day()]:this._weekdaysShort}function _u(e){return e===!0?Qr(this._weekdaysMin,this._week.dow):e?this._weekdaysMin[e.day()]:this._weekdaysMin}function bu(e,s,a){var r,n,i,l=e.toLocaleLowerCase();if(!this._weekdaysParse)for(this._weekdaysParse=[],this._shortWeekdaysParse=[],this._minWeekdaysParse=[],r=0;r<7;++r)i=Gt([2e3,1]).day(r),this._minWeekdaysParse[r]=this.weekdaysMin(i,"").toLocaleLowerCase(),this._shortWeekdaysParse[r]=this.weekdaysShort(i,"").toLocaleLowerCase(),this._weekdaysParse[r]=this.weekdays(i,"").toLocaleLowerCase();return a?s==="dddd"?(n=ct.call(this._weekdaysParse,l),n!==-1?n:null):s==="ddd"?(n=ct.call(this._shortWeekdaysParse,l),n!==-1?n:null):(n=ct.call(this._minWeekdaysParse,l),n!==-1?n:null):s==="dddd"?(n=ct.call(this._weekdaysParse,l),n!==-1||(n=ct.call(this._shortWeekdaysParse,l),n!==-1)?n:(n=ct.call(this._minWeekdaysParse,l),n!==-1?n:null)):s==="ddd"?(n=ct.call(this._shortWeekdaysParse,l),n!==-1||(n=ct.call(this._weekdaysParse,l),n!==-1)?n:(n=ct.call(this._minWeekdaysParse,l),n!==-1?n:null)):(n=ct.call(this._minWeekdaysParse,l),n!==-1||(n=ct.call(this._weekdaysParse,l),n!==-1)?n:(n=ct.call(this._shortWeekdaysParse,l),n!==-1?n:null))}function ju(e,s,a){var r,n,i;if(this._weekdaysParseExact)return bu.call(this,e,s,a);for(this._weekdaysParse||(this._weekdaysParse=[],this._minWeekdaysParse=[],this._shortWeekdaysParse=[],this._fullWeekdaysParse=[]),r=0;r<7;r++){if(n=Gt([2e3,1]).day(r),a&&!this._fullWeekdaysParse[r]&&(this._fullWeekdaysParse[r]=new RegExp("^"+this.weekdays(n,"").replace(".","\\.?")+"$","i"),this._shortWeekdaysParse[r]=new RegExp("^"+this.weekdaysShort(n,"").replace(".","\\.?")+"$","i"),this._minWeekdaysParse[r]=new RegExp("^"+this.weekdaysMin(n,"").replace(".","\\.?")+"$","i")),this._weekdaysParse[r]||(i="^"+this.weekdays(n,"")+"|^"+this.weekdaysShort(n,"")+"|^"+this.weekdaysMin(n,""),this._weekdaysParse[r]=new RegExp(i.replace(".",""),"i")),a&&s==="dddd"&&this._fullWeekdaysParse[r].test(e))return r;if(a&&s==="ddd"&&this._shortWeekdaysParse[r].test(e))return r;if(a&&s==="dd"&&this._minWeekdaysParse[r].test(e))return r;if(!a&&this._weekdaysParse[r].test(e))return r}}function wu(e){if(!this.isValid())return e!=null?this:NaN;var s=ma(this,"Day");return e!=null?(e=du(e,this.localeData()),this.add(e-s,"d")):s}function vu(e){if(!this.isValid())return e!=null?this:NaN;var s=(this.day()+7-this.localeData()._week.dow)%7;return e==null?s:this.add(e-s,"d")}function Nu(e){if(!this.isValid())return e!=null?this:NaN;if(e!=null){var s=uu(e,this.localeData());return this.day(this.day()%7?s:s-7)}else return this.day()||7}function ku(e){return this._weekdaysParseExact?(Re(this,"_weekdaysRegex")||en.call(this),e?this._weekdaysStrictRegex:this._weekdaysRegex):(Re(this,"_weekdaysRegex")||(this._weekdaysRegex=fu),this._weekdaysStrictRegex&&e?this._weekdaysStrictRegex:this._weekdaysRegex)}function Su(e){return this._weekdaysParseExact?(Re(this,"_weekdaysRegex")||en.call(this),e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex):(Re(this,"_weekdaysShortRegex")||(this._weekdaysShortRegex=pu),this._weekdaysShortStrictRegex&&e?this._weekdaysShortStrictRegex:this._weekdaysShortRegex)}function Cu(e){return this._weekdaysParseExact?(Re(this,"_weekdaysRegex")||en.call(this),e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex):(Re(this,"_weekdaysMinRegex")||(this._weekdaysMinRegex=xu),this._weekdaysMinStrictRegex&&e?this._weekdaysMinStrictRegex:this._weekdaysMinRegex)}function en(){function e(j,w){return w.length-j.length}var s=[],a=[],r=[],n=[],i,l,u,c,d;for(i=0;i<7;i++)l=Gt([2e3,1]).day(i),u=ls(this.weekdaysMin(l,"")),c=ls(this.weekdaysShort(l,"")),d=ls(this.weekdays(l,"")),s.push(u),a.push(c),r.push(d),n.push(u),n.push(c),n.push(d);s.sort(e),a.sort(e),r.sort(e),n.sort(e),this._weekdaysRegex=new RegExp("^("+n.join("|")+")","i"),this._weekdaysShortRegex=this._weekdaysRegex,this._weekdaysMinRegex=this._weekdaysRegex,this._weekdaysStrictRegex=new RegExp("^("+r.join("|")+")","i"),this._weekdaysShortStrictRegex=new RegExp("^("+a.join("|")+")","i"),this._weekdaysMinStrictRegex=new RegExp("^("+s.join("|")+")","i")}function tn(){return this.hours()%12||12}function Mu(){return this.hours()||24}he("H",["HH",2],0,"hour");he("h",["hh",2],0,tn);he("k",["kk",2],0,Mu);he("hmm",0,0,function(){return""+tn.apply(this)+Vt(this.minutes(),2)});he("hmmss",0,0,function(){return""+tn.apply(this)+Vt(this.minutes(),2)+Vt(this.seconds(),2)});he("Hmm",0,0,function(){return""+this.hours()+Vt(this.minutes(),2)});he("Hmmss",0,0,function(){return""+this.hours()+Vt(this.minutes(),2)+Vt(this.seconds(),2)});function cl(e,s){he(e,0,0,function(){return this.localeData().meridiem(this.hours(),this.minutes(),s)})}cl("a",!0);cl("A",!1);function dl(e,s){return s._meridiemParse}re("a",dl);re("A",dl);re("H",Qe,Xr);re("h",Qe,Gs);re("k",Qe,Gs);re("HH",Qe,kt);re("hh",Qe,kt);re("kk",Qe,kt);re("hmm",Ji);re("hmmss",Qi);re("Hmm",Ji);re("Hmmss",Qi);Be(["H","HH"],ht);Be(["k","kk"],function(e,s,a){var r=Le(e);s[ht]=r===24?0:r});Be(["a","A"],function(e,s,a){a._isPm=a._locale.isPM(e),a._meridiem=e});Be(["h","hh"],function(e,s,a){s[ht]=Le(e),Te(a).bigHour=!0});Be("hmm",function(e,s,a){var r=e.length-2;s[ht]=Le(e.substr(0,r)),s[At]=Le(e.substr(r)),Te(a).bigHour=!0});Be("hmmss",function(e,s,a){var r=e.length-4,n=e.length-2;s[ht]=Le(e.substr(0,r)),s[At]=Le(e.substr(r,2)),s[is]=Le(e.substr(n)),Te(a).bigHour=!0});Be("Hmm",function(e,s,a){var r=e.length-2;s[ht]=Le(e.substr(0,r)),s[At]=Le(e.substr(r))});Be("Hmmss",function(e,s,a){var r=e.length-4,n=e.length-2;s[ht]=Le(e.substr(0,r)),s[At]=Le(e.substr(r,2)),s[is]=Le(e.substr(n))});function Du(e){return(e+"").toLowerCase().charAt(0)==="p"}var Pu=/[ap]\.?m?\.?/i,Tu=Ks("Hours",!0);function qu(e,s,a){return e>11?a?"pm":"PM":a?"am":"AM"}var ul={calendar:bd,longDateFormat:Nd,invalidDate:Sd,ordinal:Md,dayOfMonthOrdinalParse:Dd,relativeTime:Td,months:Vd,monthsShort:sl,week:nu,weekdays:mu,weekdaysMin:hu,weekdaysShort:ol,meridiemParse:Pu},st={},na={},pa;function Fu(e,s){var a,r=Math.min(e.length,s.length);for(a=0;a<r;a+=1)if(e[a]!==s[a])return a;return r}function ji(e){return e&&e.toLowerCase().replace("_","-")}function Lu(e){for(var s=0,a,r,n,i;s<e.length;){for(i=ji(e[s]).split("-"),a=i.length,r=ji(e[s+1]),r=r?r.split("-"):null;a>0;){if(n=ar(i.slice(0,a).join("-")),n)return n;if(r&&r.length>=a&&Fu(i,r)>=a-1)break;a--}s++}return pa}function Au(e){return!!(e&&e.match("^[^/\\\\]*$"))}function ar(e){var s=null,a;if(st[e]===void 0&&typeof module<"u"&&module&&module.exports&&Au(e))try{s=pa._abbr,a=require,a("./locale/"+e),bs(s)}catch{st[e]=null}return st[e]}function bs(e,s){var a;return e&&(bt(s)?a=ds(e):a=sn(e,s),a?pa=a:typeof console<"u"&&console.warn&&console.warn("Locale "+e+" not found. Did you forget to load it?")),pa._abbr}function sn(e,s){if(s!==null){var a,r=ul;if(s.abbr=e,st[e]!=null)Gi("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."),r=st[e]._config;else if(s.parentLocale!=null)if(st[s.parentLocale]!=null)r=st[s.parentLocale]._config;else if(a=ar(s.parentLocale),a!=null)r=a._config;else return na[s.parentLocale]||(na[s.parentLocale]=[]),na[s.parentLocale].push({name:e,config:s}),null;
vendor: 14,217 bytes, line 94
94return st[e]=new Br(Dr(r,s)),na[e]&&na[e].forEach(function(n){sn(n.name,n.config)}),bs(e),st[e]}else return delete st[e],null}function $u(e,s){if(s!=null){var a,r,n=ul;st[e]!=null&&st[e].parentLocale!=null?st[e].set(Dr(st[e]._config,s)):(r=ar(e),r!=null&&(n=r._config),s=Dr(n,s),r==null&&(s.abbr=e),a=new Br(s),a.parentLocale=st[e],st[e]=a),bs(e)}else st[e]!=null&&(st[e].parentLocale!=null?(st[e]=st[e].parentLocale,e===bs()&&bs(e)):st[e]!=null&&delete st[e]);return st[e]}function ds(e){var s;if(e&&e._locale&&e._locale._abbr&&(e=e._locale._abbr),!e)return pa;if(!$t(e)){if(s=ar(e),s)return s;e=[e]}return Lu(e)}function Ou(){return Pr(st)}function an(e){var s,a=e._a;return a&&Te(e).overflow===-2&&(s=a[ns]<0||a[ns]>11?ns:a[Et]<1||a[Et]>Jr(a[xt],a[ns])?Et:a[ht]<0||a[ht]>24||a[ht]===24&&(a[At]!==0||a[is]!==0||a[Ds]!==0)?ht:a[At]<0||a[At]>59?At:a[is]<0||a[is]>59?is:a[Ds]<0||a[Ds]>999?Ds:-1,Te(e)._overflowDayOfYear&&(s<xt||s>Et)&&(s=Et),Te(e)._overflowWeeks&&s===-1&&(s=Ed),Te(e)._overflowWeekday&&s===-1&&(s=Wd),Te(e).overflow=s),e}var Yu=/^\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)?)?$/,Ru=/^\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)?)?$/,Iu=/Z|[+-]\d\d(?::?\d\d)?/,Pa=[["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]],kr=[["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/]],Eu=/^\/?Date\((-?\d+)/i,Wu=/^(?:(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}))$/,zu={UT:0,GMT:0,EDT:-240,EST:-300,CDT:-300,CST:-360,MDT:-360,MST:-420,PDT:-420,PST:-480};function ml(e){var s,a,r=e._i,n=Yu.exec(r)||Ru.exec(r),i,l,u,c,d=Pa.length,j=kr.length;if(n){for(Te(e).iso=!0,s=0,a=d;s<a;s++)if(Pa[s][1].exec(n[1])){l=Pa[s][0],i=Pa[s][2]!==!1;break}if(l==null){e._isValid=!1;return}if(n[3]){for(s=0,a=j;s<a;s++)if(kr[s][1].exec(n[3])){u=(n[2]||" ")+kr[s][0];break}if(u==null){e._isValid=!1;return}}if(!i&&u!=null){e._isValid=!1;return}if(n[4])if(Iu.exec(n[4]))c="Z";else{e._isValid=!1;return}e._f=l+(u||"")+(c||""),nn(e)}else e._isValid=!1}function Uu(e,s,a,r,n,i){var l=[Hu(e),sl.indexOf(s),parseInt(a,10),parseInt(r,10),parseInt(n,10)];return i&&l.push(parseInt(i,10)),l}function Hu(e){var s=parseInt(e,10);return s<=49?2e3+s:s<=999?1900+s:s}function Bu(e){return e.replace(/\([^()]*\)|[\n\t]/g," ").replace(/(\s\s+)/g," ").replace(/^\s\s*/,"").replace(/\s\s*$/,"")}function Vu(e,s,a){if(e){var r=ol.indexOf(e),n=new Date(s[0],s[1],s[2]).getDay();if(r!==n)return Te(a).weekdayMismatch=!0,a._isValid=!1,!1}return!0}function Gu(e,s,a){if(e)return zu[e];if(s)return 0;var r=parseInt(a,10),n=r%100,i=(r-n)/100;return i*60+n}function hl(e){var s=Wu.exec(Bu(e._i)),a;if(s){if(a=Uu(s[4],s[3],s[2],s[5],s[6],s[7]),!Vu(s[1],a,e))return;e._a=a,e._tzm=Gu(s[8],s[9],s[10]),e._d=ha.apply(null,e._a),e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),Te(e).rfc2822=!0}else e._isValid=!1}function Ku(e){var s=Eu.exec(e._i);if(s!==null){e._d=new Date(+s[1]);return}if(ml(e),e._isValid===!1)delete e._isValid;else return;if(hl(e),e._isValid===!1)delete e._isValid;else return;e._strict?e._isValid=!1:se.createFromInputFallback(e)}se.createFromInputFallback=qt("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 Ys(e,s,a){return e??s??a}function Zu(e){var s=new Date(se.now());return e._useUTC?[s.getUTCFullYear(),s.getUTCMonth(),s.getUTCDate()]:[s.getFullYear(),s.getMonth(),s.getDate()]}function rn(e){var s,a,r=[],n,i,l;if(!e._d){for(n=Zu(e),e._w&&e._a[Et]==null&&e._a[ns]==null&&Xu(e),e._dayOfYear!=null&&(l=Ys(e._a[xt],n[xt]),(e._dayOfYear>oa(l)||e._dayOfYear===0)&&(Te(e)._overflowDayOfYear=!0),a=ha(l,0,e._dayOfYear),e._a[ns]=a.getUTCMonth(),e._a[Et]=a.getUTCDate()),s=0;s<3&&e._a[s]==null;++s)e._a[s]=r[s]=n[s];for(;s<7;s++)e._a[s]=r[s]=e._a[s]==null?s===2?1:0:e._a[s];e._a[ht]===24&&e._a[At]===0&&e._a[is]===0&&e._a[Ds]===0&&(e._nextDay=!0,e._a[ht]=0),e._d=(e._useUTC?ha:au).apply(null,r),i=e._useUTC?e._d.getUTCDay():e._d.getDay(),e._tzm!=null&&e._d.setUTCMinutes(e._d.getUTCMinutes()-e._tzm),e._nextDay&&(e._a[ht]=24),e._w&&typeof e._w.d<"u"&&e._w.d!==i&&(Te(e).weekdayMismatch=!0)}}function Xu(e){var s,a,r,n,i,l,u,c,d;s=e._w,s.GG!=null||s.W!=null||s.E!=null?(i=1,l=4,a=Ys(s.GG,e._a[xt],fa(Je(),1,4).year),r=Ys(s.W,1),n=Ys(s.E,1),(n<1||n>7)&&(c=!0)):(i=e._locale._week.dow,l=e._locale._week.doy,d=fa(Je(),i,l),a=Ys(s.gg,e._a[xt],d.year),r=Ys(s.w,d.week),s.d!=null?(n=s.d,(n<0||n>6)&&(c=!0)):s.e!=null?(n=s.e+i,(s.e<0||s.e>6)&&(c=!0)):n=i),r<1||r>os(a,i,l)?Te(e)._overflowWeeks=!0:c!=null?Te(e)._overflowWeekday=!0:(u=ll(a,r,n,i,l),e._a[xt]=u.year,e._dayOfYear=u.dayOfYear)}se.ISO_8601=function(){};se.RFC_2822=function(){};function nn(e){if(e._f===se.ISO_8601){ml(e);return}if(e._f===se.RFC_2822){hl(e);return}e._a=[],Te(e).empty=!0;var s=""+e._i,a,r,n,i,l,u=s.length,c=0,d,j;for(n=Ki(e._f,e._locale).match(Vr)||[],j=n.length,a=0;a<j;a++)i=n[a],r=(s.match(Yd(i,e))||[])[0],r&&(l=s.substr(0,s.indexOf(r)),l.length>0&&Te(e).unusedInput.push(l),s=s.slice(s.indexOf(r)+r.length),c+=r.length),Ws[i]?(r?Te(e).empty=!1:Te(e).unusedTokens.push(i),Id(i,r,e)):e._strict&&!r&&Te(e).unusedTokens.push(i);Te(e).charsLeftOver=u-c,s.length>0&&Te(e).unusedInput.push(s),e._a[ht]<=12&&Te(e).bigHour===!0&&e._a[ht]>0&&(Te(e).bigHour=void 0),Te(e).parsedDateParts=e._a.slice(0),Te(e).meridiem=e._meridiem,e._a[ht]=Ju(e._locale,e._a[ht],e._meridiem),d=Te(e).era,d!==null&&(e._a[xt]=e._locale.erasConvertYear(d,e._a[xt])),rn(e),an(e)}function Ju(e,s,a){var r;return a==null?s:e.meridiemHour!=null?e.meridiemHour(s,a):(e.isPM!=null&&(r=e.isPM(a),r&&s<12&&(s+=12),!r&&s===12&&(s=0)),s)}function Qu(e){var s,a,r,n,i,l,u=!1,c=e._f.length;if(c===0){Te(e).invalidFormat=!0,e._d=new Date(NaN);return}for(n=0;n<c;n++)i=0,l=!1,s=Hr({},e),e._useUTC!=null&&(s._useUTC=e._useUTC),s._f=e._f[n],nn(s),Ur(s)&&(l=!0),i+=Te(s).charsLeftOver,i+=Te(s).unusedTokens.length*10,Te(s).score=i,u?i<r&&(r=i,a=s):(r==null||i<r||l)&&(r=i,a=s,l&&(u=!0));ys(e,a||s)}function em(e){if(!e._d){var s=Gr(e._i),a=s.day===void 0?s.date:s.day;e._a=Bi([s.year,s.month,a,s.hour,s.minute,s.second,s.millisecond],function(r){return r&&parseInt(r,10)}),rn(e)}}function tm(e){var s=new _a(an(fl(e)));return s._nextDay&&(s.add(1,"d"),s._nextDay=void 0),s}function fl(e){var s=e._i,a=e._f;return e._locale=e._locale||ds(e._l),s===null||a===void 0&&s===""?Za({nullInput:!0}):(typeof s=="string"&&(e._i=s=e._locale.preparse(s)),Ot(s)?new _a(an(s)):(ya(s)?e._d=s:$t(a)?Qu(e):a?nn(e):sm(e),Ur(e)||(e._d=null),e))}function sm(e){var s=e._i;bt(s)?e._d=new Date(se.now()):ya(s)?e._d=new Date(s.valueOf()):typeof s=="string"?Ku(e):$t(s)?(e._a=Bi(s.slice(0),function(a){return parseInt(a,10)}),rn(e)):Ts(s)?em(e):cs(s)?e._d=new Date(s):se.createFromInputFallback(e)}function pl(e,s,a,r,n){var i={};return(s===!0||s===!1)&&(r=s,s=void 0),(a===!0||a===!1)&&(r=a,a=void 0),(Ts(e)&&zr(e)||$t(e)&&e.length===0)&&(e=void 0),i._isAMomentObject=!0,i._useUTC=i._isUTC=n,i._l=a,i._i=e,i._f=s,i._strict=r,tm(i)}function Je(e,s,a,r){return pl(e,s,a,r,!1)}var am=qt("moment().min is deprecated, use moment.max instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var e=Je.apply(null,arguments);return this.isValid()&&e.isValid()?e<this?this:e:Za()}),rm=qt("moment().max is deprecated, use moment.min instead. http://momentjs.com/guides/#/warnings/min-max/",function(){var e=Je.apply(null,arguments);return this.isValid()&&e.isValid()?e>this?this:e:Za()});function xl(e,s){var a,r;if(s.length===1&&$t(s[0])&&(s=s[0]),!s.length)return Je();for(a=s[0],r=1;r<s.length;++r)(!s[r].isValid()||s[r][e](a))&&(a=s[r]);return a}function nm(){var e=[].slice.call(arguments,0);return xl("isBefore",e)}function im(){var e=[].slice.call(arguments,0);return xl("isAfter",e)}var lm=function(){return Date.now?Date.now():+new Date},ia=["year","quarter","month","week","day","hour","minute","second","millisecond"];function om(e){var s,a=!1,r,n=ia.length;for(s in e)if(Re(e,s)&&!(ct.call(ia,s)!==-1&&(e[s]==null||!isNaN(e[s]))))return!1;for(r=0;r<n;++r)if(e[ia[r]]){if(a)return!1;parseFloat(e[ia[r]])!==Le(e[ia[r]])&&(a=!0)}return!0}function cm(){return this._isValid}function dm(){return Yt(NaN)}function rr(e){var s=Gr(e),a=s.year||0,r=s.quarter||0,n=s.month||0,i=s.week||s.isoWeek||0,l=s.day||0,u=s.hour||0,c=s.minute||0,d=s.second||0,j=s.millisecond||0;this._isValid=om(s),this._milliseconds=+j+d*1e3+c*6e4+u*1e3*60*60,this._days=+l+i*7,this._months=+n+r*3+a*12,this._data={},this._locale=ds(),this._bubble()}function Fa(e){return e instanceof rr}function qr(e){return e<0?Math.round(-1*e)*-1:Math.round(e)}function um(e,s,a){var r=Math.min(e.length,s.length),n=Math.abs(e.length-s.length),i=0,l;for(l=0;l<r;l++)Le(e[l])!==Le(s[l])&&i++;return i+n}function gl(e,s){he(e,0,0,function(){var a=this.utcOffset(),r="+";return a<0&&(a=-a,r="-"),r+Vt(~~(a/60),2)+s+Vt(~~a%60,2)})}gl("Z",":");gl("ZZ","");re("Z",tr);re("ZZ",tr);Be(["Z","ZZ"],function(e,s,a){a._useUTC=!0,a._tzm=ln(tr,e)});var mm=/([\+\-]|\d\d)/gi;function ln(e,s){var a=(s||"").match(e),r,n,i;return a===null?null:(r=a[a.length-1]||[],n=(r+"").match(mm)||["-",0,0],i=+(n[1]*60)+Le(n[2]),i===0?0:n[0]==="+"?i:-i)}function on(e,s){var a,r;return s._isUTC?(a=s.clone(),r=(Ot(e)||ya(e)?e.valueOf():Je(e).valueOf())-a.valueOf(),a._d.setTime(a._d.valueOf()+r),se.updateOffset(a,!1),a):Je(e).local()}function Fr(e){return-Math.round(e._d.getTimezoneOffset())}se.updateOffset=function(){};function hm(e,s,a){var r=this._offset||0,n;if(!this.isValid())return e!=null?this:NaN;if(e!=null){if(typeof e=="string"){if(e=ln(tr,e),e===null)return this}else Math.abs(e)<16&&!a&&(e=e*60);return!this._isUTC&&s&&(n=Fr(this)),this._offset=e,this._isUTC=!0,n!=null&&this.add(n,"m"),r!==e&&(!s||this._changeInProgress?bl(this,Yt(e-r,"m"),1,!1):this._changeInProgress||(this._changeInProgress=!0,se.updateOffset(this,!0),this._changeInProgress=null)),this}else return this._isUTC?r:Fr(this)}function fm(e,s){return e!=null?(typeof e!="string"&&(e=-e),this.utcOffset(e,s),this):-this.utcOffset()}function pm(e){return this.utcOffset(0,e)}function xm(e){return this._isUTC&&(this.utcOffset(0,e),this._isUTC=!1,e&&this.subtract(Fr(this),"m")),this}function gm(){if(this._tzm!=null)this.utcOffset(this._tzm,!1,!0);else if(typeof this._i=="string"){var e=ln($d,this._i);e!=null?this.utcOffset(e):this.utcOffset(0,!0)}return this}function ym(e){return this.isValid()?(e=e?Je(e).utcOffset():0,(this.utcOffset()-e)%60===0):!1}function _m(){return this.utcOffset()>this.clone().month(0).utcOffset()||this.utcOffset()>this.clone().month(5).utcOffset()}function bm(){if(!bt(this._isDSTShifted))return this._isDSTShifted;var e={},s;return Hr(e,this),e=fl(e),e._a?(s=e._isUTC?Gt(e._a):Je(e._a),this._isDSTShifted=this.isValid()&&um(e._a,s.toArray())>0):this._isDSTShifted=!1,this._isDSTShifted}function jm(){return this.isValid()?!this._isUTC:!1}function wm(){return this.isValid()?this._isUTC:!1}function yl(){return this.isValid()?this._isUTC&&this._offset===0:!1}var vm=/^(-|\+)?(?:(\d*)[. ])?(\d+):(\d+)(?::(\d+)(\.\d*)?)?$/,Nm=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/;function Yt(e,s){var a=e,r=null,n,i,l;return Fa(e)?a={ms:e._milliseconds,d:e._days,M:e._months}:cs(e)||!isNaN(+e)?(a={},s?a[s]=+e:a.milliseconds=+e):(r=vm.exec(e))?(n=r[1]==="-"?-1:1,a={y:0,d:Le(r[Et])*n,h:Le(r[ht])*n,m:Le(r[At])*n,s:Le(r[is])*n,ms:Le(qr(r[Ds]*1e3))*n}):(r=Nm.exec(e))?(n=r[1]==="-"?-1:1,a={y:Ms(r[2],n),M:Ms(r[3],n),w:Ms(r[4],n),d:Ms(r[5],n),h:Ms(r[6],n),m:Ms(r[7],n),s:Ms(r[8],n)}):a==null?a={}:typeof a=="object"&&("from"in a||"to"in a)&&(l=km(Je(a.from),Je(a.to)),a={},a.ms=l.milliseconds,a.M=l.months),i=new rr(a),Fa(e)&&Re(e,"_locale")&&(i._locale=e._locale),Fa(e)&&Re(e,"_isValid")&&(i._isValid=e._isValid),i}Yt.fn=rr.prototype;Yt.invalid=dm;function Ms(e,s){var a=e&&parseFloat(e.replace(",","."));return(isNaN(a)?0:a)*s}function wi(e,s){var a={};return a.months=s.month()-e.month()+(s.year()-e.year())*12,e.clone().add(a.months,"M").isAfter(s)&&--a.months,a.milliseconds=+s-+e.clone().add(a.months,"M"),a}function km(e,s){var a;return e.isValid()&&s.isValid()?(s=on(s,e),e.isBefore(s)?a=wi(e,s):(a=wi(s,e),a.milliseconds=-a.milliseconds,a.months=-a.months),a):{milliseconds:0,months:0}}function _l(e,s){return function(a,r){var n,i;return r!==null&&!isNaN(+r)&&(Gi(s,"moment()."+s+"(period, number) is deprecated. Please use moment()."+s+"(number, period). See http://momentjs.com/guides/#/warnings/add-inverted-param/ for more info."),i=a,a=r,r=i),n=Yt(a,r),bl(this,n,e),this}}function bl(e,s,a,r){var n=s._milliseconds,i=qr(s._days),l=qr(s._months);e.isValid()&&(r=r??!0,l&&rl(e,ma(e,"Month")+l*a),i&&tl(e,"Date",ma(e,"Date")+i*a),n&&e._d.setTime(e._d.valueOf()+n*a),r&&se.updateOffset(e,i||l))}var Sm=_l(1,"add"),Cm=_l(-1,"subtract");function jl(e){return typeof e=="string"||e instanceof String}function Mm(e){return Ot(e)||ya(e)||jl(e)||cs(e)||Pm(e)||Dm(e)||e===null||e===void 0}function Dm(e){var s=Ts(e)&&!zr(e),a=!1,r=["years","year","y","months","month","M","days","day","d","dates","date","D","hours","hour","h","minutes","minute","m","seconds","second","s","milliseconds","millisecond","ms"],n,i,l=r.length;for(n=0;n<l;
vendor: 19,208 bytes, line 94
94n+=1)i=r[n],a=a||Re(e,i);return s&&a}function Pm(e){var s=$t(e),a=!1;return s&&(a=e.filter(function(r){return!cs(r)&&jl(e)}).length===0),s&&a}function Tm(e){var s=Ts(e)&&!zr(e),a=!1,r=["sameDay","nextDay","lastDay","nextWeek","lastWeek","sameElse"],n,i;for(n=0;n<r.length;n+=1)i=r[n],a=a||Re(e,i);return s&&a}function qm(e,s){var a=e.diff(s,"days",!0);return a<-6?"sameElse":a<-1?"lastWeek":a<0?"lastDay":a<1?"sameDay":a<2?"nextDay":a<7?"nextWeek":"sameElse"}function Fm(e,s){arguments.length===1&&(arguments[0]?Mm(arguments[0])?(e=arguments[0],s=void 0):Tm(arguments[0])&&(s=arguments[0],e=void 0):(e=void 0,s=void 0));var a=e||Je(),r=on(a,this).startOf("day"),n=se.calendarFormat(this,r)||"sameElse",i=s&&(Kt(s[n])?s[n].call(this,a):s[n]);return this.format(i||this.localeData().calendar(n,this,Je(a)))}function Lm(){return new _a(this)}function Am(e,s){var a=Ot(e)?e:Je(e);return this.isValid()&&a.isValid()?(s=Ft(s)||"millisecond",s==="millisecond"?this.valueOf()>a.valueOf():a.valueOf()<this.clone().startOf(s).valueOf()):!1}function $m(e,s){var a=Ot(e)?e:Je(e);return this.isValid()&&a.isValid()?(s=Ft(s)||"millisecond",s==="millisecond"?this.valueOf()<a.valueOf():this.clone().endOf(s).valueOf()<a.valueOf()):!1}function Om(e,s,a,r){var n=Ot(e)?e:Je(e),i=Ot(s)?s:Je(s);return this.isValid()&&n.isValid()&&i.isValid()?(r=r||"()",(r[0]==="("?this.isAfter(n,a):!this.isBefore(n,a))&&(r[1]===")"?this.isBefore(i,a):!this.isAfter(i,a))):!1}function Ym(e,s){var a=Ot(e)?e:Je(e),r;return this.isValid()&&a.isValid()?(s=Ft(s)||"millisecond",s==="millisecond"?this.valueOf()===a.valueOf():(r=a.valueOf(),this.clone().startOf(s).valueOf()<=r&&r<=this.clone().endOf(s).valueOf())):!1}function Rm(e,s){return this.isSame(e,s)||this.isAfter(e,s)}function Im(e,s){return this.isSame(e,s)||this.isBefore(e,s)}function Em(e,s,a){var r,n,i;if(!this.isValid())return NaN;if(r=on(e,this),!r.isValid())return NaN;switch(n=(r.utcOffset()-this.utcOffset())*6e4,s=Ft(s),s){case"year":i=La(this,r)/12;break;case"month":i=La(this,r);break;case"quarter":i=La(this,r)/3;break;case"second":i=(this-r)/1e3;break;case"minute":i=(this-r)/6e4;break;case"hour":i=(this-r)/36e5;break;case"day":i=(this-r-n)/864e5;break;case"week":i=(this-r-n)/6048e5;break;default:i=this-r}return a?i:Pt(i)}function La(e,s){if(e.date()<s.date())return-La(s,e);var a=(s.year()-e.year())*12+(s.month()-e.month()),r=e.clone().add(a,"months"),n,i;return s-r<0?(n=e.clone().add(a-1,"months"),i=(s-r)/(r-n)):(n=e.clone().add(a+1,"months"),i=(s-r)/(n-r)),-(a+i)||0}se.defaultFormat="YYYY-MM-DDTHH:mm:ssZ";se.defaultFormatUtc="YYYY-MM-DDTHH:mm:ss[Z]";function Wm(){return this.clone().locale("en").format("ddd MMM DD YYYY HH:mm:ss [GMT]ZZ")}function zm(e){if(!this.isValid())return null;var s=e!==!0,a=s?this.clone().utc():this;return a.year()<0||a.year()>9999?qa(a,s?"YYYYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYYYY-MM-DD[T]HH:mm:ss.SSSZ"):Kt(Date.prototype.toISOString)?s?this.toDate().toISOString():new Date(this.valueOf()+this.utcOffset()*60*1e3).toISOString().replace("Z",qa(a,"Z")):qa(a,s?"YYYY-MM-DD[T]HH:mm:ss.SSS[Z]":"YYYY-MM-DD[T]HH:mm:ss.SSSZ")}function Um(){if(!this.isValid())return"moment.invalid(/* "+this._i+" */)";var e="moment",s="",a,r,n,i;return this.isLocal()||(e=this.utcOffset()===0?"moment.utc":"moment.parseZone",s="Z"),a="["+e+'("]',r=0<=this.year()&&this.year()<=9999?"YYYY":"YYYYYY",n="-MM-DD[T]HH:mm:ss.SSS",i=s+'[")]',this.format(a+r+n+i)}function Hm(e){e||(e=this.isUtc()?se.defaultFormatUtc:se.defaultFormat);var s=qa(this,e);return this.localeData().postformat(s)}function Bm(e,s){return this.isValid()&&(Ot(e)&&e.isValid()||Je(e).isValid())?Yt({to:this,from:e}).locale(this.locale()).humanize(!s):this.localeData().invalidDate()}function Vm(e){return this.from(Je(),e)}function Gm(e,s){return this.isValid()&&(Ot(e)&&e.isValid()||Je(e).isValid())?Yt({from:this,to:e}).locale(this.locale()).humanize(!s):this.localeData().invalidDate()}function Km(e){return this.to(Je(),e)}function wl(e){var s;return e===void 0?this._locale._abbr:(s=ds(e),s!=null&&(this._locale=s),this)}var vl=qt("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 Nl(){return this._locale}var Ea=1e3,zs=60*Ea,Wa=60*zs,kl=(365*400+97)*24*Wa;function Us(e,s){return(e%s+s)%s}function Sl(e,s,a){return e<100&&e>=0?new Date(e+400,s,a)-kl:new Date(e,s,a).valueOf()}function Cl(e,s,a){return e<100&&e>=0?Date.UTC(e+400,s,a)-kl:Date.UTC(e,s,a)}function Zm(e){var s,a;if(e=Ft(e),e===void 0||e==="millisecond"||!this.isValid())return this;switch(a=this._isUTC?Cl:Sl,e){case"year":s=a(this.year(),0,1);break;case"quarter":s=a(this.year(),this.month()-this.month()%3,1);break;case"month":s=a(this.year(),this.month(),1);break;case"week":s=a(this.year(),this.month(),this.date()-this.weekday());break;case"isoWeek":s=a(this.year(),this.month(),this.date()-(this.isoWeekday()-1));break;case"day":case"date":s=a(this.year(),this.month(),this.date());break;case"hour":s=this._d.valueOf(),s-=Us(s+(this._isUTC?0:this.utcOffset()*zs),Wa);break;case"minute":s=this._d.valueOf(),s-=Us(s,zs);break;case"second":s=this._d.valueOf(),s-=Us(s,Ea);break}return this._d.setTime(s),se.updateOffset(this,!0),this}function Xm(e){var s,a;if(e=Ft(e),e===void 0||e==="millisecond"||!this.isValid())return this;switch(a=this._isUTC?Cl:Sl,e){case"year":s=a(this.year()+1,0,1)-1;break;case"quarter":s=a(this.year(),this.month()-this.month()%3+3,1)-1;break;case"month":s=a(this.year(),this.month()+1,1)-1;break;case"week":s=a(this.year(),this.month(),this.date()-this.weekday()+7)-1;break;case"isoWeek":s=a(this.year(),this.month(),this.date()-(this.isoWeekday()-1)+7)-1;break;case"day":case"date":s=a(this.year(),this.month(),this.date()+1)-1;break;case"hour":s=this._d.valueOf(),s+=Wa-Us(s+(this._isUTC?0:this.utcOffset()*zs),Wa)-1;break;case"minute":s=this._d.valueOf(),s+=zs-Us(s,zs)-1;break;case"second":s=this._d.valueOf(),s+=Ea-Us(s,Ea)-1;break}return this._d.setTime(s),se.updateOffset(this,!0),this}function Jm(){return this._d.valueOf()-(this._offset||0)*6e4}function Qm(){return Math.floor(this.valueOf()/1e3)}function eh(){return new Date(this.valueOf())}function th(){var e=this;return[e.year(),e.month(),e.date(),e.hour(),e.minute(),e.second(),e.millisecond()]}function sh(){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 ah(){return this.isValid()?this.toISOString():null}function rh(){return Ur(this)}function nh(){return ys({},Te(this))}function ih(){return Te(this).overflow}function lh(){return{input:this._i,format:this._f,locale:this._locale,isUTC:this._isUTC,strict:this._strict}}he("N",0,0,"eraAbbr");he("NN",0,0,"eraAbbr");he("NNN",0,0,"eraAbbr");he("NNNN",0,0,"eraName");he("NNNNN",0,0,"eraNarrow");he("y",["y",1],"yo","eraYear");he("y",["yy",2],0,"eraYear");he("y",["yyy",3],0,"eraYear");he("y",["yyyy",4],0,"eraYear");re("N",cn);re("NN",cn);re("NNN",cn);re("NNNN",yh);re("NNNNN",_h);Be(["N","NN","NNN","NNNN","NNNNN"],function(e,s,a,r){var n=a._locale.erasParse(e,r,a._strict);n?Te(a).era=n:Te(a).invalidEra=e});re("y",Vs);re("yy",Vs);re("yyy",Vs);re("yyyy",Vs);re("yo",bh);Be(["y","yy","yyy","yyyy"],xt);Be(["yo"],function(e,s,a,r){var n;a._locale._eraYearOrdinalRegex&&(n=e.match(a._locale._eraYearOrdinalRegex)),a._locale.eraYearOrdinalParse?s[xt]=a._locale.eraYearOrdinalParse(e,n):s[xt]=parseInt(e,10)});function oh(e,s){var a,r,n,i=this._eras||ds("en")._eras;for(a=0,r=i.length;a<r;++a){switch(typeof i[a].since){case"string":n=se(i[a].since).startOf("day"),i[a].since=n.valueOf();break}switch(typeof i[a].until){case"undefined":i[a].until=1/0;break;case"string":n=se(i[a].until).startOf("day").valueOf(),i[a].until=n.valueOf();break}}return i}function ch(e,s,a){var r,n,i=this.eras(),l,u,c;for(e=e.toUpperCase(),r=0,n=i.length;r<n;++r)if(l=i[r].name.toUpperCase(),u=i[r].abbr.toUpperCase(),c=i[r].narrow.toUpperCase(),a)switch(s){case"N":case"NN":case"NNN":if(u===e)return i[r];break;case"NNNN":if(l===e)return i[r];break;case"NNNNN":if(c===e)return i[r];break}else if([l,u,c].indexOf(e)>=0)return i[r]}function dh(e,s){var a=e.since<=e.until?1:-1;return s===void 0?se(e.since).year():se(e.since).year()+(s-e.offset)*a}function uh(){var e,s,a,r=this.localeData().eras();for(e=0,s=r.length;e<s;++e)if(a=this.clone().startOf("day").valueOf(),r[e].since<=a&&a<=r[e].until||r[e].until<=a&&a<=r[e].since)return r[e].name;return""}function mh(){var e,s,a,r=this.localeData().eras();for(e=0,s=r.length;e<s;++e)if(a=this.clone().startOf("day").valueOf(),r[e].since<=a&&a<=r[e].until||r[e].until<=a&&a<=r[e].since)return r[e].narrow;return""}function hh(){var e,s,a,r=this.localeData().eras();for(e=0,s=r.length;e<s;++e)if(a=this.clone().startOf("day").valueOf(),r[e].since<=a&&a<=r[e].until||r[e].until<=a&&a<=r[e].since)return r[e].abbr;return""}function fh(){var e,s,a,r,n=this.localeData().eras();for(e=0,s=n.length;e<s;++e)if(a=n[e].since<=n[e].until?1:-1,r=this.clone().startOf("day").valueOf(),n[e].since<=r&&r<=n[e].until||n[e].until<=r&&r<=n[e].since)return(this.year()-se(n[e].since).year())*a+n[e].offset;return this.year()}function ph(e){return Re(this,"_erasNameRegex")||dn.call(this),e?this._erasNameRegex:this._erasRegex}function xh(e){return Re(this,"_erasAbbrRegex")||dn.call(this),e?this._erasAbbrRegex:this._erasRegex}function gh(e){return Re(this,"_erasNarrowRegex")||dn.call(this),e?this._erasNarrowRegex:this._erasRegex}function cn(e,s){return s.erasAbbrRegex(e)}function yh(e,s){return s.erasNameRegex(e)}function _h(e,s){return s.erasNarrowRegex(e)}function bh(e,s){return s._eraYearOrdinalRegex||Vs}function dn(){var e=[],s=[],a=[],r=[],n,i,l,u,c,d=this.eras();for(n=0,i=d.length;n<i;++n)l=ls(d[n].name),u=ls(d[n].abbr),c=ls(d[n].narrow),s.push(l),e.push(u),a.push(c),r.push(l),r.push(u),r.push(c);this._erasRegex=new RegExp("^("+r.join("|")+")","i"),this._erasNameRegex=new RegExp("^("+s.join("|")+")","i"),this._erasAbbrRegex=new RegExp("^("+e.join("|")+")","i"),this._erasNarrowRegex=new RegExp("^("+a.join("|")+")","i")}he(0,["gg",2],0,function(){return this.weekYear()%100});he(0,["GG",2],0,function(){return this.isoWeekYear()%100});function nr(e,s){he(0,[e,e.length],0,s)}nr("gggg","weekYear");nr("ggggg","weekYear");nr("GGGG","isoWeekYear");nr("GGGGG","isoWeekYear");re("G",er);re("g",er);re("GG",Qe,kt);re("gg",Qe,kt);re("GGGG",Zr,Kr);re("gggg",Zr,Kr);re("GGGGG",Qa,Xa);re("ggggg",Qa,Xa);ja(["gggg","ggggg","GGGG","GGGGG"],function(e,s,a,r){s[r.substr(0,2)]=Le(e)});ja(["gg","GG"],function(e,s,a,r){s[r]=se.parseTwoDigitYear(e)});function jh(e){return Ml.call(this,e,this.week(),this.weekday()+this.localeData()._week.dow,this.localeData()._week.dow,this.localeData()._week.doy)}function wh(e){return Ml.call(this,e,this.isoWeek(),this.isoWeekday(),1,4)}function vh(){return os(this.year(),1,4)}function Nh(){return os(this.isoWeekYear(),1,4)}function kh(){var e=this.localeData()._week;return os(this.year(),e.dow,e.doy)}function Sh(){var e=this.localeData()._week;return os(this.weekYear(),e.dow,e.doy)}function Ml(e,s,a,r,n){var i;return e==null?fa(this,r,n).year:(i=os(e,r,n),s>i&&(s=i),Ch.call(this,e,s,a,r,n))}function Ch(e,s,a,r,n){var i=ll(e,s,a,r,n),l=ha(i.year,0,i.dayOfYear);return this.year(l.getUTCFullYear()),this.month(l.getUTCMonth()),this.date(l.getUTCDate()),this}he("Q",0,"Qo","quarter");re("Q",Zi);Be("Q",function(e,s){s[ns]=(Le(e)-1)*3});function Mh(e){return e==null?Math.ceil((this.month()+1)/3):this.month((e-1)*3+this.month()%3)}he("D",["DD",2],"Do","date");re("D",Qe,Gs);re("DD",Qe,kt);re("Do",function(e,s){return e?s._dayOfMonthOrdinalParse||s._ordinalParse:s._dayOfMonthOrdinalParseLenient});Be(["D","DD"],Et);Be("Do",function(e,s){s[Et]=Le(e.match(Qe)[0])});var Dl=Ks("Date",!0);he("DDD",["DDDD",3],"DDDo","dayOfYear");re("DDD",Ja);re("DDDD",Xi);Be(["DDD","DDDD"],function(e,s,a){a._dayOfYear=Le(e)});function Dh(e){var s=Math.round((this.clone().startOf("day")-this.clone().startOf("year"))/864e5)+1;return e==null?s:this.add(e-s,"d")}he("m",["mm",2],0,"minute");re("m",Qe,Xr);re("mm",Qe,kt);Be(["m","mm"],At);var Ph=Ks("Minutes",!1);he("s",["ss",2],0,"second");re("s",Qe,Xr);re("ss",Qe,kt);Be(["s","ss"],is);var Th=Ks("Seconds",!1);he("S",0,0,function(){return~~(this.millisecond()/100)});he(0,["SS",2],0,function(){return~~(this.millisecond()/10)});he(0,["SSS",3],0,"millisecond");he(0,["SSSS",4],0,function(){return this.millisecond()*10});he(0,["SSSSS",5],0,function(){return this.millisecond()*100});he(0,["SSSSSS",6],0,function(){return this.millisecond()*1e3});he(0,["SSSSSSS",7],0,function(){return this.millisecond()*1e4});he(0,["SSSSSSSS",8],0,function(){return this.millisecond()*1e5});he(0,["SSSSSSSSS",9],0,function(){return this.millisecond()*1e6});re("S",Ja,Zi);re("SS",Ja,kt);re("SSS",Ja,Xi);var _s,Pl;for(_s="SSSS";_s.length<=9;_s+="S")re(_s,Vs);function qh(e,s){s[Ds]=Le(("0."+e)*1e3)}for(_s="S";_s.length<=9;_s+="S")Be(_s,qh);Pl=Ks("Milliseconds",!1);he("z",0,0,"zoneAbbr");he("zz",0,0,"zoneName");function Fh(){return this._isUTC?"UTC":""}function Lh(){return this._isUTC?"Coordinated Universal Time":""}var G=_a.prototype;G.add=Sm;G.calendar=Fm;G.clone=Lm;G.diff=Em;G.endOf=Xm;G.format=Hm;G.from=Bm;G.fromNow=Vm;G.to=Gm;G.toNow=Km;G.get=Ud;G.invalidAt=ih;G.isAfter=Am;G.isBefore=$m;G.isBetween=Om;G.isSame=Ym;G.isSameOrAfter=Rm;G.isSameOrBefore=Im;G.isValid=rh;G.lang=vl;G.locale=wl;G.localeData=Nl;G.max=rm;G.min=am;G.parsingFlags=nh;G.set=Hd;G.startOf=Zm;G.subtract=Cm;G.toArray=th;G.toObject=sh;G.toDate=eh;G.toISOString=zm;G.inspect=Um;typeof Symbol<"u"&&Symbol.for!=null&&(G[Symbol.for("nodejs.util.inspect.custom")]=function(){return"Moment<"+this.format()+">"});G.toJSON=ah;G.toString=Wm;G.unix=Qm;G.valueOf=Jm;G.creationData=lh;G.eraName=uh;G.eraNarrow=mh;G.eraAbbr=hh;G.eraYear=fh;G.year=el;G.isLeapYear=zd;G.weekYear=jh;G.isoWeekYear=wh;G.quarter=G.quarters=Mh;G.month=nl;G.daysInMonth=eu;G.week=G.weeks=ou;G.isoWeek=G.isoWeeks=cu;G.weeksInYear=kh;G.weeksInWeekYear=Sh;G.isoWeeksInYear=vh;G.isoWeeksInISOWeekYear=Nh;G.date=Dl;G.day=G.days=wu;G.weekday=vu;G.isoWeekday=Nu;G.dayOfYear=Dh;G.hour=G.hours=Tu;G.minute=G.minutes=Ph;G.second=G.seconds=Th;G.millisecond=G.milliseconds=Pl;G.utcOffset=hm;G.utc=pm;G.local=xm;G.parseZone=gm;G.hasAlignedHourOffset=ym;G.isDST=_m;G.isLocal=jm;G.isUtcOffset=wm;G.isUtc=yl;G.isUTC=yl;G.zoneAbbr=Fh;G.zoneName=Lh;G.dates=qt("dates accessor is deprecated. Use date instead.",Dl);G.months=qt("months accessor is deprecated. Use month instead",nl);G.years=qt("years accessor is deprecated. Use year instead",el);G.zone=qt("moment().zone is deprecated, use moment().utcOffset instead. http://momentjs.com/guides/#/warnings/zone/",fm);G.isDSTShifted=qt("isDSTShifted is deprecated. See http://momentjs.com/guides/#/warnings/dst-shifted/ for more information",bm);function Ah(e){return Je(e*1e3)}function $h(){return Je.apply(null,arguments).parseZone()}function Tl(e){return e}var Ie=Br.prototype;Ie.calendar=jd;Ie.longDateFormat=kd;Ie.invalidDate=Cd;Ie.ordinal=Pd;Ie.preparse=Tl;Ie.postformat=Tl;Ie.relativeTime=qd;Ie.pastFuture=Fd;Ie.set=_d;Ie.eras=oh;Ie.erasParse=ch;Ie.erasConvertYear=dh;Ie.erasAbbrRegex=xh;Ie.erasNameRegex=ph;Ie.erasNarrowRegex=gh;Ie.months=Zd;Ie.monthsShort=Xd;Ie.monthsParse=Qd;Ie.monthsRegex=su;Ie.monthsShortRegex=tu;Ie.week=ru;Ie.firstDayOfYear=lu;Ie.firstDayOfWeek=iu;Ie.weekdays=gu;Ie.weekdaysMin=_u;Ie.weekdaysShort=yu;Ie.weekdaysParse=ju;Ie.weekdaysRegex=ku;Ie.weekdaysShortRegex=Su;Ie.weekdaysMinRegex=Cu;Ie.isPM=Du;Ie.meridiem=qu;function za(e,s,a,r){var n=ds(),i=Gt().set(r,s);return n[a](i,e)}function ql(e,s,a){if(cs(e)&&(s=e,e=void 0),e=e||"",s!=null)return za(e,s,a,"month");var r,n=[];for(r=0;r<12;r++)n[r]=za(e,r,a,"month");return n}function un(e,s,a,r){typeof e=="boolean"?(cs(s)&&(a=s,s=void 0),s=s||""):(s=e,a=s,e=!1,cs(s)&&(a=s,s=void 0),s=s||"");var n=ds(),i=e?n._week.dow:0,l,u=[];if(a!=null)return za(s,(a+i)%7,r,"day");for(l=0;l<7;l++)u[l]=za(s,(l+i)%7,r,"day");return u}function Oh(e,s){return ql(e,s,"months")}function Yh(e,s){return ql(e,s,"monthsShort")}function Rh(e,s,a){return un(e,s,a,"weekdays")}function Ih(e,s,a){return un(e,s,a,"weekdaysShort")}function Eh(e,s,a){return un(e,s,a,"weekdaysMin")}bs("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 s=e%10,a=Le(e%100/10)===1?"th":s===1?"st":s===2?"nd":s===3?"rd":"th";return e+a}});se.lang=qt("moment.lang is deprecated. Use moment.locale instead.",bs);se.langData=qt("moment.langData is deprecated. Use moment.localeData instead.",ds);var Jt=Math.abs;function Wh(){var e=this._data;return this._milliseconds=Jt(this._milliseconds),this._days=Jt(this._days),this._months=Jt(this._months),e.milliseconds=Jt(e.milliseconds),e.seconds=Jt(e.seconds),e.minutes=Jt(e.minutes),e.hours=Jt(e.hours),e.months=Jt(e.months),e.years=Jt(e.years),this}function Fl(e,s,a,r){var n=Yt(s,a);return e._milliseconds+=r*n._milliseconds,e._days+=r*n._days,e._months+=r*n._months,e._bubble()}function zh(e,s){return Fl(this,e,s,1)}function Uh(e,s){return Fl(this,e,s,-1)}function vi(e){return e<0?Math.floor(e):Math.ceil(e)}function Hh(){var e=this._milliseconds,s=this._days,a=this._months,r=this._data,n,i,l,u,c;return e>=0&&s>=0&&a>=0||e<=0&&s<=0&&a<=0||(e+=vi(Lr(a)+s)*864e5,s=0,a=0),r.milliseconds=e%1e3,n=Pt(e/1e3),r.seconds=n%60,i=Pt(n/60),r.minutes=i%60,l=Pt(i/60),r.hours=l%24,s+=Pt(l/24),c=Pt(Ll(s)),a+=c,s-=vi(Lr(c)),u=Pt(a/12),a%=12,r.days=s,r.months=a,r.years=u,this}function Ll(e){return e*4800/146097}function Lr(e){return e*146097/4800}function Bh(e){if(!this.isValid())return NaN;var s,a,r=this._milliseconds;if(e=Ft(e),e==="month"||e==="quarter"||e==="year")switch(s=this._days+r/864e5,a=this._months+Ll(s),e){case"month":return a;case"quarter":return a/3;case"year":return a/12}else switch(s=this._days+Math.round(Lr(this._months)),e){case"week":return s/7+r/6048e5;case"day":return s+r/864e5;case"hour":return s*24+r/36e5;case"minute":return s*1440+r/6e4;case"second":return s*86400+r/1e3;case"millisecond":return Math.floor(s*864e5)+r;default:throw new Error("Unknown unit "+e)}}function us(e){return function(){return this.as(e)}}var Al=us("ms"),Vh=us("s"),Gh=us("m"),Kh=us("h"),Zh=us("d"),Xh=us("w"),Jh=us("M"),Qh=us("Q"),ef=us("y"),tf=Al;function sf(){return Yt(this)}function af(e){return e=Ft(e),this.isValid()?this[e+"s"]():NaN}function Ls(e){return function(){return this.isValid()?this._data[e]:NaN}}var rf=Ls("milliseconds"),nf=Ls("seconds"),lf=Ls("minutes"),of=Ls("hours"),cf=Ls("days"),df=Ls("months"),uf=Ls("years");function mf(){return Pt(this.days()/7)}var es=Math.round,Is={ss:44,s:45,m:45,h:22,d:26,w:null,M:11};function hf(e,s,a,r,n){return n.relativeTime(s||1,!!a,e,r)}function ff(e,s,a,r){var n=Yt(e).abs(),i=es(n.as("s")),l=es(n.as("m")),u=es(n.as("h")),c=es(n.as("d")),d=es(n.as("M")),j=es(n.as("w")),w=es(n.as("y")),A=i<=a.ss&&["s",i]||i<a.s&&["ss",i]||l<=1&&["m"]||l<a.m&&["mm",l]||u<=1&&["h"]||u<a.h&&["hh",u]||c<=1&&["d"]||c<a.d&&["dd",c];
94return a.w!=null&&(A=A||j<=1&&["w"]||j<a.w&&["ww",j]),A=A||d<=1&&["M"]||d<a.M&&["MM",d]||w<=1&&["y"]||["yy",w],A[2]=s,A[3]=+e>0,A[4]=r,hf.apply(null,A)}function pf(e){return e===void 0?es:typeof e=="function"?(es=e,!0):!1}function xf(e,s){return Is[e]===void 0?!1:s===void 0?Is[e]:(Is[e]=s,e==="s"&&(Is.ss=s-1),!0)}function gf(e,s){if(!this.isValid())return this.localeData().invalidDate();var a=!1,r=Is,n,i;return typeof e=="object"&&(s=e,e=!1),typeof e=="boolean"&&(a=e),typeof s=="object"&&(r=Object.assign({},Is,s),s.s!=null&&s.ss==null&&(r.ss=s.s-1)),n=this.localeData(),i=ff(this,!a,r,n),a&&(i=n.pastFuture(+this,i)),n.postformat(i)}var Sr=Math.abs;function Os(e){return(e>0)-(e<0)||+e}function ir(){if(!this.isValid())return this.localeData().invalidDate();var e=Sr(this._milliseconds)/1e3,s=Sr(this._days),a=Sr(this._months),r,n,i,l,u=this.asSeconds(),c,d,j,w;return u?(r=Pt(e/60),n=Pt(r/60),e%=60,r%=60,i=Pt(a/12),a%=12,l=e?e.toFixed(3).replace(/\.?0+$/,""):"",c=u<0?"-":"",d=Os(this._months)!==Os(u)?"-":"",j=Os(this._days)!==Os(u)?"-":"",w=Os(this._milliseconds)!==Os(u)?"-":"",c+"P"+(i?d+i+"Y":"")+(a?d+a+"M":"")+(s?j+s+"D":"")+(n||r||e?"T":"")+(n?w+n+"H":"")+(r?w+r+"M":"")+(e?w+l+"S":"")):"P0D"}var $e=rr.prototype;$e.isValid=cm;$e.abs=Wh;$e.add=zh;$e.subtract=Uh;$e.as=Bh;$e.asMilliseconds=Al;$e.asSeconds=Vh;$e.asMinutes=Gh;$e.asHours=Kh;$e.asDays=Zh;$e.asWeeks=Xh;$e.asMonths=Jh;$e.asQuarters=Qh;$e.asYears=ef;$e.valueOf=tf;$e._bubble=Hh;$e.clone=sf;$e.get=af;$e.milliseconds=rf;$e.seconds=nf;$e.minutes=lf;$e.hours=of;$e.days=cf;$e.weeks=mf;$e.months=df;$e.years=uf;$e.humanize=gf;$e.toISOString=ir;$e.toString=ir;$e.toJSON=ir;$e.locale=wl;$e.localeData=Nl;$e.toIsoString=qt("toIsoString() is deprecated. Please use toISOString() instead (notice the capitals)",ir);$e.lang=vl;he("X",0,0,"unix");he("x",0,0,"valueOf");re("x",er);re("X",Od);Be("X",function(e,s,a){a._d=new Date(parseFloat(e)*1e3)});Be("x",function(e,s,a){a._d=new Date(Le(e))});//! moment.js
95se.version="2.30.1";gd(Je);se.fn=G;se.min=nm;se.max=im;se.now=lm;se.utc=Gt;se.unix=Ah;se.months=Oh;se.isDate=ya;se.locale=bs;se.invalid=Za;se.duration=Yt;se.isMoment=Ot;se.weekdays=Rh;se.parseZone=$h;se.localeData=ds;se.isDuration=Fa;se.monthsShort=Yh;se.weekdaysMin=Eh;se.defineLocale=sn;se.updateLocale=$u;se.locales=Ou;se.weekdaysShort=Ih;se.normalizeUnits=Ft;se.relativeTimeRounding=pf;se.relativeTimeThreshold=xf;se.calendarFormat=qm;se.prototype=G;se.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 yf({quoteId:e}){const s=xa(),[a,r]=m.useState(""),{data:n}=jt({queryKey:["quote-comments",e],queryFn:()=>ge.entities.Quote.get(e),enabled:!!e}),i=(n==null?void 0:n.comments)||[],l=async()=>{if(a.trim())try{const d=await ge.auth.me(),j={id:`cmt-${Date.now()}`,author_id:(d==null?void 0:d.id)||"unknown",author_name:(d==null?void 0:d.full_name)||(d==null?void 0:d.email)||"Unknown",text:a.trim(),created_at:new Date().toISOString()},w=[...i,j];await ge.entities.Quote.update(e,{comments:w}),r(""),s.invalidateQueries({queryKey:["quote-comments",e]}),$.success("Comment added")}catch(d){$.error("Failed to add comment"),console.error(d)}},u=async d=>{try{const j=i.filter(w=>w.id!==d);await ge.entities.Quote.update(e,{comments:j}),s.invalidateQueries({queryKey:["quote-comments",e]}),$.success("Comment deleted")}catch(j){$.error("Failed to delete comment"),console.error(j)}},c=d=>{d.key==="Enter"&&!d.shiftKey&&(d.preventDefault(),l())};return t.jsxs(at,{children:[t.jsx(Ua,{className:"pb-3",children:t.jsxs(Ha,{className:"flex items-center gap-2 text-base",children:[t.jsx(Rr,{className:"w-4 h-4 text-primary"}),"Comments",i.length>0&&t.jsxs("span",{className:"text-xs font-normal text-muted-foreground",children:["(",i.length,")"]})]})}),t.jsxs(rt,{className:"space-y-3",children:[i.length===0?t.jsx("p",{className:"text-sm text-muted-foreground py-2",children:"No comments yet. Discuss deadlines, material changes, or client requests here."}):t.jsx("div",{className:"space-y-2 max-h-64 overflow-y-auto",children:i.map(d=>t.jsxs("div",{className:"flex items-start gap-2 p-2 rounded-lg bg-slate-50 dark:bg-slate-900/50 group",children:[t.jsx("div",{className:"w-7 h-7 rounded-full bg-primary/15 text-primary flex items-center justify-center text-xs font-semibold shrink-0",children:(d.author_name||"?").charAt(0).toUpperCase()}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsx("span",{className:"text-sm font-medium",children:d.author_name}),t.jsx("span",{className:"text-xs text-muted-foreground",children:se(d.created_at).fromNow()})]}),t.jsx("p",{className:"text-sm text-foreground whitespace-pre-wrap break-words mt-0.5",children:d.text})]}),t.jsx(X,{variant:"ghost",size:"icon",className:"h-6 w-6 opacity-0 group-hover:opacity-100 shrink-0",onClick:()=>u(d.id),title:"Delete comment",children:t.jsx(Fs,{className:"w-3.5 h-3.5 text-muted-foreground"})})]},d.id))}),t.jsxs("div",{className:"flex items-center gap-2 pt-1",children:[t.jsx(He,{value:a,onChange:d=>r(d.target.value),onKeyDown:c,placeholder:"Write a comment...",className:"h-9"}),t.jsx(X,{size:"icon",className:"h-9 w-9 shrink-0",onClick:l,disabled:!a.trim(),children:t.jsx(Wr,{className:"w-4 h-4"})})]})]})]})}function _f({isCustomerView:e,onToggle:s}){return t.jsxs("div",{className:"inline-flex items-center rounded-lg border bg-muted/50 p-0.5",children:[t.jsxs(X,{variant:e?"ghost":"default",size:"sm",className:"h-7 text-xs gap-1",onClick:()=>s(!1),children:[t.jsx(Ir,{className:"w-3.5 h-3.5"}),"Edit"]}),t.jsxs(X,{variant:e?"default":"ghost",size:"sm",className:"h-7 text-xs gap-1",onClick:()=>s(!0),children:[t.jsx(Ti,{className:"w-3.5 h-3.5"}),"Present"]})]})}function bf({lineItems:e,addonTotal:s,discountType:a,discountValue:r,taxRate:n,applyCreditCardFee:i,creditCardFeeRate:l,paymentsReceived:u=0,depositSchedule:c=[],measurementUnit:d="imperial",pricingConfig:j={}}){const w=j.backsplash_rate_per_sqft??12,A=j.sink_cutout_flat_fee??75,M=j.cooktop_cutout_flat_fee??125,T=j.special_feature_flat_fee??50,D=j.finished_edge_rate_per_linear_ft??8,Y=e.filter(q=>q.item_type!=="service"&&q.item_type!=="product"),P=Y[0]||{},h=Y.reduce((q,E)=>
95q+(parseFloat(E.sqft)||0),0),J=Y.reduce((q,E)=>{let be=0;return E.sink_type&&E.sink_type!=="none"&&be++,E.cooktop_included&&be++,q+be},0),z=[{label:"Material",value:P.material_name||"—"},{label:"Edge",value:P.edge_profile?P.edge_profile.charAt(0).toUpperCase()+P.edge_profile.slice(1):"Eased"},{label:"Area",value:Es(h,d)},{label:"Cutouts",value:J}],B=[],U=new Map;e.forEach((q,E)=>{const be=q.item_type==="service",we=q.item_type==="product",le=be||we?"Services & Products":q.name||q.material_name||`Area ${E+1}`;if(!U.has(le)){const fe={label:le,rows:[],subtotal:0};U.set(le,fe),B.push(fe)}const me=U.get(le);if(q.hidden_from_customer){const fe={key:`hid-${E}`,desc:`${le} (Included)`,rate:"Included",total:q.selling_price||0,hidden:!0};me.rows.push(fe),me.subtotal+=fe.total;return}if(be||we){const fe=parseFloat(q.sqft)||1,Ke=q.unit_price_per_sqft||0,et={key:`svc-${E}`,desc:`${fe} — ${q.name||(be?"Service":"Product")}`,rate:`$${Ke.toFixed(2)}/ea`,total:q.selling_price||0};me.rows.push(et),me.subtotal+=et.total;return}const De=parseFloat(q.sqft)||0,Ge=q.unit_price_per_sqft||0,Ue=q.discount_approval_status==="approved"&&q.discount_pct>0?1-q.discount_pct/100:1,nt=Ge*De*Ue,lt={key:`mat-${E}`,desc:`${Es(De,d)} ${q.material_name||q.name||`Area ${E+1}`}`,rate:gr(Ge,d),total:nt,swatch:q.color};if(me.rows.push(lt),me.subtotal+=nt,q.backsplash){const fe={key:`bs-${E}`,desc:`${Es(De,d)} Backsplash`,rate:gr(w,d),total:De*w*Ue};me.rows.push(fe),me.subtotal+=fe.total}if(q.sink_type&&q.sink_type!=="none"){const fe={key:`sink-${E}`,desc:`1 — ${q.sink_type==="undermount"?"Single Bowl Undermount":q.sink_type} Cutout`,rate:`$${A.toFixed(2)}/ea`,total:A*Ue};me.rows.push(fe),me.subtotal+=fe.total}if(q.cooktop_included){const fe={key:`cook-${E}`,desc:"1 — Cooktop Cutout",rate:`$${M.toFixed(2)}/ea`,total:M*Ue};me.rows.push(fe),me.subtotal+=fe.total}const dt=parseFloat(q.edge_linear_ft)||0;if(dt>0){const fe={key:`edge-${E}`,desc:`${dt} lf — Finished Edge`,rate:`$${D.toFixed(2)}/lf`,total:dt*D*Ue};me.rows.push(fe),me.subtotal+=fe.total}(q.special_features||[]).forEach((fe,Ke)=>{const et={key:`feat-${E}-${Ke}`,desc:`1 — ${fe}`,rate:`$${T.toFixed(2)}/ea`,total:T*Ue};me.rows.push(et),me.subtotal+=et.total})});const{shortfallSqft:oe}=Ei(Y,j.minimum_sqft||0);if(oe>0&&B.length>0){const q=Y.find(le=>(parseFloat(le.sqft)||0)>0)||P,E=(parseFloat(q.unit_price_per_sqft)||0)*(1+(q.markup_pct||0)/100),be=q.discount_approval_status==="approved"&&q.discount_pct>0?1-q.discount_pct/100:1,we={key:"min-floor",desc:`Kitchen minimum (${j.minimum_sqft} sq ft)`,rate:gr(E,d),total:oe*E*be};B.push({label:"Minimum",rows:[we],subtotal:we.total})}const Ne=B.reduce((q,E)=>q+E.subtotal,0)+(s||0),{discountAmount:ue,taxAmount:je,ccFeeAmount:ye,finalTotal:W}=Ya({basePrice:Ne,discountType:a,discountValue:r,taxRate:n,applyCreditCardFee:i,ccFeeRate:l}),V=q=>t.jsxs("div",{className:"px-4 py-2.5 flex items-center justify-between gap-3 text-sm",children:[t.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-0",children:[t.jsx(Va,{className:"w-3.5 h-3.5 text-muted-foreground/40 shrink-0"}),q.swatch&&t.jsx("span",{className:"inline-block w-3 h-3 rounded-full border border-border shrink-0",style:{backgroundColor:q.swatch}}),t.jsx("span",{className:"text-foreground truncate",children:q.desc})]}),t.jsx("div",{className:"text-xs text-muted-foreground tabular-nums whitespace-nowrap border-b border-dashed border-primary/40",children:q.rate}),t.jsx("div",{className:"font-semibold tabular-nums whitespace-nowrap text-right w-24",children:q.hidden?"—":"$"+q.total.toFixed(2)})]},q.key);return t.jsxs("div",{className:"bg-white dark:bg-slate-800 rounded-xl border border-border overflow-hidden shadow-sm",children:[t.jsx("div",{className:"bg-primary text-primary-foreground px-4 py-3",children:t.jsx("div",{className:"flex flex-wrap items-center gap-x-6 gap-y-2 text-sm",children:z.map(q=>t.jsxs("div",{className:"flex flex-col",children:[t.jsx("span",{className:"text-xs uppercase tracking-wide opacity-70",children:q.label}),t.jsx("span",{className:"font-semibold capitalize",children:q.value})]},q.label))})}),t.jsx("div",{className:"divide-y divide-border",children:B.map((q,E)=>t.jsxs("div",{children:[B.length>1&&t.jsxs("div",{className:"px-4 py-2 bg-slate-50 dark:bg-slate-900/40 flex items-center justify-between",children:[t.jsx("span",{className:"text-xs font-bold uppercase tracking-wide text-muted-foreground",children:q.label}),t.jsxs("span",{className:"text-xs font-semibold tabular-nums text-muted-foreground",children:["$",q.subtotal.toFixed(2)]})]}),q.rows.map(V)]},E))}),t.jsxs("div",{className:"px-4 py-3 bg-slate-50 dark:bg-slate-900/50 border-t border-border space-y-1.5 text-sm",children:[t.jsxs("div",{className:"flex justify-between font-semibold",children:[t.jsx("span",{children:"Subtotal:"}),t.jsxs("span",{className:"tabular-nums",children:["$",Ne.toFixed(2)]})]}),a!=="none"&&ue>0&&t.jsxs("div",{className:"flex justify-between text-success",children:[t.jsxs("span",{children:["Discount (",a==="percentage"?`${r}%`:"$"+r,"):"]}),t.jsxs("span",{className:"tabular-nums",children:["-$",ue.toFixed(2)]})]}),t.jsxs("div",{className:"flex justify-between",children:[t.jsxs("span",{className:"text-sm",children:["Tax (",n||0,"%):"]}),t.jsxs("span",{className:"tabular-nums font-medium",children:["$",je.toFixed(2)]})]}),t.jsxs("div",{className:"flex justify-between",children:[t.jsxs("span",{className:"text-sm",children:["Credit Card Fee (",i?l:0,"%):"]}),t.jsxs("span",{className:"tabular-nums font-medium",children:["$",ye.toFixed(2)]})]}),t.jsx("div",{className:"border-t-2 border-primary my-1"}),t.jsxs("div",{className:"flex justify-between text-xl font-bold text-primary",children:[t.jsx("span",{children:"Total Price:"}),t.jsxs("span",{className:"tabular-nums",children:["$",W.toFixed(2)]})]}),c.length>0&&t.jsxs("div",{className:"pt-2 space-y-1",children:[t.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Deposit Schedule"}),c.map((q,E)=>t.jsxs("div",{className:"flex justify-between text-sm",children:[t.jsxs("span",{className:"text-muted-foreground",children:[q.label," (",q.percentage,"%)",q.due_date&&t.jsxs("span",{className:"text-xs ml-1 opacity-70",children:["· due ",q.due_date]})]}),t.jsxs("span",{className:"tabular-nums font-medium",children:["$",(W*q.percentage/100).toFixed(2)]})]},q.id||E))]}),u>0&&t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex justify-between text-success",children:[t.jsx("span",{className:"text-sm",children:"Payments Received:"}),t.jsxs("span",{className:"tabular-nums font-medium",children:["-$",u.toFixed(2)]})]}),u>=W&&W>0?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"flex justify-between text-lg font-bold pt-1 text-success",children:[t.jsx("span",{children:"Paid in Full"}),t.jsx("span",{className:"tabular-nums",children:"$0.00"})]}),u>W&&t.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[t.jsx("span",{children:"Customer Credit (overpayment):"}),t.jsxs("span",{className:"tabular-nums",children:["$",(u-W).toFixed(2)]})]})]}):t.jsxs("div",{className:"flex justify-between text-lg font-bold pt-1",children:[t.jsx("span",{children:"Balance Due:"}),t.jsxs("span",{className:"tabular-nums",children:["$",Math.max(0,W-u).toFixed(2)]})]})]})]})]})}function jf({quoteData:e,lineItems:s,aiQuote:a,allMaterials:r,depositSchedule:n,discountType:i,discountValue:l,taxRate:u,applyCreditCardFee:c,creditCardFeeRate:d,paymentsReceived:j,customerSignature:w,layoutImageUrl:A,onSign:M,measurementUnit:T="imperial",pricingConfig:D={}}){const Y=s.reduce((h,J)=>h+(parseFloat(J.sqft)||0),0),P=s.filter(h=>!h.item_type||h.item_type==="material");return t.jsxs("div",{className:"space-y-4",children:[t.jsxs(at,{className:"overflow-hidden",children:[t.jsx("div",{className:"bg-primary text-primary-foreground px-6 py-5",children:t.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[t.jsxs("div",{children:[t.jsx("p",{className:"text-xs uppercase tracking-wide opacity-80",children:"Prepared for"}),t.jsx("h2",{className:"text-xl font-bold",children:e.customer_name}),t.jsxs("p",{className:"text-sm opacity-90 capitalize",children:[e.project_type," Project"]})]}),(a==null?void 0:a.selling_price)&&t.jsxs("div",{className:"text-right",children:[t.jsx("p",{className:"text-xs uppercase tracking-wide opacity-80",children:"Total Investment"}),t.jsxs("p",{className:"text-2xl font-bold",children:["$",a.selling_price.toLocaleStr
95ing(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})]}),t.jsxs("p",{className:"text-xs opacity-90",children:[Es(Y,T)," of material"]})]})]})}),t.jsxs(rt,{className:"pt-4 pb-4 space-y-2",children:[e.job_address&&t.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[t.jsx(_o,{className:"w-4 h-4 shrink-0"}),t.jsx("span",{children:e.job_address})]}),e.customer_phone&&t.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[t.jsx(Li,{className:"w-4 h-4 shrink-0"}),t.jsx("span",{children:e.customer_phone})]}),e.customer_email&&t.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[t.jsx($r,{className:"w-4 h-4 shrink-0"}),t.jsx("span",{children:e.customer_email})]})]})]}),P.length>0&&t.jsx(at,{children:t.jsxs(rt,{className:"pt-4 pb-4",children:[t.jsx("h3",{className:"text-sm font-semibold mb-3",children:"Selected Materials"}),t.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:P.map((h,J)=>{const z=r.find(B=>B.material_name===h.material_name);return t.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-card",children:[t.jsx(Wi,{material:z||h,size:"lg"}),t.jsxs("div",{className:"min-w-0",children:[t.jsx("p",{className:"text-sm font-medium truncate",children:h.material_name||h.name}),t.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:h.material_type}),t.jsx("p",{className:"text-xs text-muted-foreground",children:Es(parseFloat(h.sqft)||
950,T)})]})]},J)})})]})}),A&&t.jsx(at,{children:t.jsxs(rt,{className:"pt-4 pb-4",children:[t.jsx("h3",{className:"text-sm font-semibold mb-3",children:"Room Layout"}),t.jsx("img",{src:A,alt:"Room layout",className:"w-full rounded-lg border"})]})}),t.jsx(bf,{lineItems:s,addonTotal:0,discountType:i,discountValue:l,taxRate:u,applyCreditCardFee:c,creditCardFeeRate:d,paymentsReceived:j,depositSchedule:n,measurementUnit:T,pricingConfig:D}),n.length>0&&t.jsx(at,{children:t.jsxs(rt,{className:"pt-4 pb-4",children:[t.jsxs("h3",{className:"text-sm font-semibold mb-3 flex items-center gap-2",children:[t.jsx(Di,{className:"w-4 h-4"}),"Payment Schedule"]}),t.jsx("div",{className:"space-y-2",children:n.map((h,J)=>t.jsxs("div",{className:"flex items-center justify-between text-sm p-2 rounded border bg-muted/30",children:[t.jsxs("div",{children:[t.jsx("span",{className:"font-medium",children:h.label}),h.due_date&&t.jsxs("span",{className:"text-xs text-muted-foreground ml-2",children:["due ",h.due_date]})]}),t.jsxs(Tt,{variant:"secondary",children:[h.percentage,"%"]})]},h.id||J))})]})}),t.jsx(at,{className:w?"border-green-200 dark:border-green-800":"border-dashed",children:t.jsx(rt,{className:"pt-4 pb-4",children:w?t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx(qs,{className:"w-6 h-6 text-green-600"}),t.jsxs("div",{children:[t.jsx("p",{className:"font-semibold text-sm text-green-700 dark:text-green-400",children:"Quote Accepted & Signed"}),t.jsxs("p",{className:"text-xs text-muted-foreground",children:["Thank you, ",e.customer_name,"!"]})]}),w&&t.jsx("img",{src:w,alt:"Signature",className:"ml-auto h-12 object-contain"})]}):t.jsxs("div",{className:"text-center py-4",children:[t.jsx(Oa,{className:"w-8 h-8 mx-auto text-muted-foreground/40 mb-2"}),t.jsx("p",{className:"text-sm font-medium mb-1",children:"Ready to move forward?"}),t.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Sign electronically to accept this quote"}),t.jsxs(X,{onClick:M,className:"gap-2",children:[t.jsx(Oa,{className:"w-4 h-4"}),"Accept & Sign Quote"]})]})})})]})}function wf({onClick:e,hasItems:s=!1}){return t.jsxs(X,{variant:s?"outline":"default",size:"sm",onClick:e,className:"gap-1.5",children:[t.jsx(Or,{className:"w-4 h-4"}),s?"AI Reconfigure":"Quick Start"]})}function vf({quoteId:e,disabled:s=!1}){const[a,r]=m.useState(null),[n,i]=m.useState(!1),[l,u]=m.useState(!1),c=async()=>{var j,w;if(!e){$.error("Save the quote first to generate a microsite link");return}i(!0);try{const A=await ge.functions.invoke("generatePortalToken",{action:"generate",entity_type:"quote",entity_id:e});(j=A.data)!=null&&j.share_url?(r(A.data.share_url),$.success("Microsite link generated!")):$.error(((w=A.data)==null?void 0:w.error)||"Failed to generate link")}catch{$.error("Failed to generate microsite link")}finally{i(!1)}},d=()=>{navigator.clipboard.writeText(a),u(!0),$.success("Microsite link copied to clipboard"),setTimeout(()=>u(!1),2e3)};return a?t.jsxs("div",{className:"flex items-center gap-2",children:[t.jsxs(X,{variant:"outline",size:"sm",onClick:d,className:"shrink-0",children:[l?t.jsx(Ba,{className:"w-4 h-4 mr-1.5 text-green-600"}):t.jsx(Er,{className:"w-4 h-4 mr-1.5"}),l?"Copied!":"Copy Microsite"]}),t.jsx(X,{variant:"ghost",size:"sm",asChild:!0,className:"shrink-0",children:t.jsxs("a",{href:a,target:"_blank",rel:"noopener noreferrer",children:[t.jsx(Ri,{className:"w-4 h-4 mr-1.5"}),"Open"]})})]}):t.jsxs(X,{variant:"outline",size:"sm",onClick:c,disabled:s||n,className:"shrink-0",children:[t.jsx(Pi,{className:"w-4 h-4 mr-1.5"}),n?"Generating…":"Share Microsite"]})}function Nf({quoteId:e,quoteNumber:s,onEdit:a,onEmail:r,canEmail:n,isEmailing:i,onText:l,canText:u,isTexting:c,onWhatsApp:d,canWhatsApp:j,isWhatsApping:w,onPrint:A,canPrint:M,isPrinting:T,onPdf:D,canPdf:Y,isExportingPdf:P,onRevisions:h,onPayment:J,isCreatingPaymentLink:z,paymentLinkUrl:B,onEsign:U,isSendingContract:oe,contractSent:Ne,onRefreshCosts:ue,isRefreshingCosts:je,onCreateSalesOrder:ye,isCreatingSalesOrder:W,onNewQuote:V,onSave:q,isSaving:E=!1,onSaveAndCreateJob:be,canCreateJob:we=!1}){return t.jsx("div",{className:"fixed bottom-0 left-0 right-0 z-40 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 border-t shadow-lg",children:t.jsx("div",{className:"max-w-4xl mx-auto px-4 py-2.5",children:t.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[t.jsx("div",{className:"flex items-center gap-2 min-w-0",children:t.jsx("span",{className:"text-xs font-semibold text-muted-foreground hidden sm:inline truncate",children:s})}),t.jsxs("div",{className:"flex items-center gap-1 flex-wrap justify-end",children:[q&&t.jsxs(X,{onClick:q,disabled:E,className:"gap-1.5 shrink-0 h-8",size:"sm",children:[E?t.jsx(Bt,{className:"w-4 h-4 animate-spin"}):t.jsx(Ka,{className:"w-4 h-4"}),t.jsx("span",{className:"hidden sm:inline",children:"Save"})]}),be&&we&&t.jsxs(X,{variant:"outline",onClick:be,disabled:E,className:"gap-1.5 shrink-0 h-8",size:"sm",children:[t.jsx(Ga,{className:"w-4 h-4"}),t.jsx("span",{className:"hidden sm:inline",children:"Create Job"})]}
95),t.jsx(zi,{isSaved:!0,onEdit:a,onEmail:r,canEmail:n,isEmailing:i,onText:l,canText:u,isTexting:c,onWhatsApp:d,canWhatsApp:j,isWhatsApping:w,onPrint:A,canPrint:M,isPrinting:T,onPdf:D,canPdf:Y,isExportingPdf:P,onRevisions:h,onPayment:J,isCreatingPaymentLink:z,paymentLinkUrl:B,onEsign:U,isSendingContract:oe,contractSent:Ne,onRefreshCosts:ue,isRefreshingCosts:je,onCreateSalesOrder:ye,isCreatingSalesOrder:W}),e&&t.jsx(vf,{quoteId:e}),t.jsxs(X,{variant:"outline",size:"sm",onClick:V,className:"shrink-0 gap-1",children:[t.jsx(It,{className:"w-4 h-4"}),"New"]})]})]})})})}function kf({materialImageUrl:e,materialName:s}){const[a,r]=m.useState(!1),[n,i]=m.useState(null),[l,u]=m.useState(.55),[c,d]=m.useState(1),j=m.useRef(null),w=m.useRef(null),A=async()=>{try{const T=await navigator.mediaDevices.getUserMedia({video:{facingMode:"environment"},audio:!1});w.current=T,j.current&&(j.current.srcObject=T),r(!0),i(null)}catch{i("Camera not available. Try on a mobile device with camera permissions enabled.")}},M=()=>{w.current&&(w.current.getTracks().forEach(T=>T.stop()),w.current=null),r(!1)};return m.useEffect(()=>()=>{w.current&&w.current.getTracks().forEach(T=>T.stop())},[]),a?t.jsxs("div",{className:"fixed inset-0 z-50 bg-black",children:[t.jsx("video",{ref:j,autoPlay:!0,playsInline:!0,className:"w-full h-full object-cover"}),e&&t.jsx("img",{src:e,alt:s,className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 rounded-lg pointer-events-none",style:{opacity:l,width:`${70*c}%`,height:`${45*c}%`,objectFit:"cover"}}),t.jsxs("div",{className:"absolute top-4 left-4 right-4 flex items-center justify-between",children:[t.jsxs("div",{className:"bg-black/60 text-white px-3 py-1.5 rounded-lg text-sm",children:[s," Preview"]}),t.jsx(X,{variant:"destructive",size:"icon",onClick:M,children:t.jsx(ca,{className:"w-5 h-5"})})]}),t.jsxs("div",{className:"absolute bottom-4 left-4 right-4 flex gap-3",children:[t.jsxs("div",{className:"flex-1 bg-black/60 rounded-lg p-2",children:[t.jsxs("label",{className:"text-white text-xs block mb-0.5",children:["Opacity: ",Math.round(l*100),"%"]}),t.jsx("input",{type:"range",min:"20",max:"100",value:l*100,onChange:T=>u(T.target.value/100),className:"w-full"})]}),t.jsxs("div",{className:"flex-1 bg-black/60 rounded-lg p-2",children:[t.jsxs("label",{className:"text-white text-xs block mb-0.5",children:["Size: ",Math.round(c*100),"%"]}),t.jsx("input",{type:"range",min:"50",max:"200",value:c*100,onChange:T=>d(T.target.value/100),className:"w-full"})]})]})]}):t.jsx(at,{children:t.jsx(rt,{className:"pt-6",children:t.jsxs("div",{className:"text-center",children:[t.jsx(ti,{className:"w-10 h-10 text-primary mx-auto mb-2"}),t.jsx("h3",{className:"font-semibold text-sm",children:"AR Kitchen Preview"}),t.jsxs("p",{className:"text-xs text-muted-foreground mt-1 mb-3 max-w-xs mx-auto",children:["Point your camera at your kitchen to see ",s||"the selected material"," overlaid live."]}),t.jsxs(X,{onClick:A,disabled:!e,size:"sm",children:[t.jsx(ti,{className:"w-4 h-4 mr-2"})," Launch AR Preview"]}),n&&t.jsx("p",{className:"text-xs text-destructive mt-2",children:n})]})})})}const Ni=e=>(Number(e)||0).toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2});function Sf({depositSchedule:e=[],deposits:s=[],total:a=0,stagedPayment:r=0}){const n=e.length>0?e:[{id:"deposit",label:"Deposit",percentage:100}];let i=s.reduce((d,j)=>d+(Number(j.amount)||0),0)+(r||0);const l=n.map(d=>{const j=a*d.percentage/100,w=Math.min(i,j);i-=w;const A=w>=j&&j>0,M=w>0&&w<j;return{...d,target:j,paid:w,status:A?"paid":M?"partial":"pending"}}),u=l.every(d=>d.status==="paid"),c=l.some(d=>d.status!=="pending");return a<=0?null:t.jsxs("div",{className:"space-y-2",children:[t.jsxs("div",{className:"flex items-center justify-between",children:[t.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:"Payment Progress"}),u?t.jsxs(Tt,{className:"bg-green-100 text-green-700 border-green-200 text-[10px] gap-1",children:[t.jsx(Hs,{className:"w-3 h-3"})," Fully Paid"]}):c?t.jsxs(Tt,{className:"bg-amber-100 text-amber-700 border-amber-200 text-[10px] gap-1",children:[t.jsx(js,{className:"w-3 h-3"})," Partially Paid"]}):t.jsxs(Tt,{className:"bg-slate-100 text-slate-600 border-slate-200 text-[10px] gap-1",children:[t.jsx(Ar,{className:"w-3 h-3"})," Deposit Pending"]})]}),t.jsx("div",{className:"flex items-stretch",children:l.map((d,j)=>{const w=d.status==="paid"?Hs:d.status==="partial"?js:Va,A=d.status==="paid"?"text-green-500":d.status==="partial"?"text-amber-500":"text-slate-300 dark:text-slate-600",M=j===l.length-1,T=d.status==="paid"?"bg-green-400":"bg-slate-200 dark:bg-slate-700";return t.jsxs("div",{className:"flex flex-col items-center flex-1 min-w-0",children:[t.jsxs("div",{className:"flex items-center w-full",children:[!M&&j!==0&&t.jsx("div",{className:`flex-1 h-0.5 ${T}`}),j===0&&t.jsx("div",{className:`flex-1 h-0.5 ${d.status==="paid"?"bg-green-400":"bg-transparent"}`}),t.jsx("div",{className:`shrink-0 z-10 ${A}`,children:t.jsx(w,{className:"w-5 h-5"})}),M?t.jsx("div",{className:"flex-1"}):t.jsx("div",{className:`flex-1 h-0.5 ${T}`})]}),t.jsxs("div",{className:"text-center mt-1 px-0.5 w-full",children:[t.jsx("p",{className:"text-[10px] font-medium leading-tight truncate",children:d.label}),t.jsxs("p",{className:"text-[10px] text-muted-foreground tabular-nums",children:["$",Ni(d.target)]}),d.status!=="pending"&&t.jsxs("p",{className:`text-[9px] tabular-nums font-medium ${d.status==="paid"?"text-green-600":"text-amber-600"}`,children:["$",Ni(d.paid)," paid"]})]})]},d.id||j)})})]})}const Cf={credit_card:"Credit Card",debit_card:"Debit Card",cash:"Cash",zelle:"Zelle",ach:"ACH",check:"Check",mixed:"Mixed"},Mf=[{id:"cash",label:"Cash",icon:xr},{id:"zelle",label:"Zelle",icon:Wr},{id:"ach",label:"ACH",icon:xr},{id:"check",label:"Check",icon:xr}],Qt=e=>
95(Number(e)||0).toLocaleString(void 0,{minimumFractionDigits:2,maximumFractionDigits:2}),Df=[{id:"half_now",label:"Half Now",desc:"50% deposit · 50% on completion",milestones:[{label:"Deposit",percentage:50},{label:"On Completion",percentage:50}]},{id:"classic",label:"50/30/20",desc:"Deposit · Template · Install",milestones:[{label:"Deposit",percentage:50},{label:"Template",percentage:30},{label:"Installation",percentage:20}]},{id:"thirds",label:"Thirds",desc:"33% · 33% · 34% milestones",milestones:[{label:"Deposit",percentage:33},{label:"Template",percentage:33},{label:"Installation",percentage:34}]},{id:"light",label:"Light",desc:"25% deposit · 75% on completion",milestones:[{label:"Deposit",percentage:25},{label:"On Completion",percentage:75}]},{id:"full",label:"Full",desc:"100% paid now",milestones:[{label:"Deposit",percentage:100}]}];function Pf({isRush:e=!1,onToggleRush:s,rushPremiumPct:a=15,rushPremiumAmount:r=0,subtotal:n=0,discountAmount:i=0,taxAmount:l=0,ccFeeAmount:u=0,total:c=0,taxRate:d=0,onTaxRateChange:j,isTaxExemptAccount:w=!1,discountType:A="none",onDiscountTypeChange:M,discountValue:T=0,onDiscountValueChange:D,applyCreditCardFee:Y=!1,onApplyCreditCardFeeChange:P,creditCardFeeRate:h=3,ccFeeEnabled:J=!0,ccFeeAdminOverride:z=!0,effectiveFeeRate:B=3,isAdmin:U=!1,depositSchedule:oe=[],onDepositScheduleChange:Ne,deposits:ue=[],paymentsReceived:je=0,onRecordPayment:ye,onRemoveDeposit:W,paymentMethod:V="credit_card",onPaymentMethodChange:q,canRecord:E=!1,onEmailPaymentLink:be,isEmailingPaymentLink:we=!1,paymentLinkUrl:le=null,stagedPayment:me=0,quoteId:De=null}){const[Ge,Ue]=m.useState(""),[nt,lt]=m.useState(!1),fe=ue.reduce((te,Ce)=>te+(Number(Ce.amount)||0),0)+(me||0),Ke=Math.max(0,c-fe),et=Math.max(0,fe-c),it=c>0?Math.min(100,fe/c*100):0,Xe=Ke===0&&c>0,pt=Ke>0?Ke:0,x=parseFloat(Ge)||pt,Q=x*(B/100),C=x+(Y?Q:0);(()=>{var Ce;if(!(oe!=null&&oe.length))return null;const te=oe.map(Oe=>Oe.percentage);return((Ce=Df.find(Oe=>Oe.milestones.length===te.length&&Oe.milestones.every((b,tt)=>b.percentage===te[tt])))==null?void 0:Ce.id)||null})();const ne=async()=>{var te,Ce,Oe,b;if(!De){$.error("Save the quote first to take a payment");return}if(x<.5){$.error("Minimum card charge is $0.50");return}lt(!0);try{const tt=await ge.functions.invoke("createQuoteCheckout",{quote_id:De,amount:x,card_type:V,return_path:"/quote"});if((te=tt.data)!=null&&te.redirectUrl){window.location.href=tt.data.redirectUrl;return}throw new Error(((Ce=tt.data)==null?void 0:Ce.error)||"No checkout URL returned")}catch(tt){lt(!1),$.error(((b=(Oe=tt==null?void 0:tt.response)==null?void 0:Oe.data)==null?void 0:b.error)||tt.message||"Could not start card payment")}},ce=te=>{const Ce=parseFloat(Ge)||pt;if(Ce<=0){$.error("Enter an amount first");return}ye==null||ye(Ce,te),Ue("")};return t.jsx(at,{className:Xe?"border-green-200 dark:border-green-800":"border-primary/20",children:t.jsxs(rt,{className:"p-4 space-y-3",children:[s&&t.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2 pb-3 border-b border-border",children:[t.jsxs("div",{className:"flex items-center gap-2.5",children:[t.jsx("div",{className:`w-9 h-9 rounded-full flex items-center justify-center transition-colors shrink-0 ${e?"bg-orange-500/15":"bg-blue-500/15"}`,children:e?t.jsx(bo,{className:"w-4 h-4 text-orange-500"}):t.jsx(js,{className:"w-4 h-4 text-blue-500"})}),t.jsxs("div",{children:[t.jsx("p",{className:"font-semibold text-sm leading-tight",children:e?"Rush Production":"Standard Timeline"}),t.jsx("p",{className:"text-[11px] text-muted-foreground leading-tight",children:e?`+${a}% premium · +$${Qt(r)}`:"Standard production timeline"})]})]}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("span",{className:`text-[11px] ${e?"text-muted-foreground":"font-semibold text-blue-600"}`,children:"Standard"}),t.jsx("button",{onClick:()=>s(!e),className:`relative w-11 h-6 rounded-full transition-colors ${e?"bg-orange-500":"bg-blue-500"}`,children:t.jsx("span",{className:`absolute top-0.5 w-5 h-5 bg-white rounded-full shadow transition-transform ${e?"translate-x-5":"translate-x-0.5"}`})}),t.jsx("span",{className:`text-[11px] ${e?"font-semibold text-orange-600":"text-muted-foreground"}`,children:"Rush"})]})]}),t.jsxs("div",{className:"bg-slate-50 dark:bg-slate-900/40 border border-border rounded-lg p-2.5 space-y-2",children:[t.jsx("p",{className:"text-[11px] font-semibold text-muted-foreground uppercase tracking-wide",children:"Tax, Discount & Fees"}),t.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[t.jsx("span",{className:"text-xs text-muted-foreground w-12 shrink-0",children:"Discount"}),t.jsx("div",{className:"flex gap-1",children:[{id:"none",label:"None"},{id:"percentage",label:"%"},{id:"fixed",label:"$"}].map(te=>t.jsx("button",{onClick:()=>M==null?void 0:M(te.id),className:`px-2 h-7 rounded-md text-[11px] font-medium border transition-colors ${A===te.id?"bg-primary text-primary-foreground border-primary":"bg-transparent text-muted-foreground border-border hover:border-primary/40"}`,children:te.label},te.id))}),A!=="none"&&t.jsx(He,{type:"number",value:T,onChange:te=>D(parseFloat(te.target.value)||0),placeholder:A==="percentage"?"10":"100",className:"h-7 w-16 text-xs"})]}),t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("span",{className:"text-xs text-muted-foreground w-12 shrink-0",children:"Tax"}),w?t.jsx(Tt,{className:"bg-success/10 text-success border-success/20 text-[10px]",children:"Exempt"}):t.jsxs("div",{className:"flex items-center gap-1",children:[t.jsx(He,{type:"number",value:d,onChange:te=>j(parseFloat(te.target.value)||0),step:"0.1",className:"h-7 w-16 text-xs"}),t.jsx("span",{className:"text-xs text-muted-foreground",children:"%"})]})]}),J&&t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx("span",{className:"text-xs text-muted-foreground w-12 shrink-0",children:"Card Fee"}),t.jsx("button",{onClick:()=>
95{if(Y&&z&&!U){$.error("Only an admin can remove the credit card fee.");return}P(!Y)},className:`px-2.5 h-7 rounded-md text-[11px] font-medium border transition-colors ${Y?"bg-primary text-primary-foreground border-primary":"bg-transparent text-muted-foreground border-border hover:border-primary/40"}`,children:Y?`On · ${B}%`:"Off"})]})]}),c>0&&t.jsxs("div",{className:"space-y-1.5",children:[t.jsxs("div",{className:"flex justify-between items-center text-xs",children:[t.jsxs("span",{className:"text-muted-foreground",children:["Paid ",t.jsxs("span",{className:"text-success font-semibold",children:["$",Qt(fe)]})]}),et>0?t.jsxs("span",{className:"text-muted-foreground",children:["Balance ",t.jsx("span",{className:"font-bold text-green-600",children:"$0.00"})," · Credit ",t.jsxs("span",{className:"font-bold text-info",children:["$",Qt(et)]})]}):t.jsxs("span",{className:"text-muted-foreground",children:["Balance ",t.jsxs("span",{className:`font-bold ${Xe?"text-green-600":"text-foreground"}`,children:["$",Qt(Ke)]})]})]}),t.jsx("div",{className:"h-1.5 bg-slate-100 dark:bg-slate-700 rounded-full overflow-hidden",children:t.jsx("div",{className:"h-full bg-success rounded-full transition-all duration-300",style:{width:`${it}%`}})})]}),c>0&&t.jsx(Sf,{depositSchedule:oe,deposits:ue,stagedPayment:me,total:c}),ue.length>0&&t.jsx("div",{className:"space-y-1",children:ue.map((te,Ce)=>t.jsxs("div",{className:"flex items-center justify-between text-xs py-1 px-2 bg-slate-50 dark:bg-slate-900/40 rounded-md",children:[t.jsxs("div",{className:"flex items-center gap-1.5",children:[t.jsx(Tt,{variant:"secondary",className:"text-[10px] h-5",children:Cf[te.method]||te.method||"—"}),t.jsx("span",{className:"text-muted-foreground",children:te.date||""})]}),t.jsxs("div",{className:"flex items-center gap-1",children:[t.jsxs("span",{className:"font-semibold tabular-nums text-green-600",children:["$",Qt(te.amount)]}),W&&t.jsx(X,{variant:"ghost",size:"icon",className:"h-5 w-5",onClick:()=>W(te.id),children:t.jsx(Fs,{className:"w-3 h-3 text-red-400"})})]})]},te.id||Ce))}),E&&!Xe&&t.jsxs("div",{className:"space-y-2 pt-1",children:[t.jsxs("div",{className:"relative",children:[t.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-sm text-muted-foreground",children:"$"}),t.jsx(He,{type:"number",value:Ge,onChange:te=>Ue(te.target.value),placeholder:pt.toFixed(2),className:"h-11 pl-7 text-base font-medium",step:"0.01",min:"0"})]}),t.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[t.jsxs("button",{onClick:()=>q==null?void 0:q("credit_card"),className:`flex items-center justify-center gap-1.5 h-10 rounded-md border text-xs font-semibold transition-all ${V==="credit_card"?"bg-primary text-primary-foreground border-primary":"bg-transparent text-muted-foreground border-border hover:border-primary/40"}`,children:[t.jsx(la,{className:"w-3.5 h-3.5"})," Credit",V==="credit_card"&&J&&t.jsxs(Tt,{className:"ml-0.5 text-[9px] h-4 px-1 py-0 bg-warning/10 text-warning border-warning/20",children:["+",B,"%"]})]}),t.jsxs("button",{onClick:()=>q==null?void 0:q("debit_card"),className:`flex items-center justify-center gap-1.5 h-10 rounded-md border text-xs font-semibold transition-all ${V==="debit_card"?"bg-primary text-primary-foreground border-primary":"bg-transparent text-muted-foreground border-border hover:border-primary/40"}`,children:[t.jsx(la,{className:"w-3.5 h-3.5"})," Debit",V==="debit_card"&&t.jsx(Tt,{className:"ml-0.5 text-[9px] h-4 px-1 py-0 bg-success/10 text-success border-success/20",children:"No Fee"})]})]}),t.jsx(X,{onClick:ne,disabled:nt||x<.5,className:"w-full h-11 gap-2 text-sm font-semibold",children:nt?t.jsxs(t.Fragment,{children:[t.jsx(Bt,{className:"w-4 h-4 animate-spin"})," Opening checkout…"]}):t.jsxs(t.Fragment,{children:[t.jsx(la,{className:"w-4 h-4"})," Charge ",V==="debit_card"?"Debit":"Credit"," · $",Qt(x)]})}),x>0&&V==="credit_card"&&Y&&t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-muted-foreground px-1",children:[t.jsx(pr,{className:"w-3 h-3 text-green-500"}),t.jsxs("span",{children:["Customer pays ",t.jsxs("span",{className:"font-semibold text-foreground",children:["$",Qt(C)]})," · incl. $",Qt(Q)," fee"]})]}),x>0&&V==="debit_card"&&t.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] text-muted-foreground px-1",children:[t.jsx(pr,{className:"w-3 h-3 text-green-500"}),t.jsxs("span",{children:["Customer pays ",t.jsxs("span",{className:"font-semibold text-foreground",children:["$",Qt(x)]})," · no surcharge"]})]}),V==="credit_card"&&J&&t.jsxs("div",{className:"text-[10px] leading-relaxed text-muted-foreground bg-slate-50 dark:bg-slate-900/40 border border-border rounded-md p-2.5 space-y-1",children:[t.jsx("p",{className:"font-semibold text-foreground",children:"Credit Card Surcharge Disclosure"}),t.jsxs("p",{children:["A convenience fee of ",B,"% is applied to all credit card transactions to cover processing costs. This surcharge is not greater than our actual cost of acceptance. Debit card and ACH payments are not subject to this fee. The surcharge amount is displayed separately on your receipt and is non-refundable except in cases of documented billing errors."]})]}),t.jsxs("div",{className:"pt-1",children:[t.jsx("p",{className:"text-[11px] font-semibold text-muted-foreground uppercase tracking-wide mb-1.5",children:"Other Methods — Record Payment"}),t.jsx("div",{className:"grid grid-cols-2 gap-1.5",children:Mf.map(te=>{const Ce=te.icon;return t.jsxs("button",{onClick:()=>ce(te.id),className:`flex items-center justify-center gap-1.5 h-9 rounded-md border text-xs font-medium transition-all ${V===te.id?"bg-primary text-primary-foreground border-primary":"bg-transparent text-muted-foreground border-border hover:border-primary/40 hover:text-foreground"}`,children:[t.jsx(Ce,{className:"w-3.5 h-3.5"})," ",te.label]},te.id)})})]}),be&&t.jsx(X,{variant:"ghost",size:"sm",className:"w-full h-8 gap-1.5 text-xs text-muted-foreground",onClick:be,disabled:we,children:we?t.jsxs(t.Fragment,{children:[t.jsx(Bt,{className:"w-3.5 h-3.5 animate-spin"})," Sending…"]}):t.jsxs(t.Fragment,{children:[t.jsx($r,{className:"w-3.5 h-3.5"})," ",le?"Resend":"Email"," payment link"]})})]}),Xe&&t.jsxs("div",{className:"flex items-center justify-center gap-2 py-2 text-success font-semibold text-sm",children:[t.jsx(pr,{className:"w-4 h-4"})," Paid in Full"]})]})})}const Tf={margin_factor:"Margin Health",sqft_factor:"Project Size",response_time_factor:"Response Speed",material_factor:"Material Appeal",customer_history_factor:"Customer History"};function qf({score:e,factors:s,lastUpdated:a,isAdmin:r=!0}){if(!r||e==null)return null;const n=e>=70?"text-green-600":e>=40?"text-amber-600":"text-red-600",i=e>=70?"bg-green-500":e>=40?"bg-amber-500":"bg-red-500",l=e>=70?"Likely to Close":e>=40?"On the Fence":"At Risk",u=e>=70?Hs:e>=40?Aa:Ar;return t.jsxs(at,{children:[t.jsx(Ua,{className:"pb-2",children:t.jsxs(Ha,{className:"flex items-center justify-between text-sm",children:[t.jsxs("span",{className:"flex items-center gap-2",children:[t.jsx(Aa,{className:"w-4 h-4 text-primary"})," Acceptance Score"]}),a&&t.jsxs("span",{className:"text-[10px] text-muted-foreground font-normal",children:["Updated ",new Date(a).toLocaleDateString()]})]})}),t.jsxs(rt,{children:[t.jsxs("div",{className:"flex items-center gap-4",children:[t.jsxs("div",{className:"relative w-20 h-20 shrink-0",children:[t.jsxs("svg",{className:"w-full h-full -rotate-90",viewBox:"0 0 100 100",children:[t.jsx("circle",{cx:"50",cy:"50",r:"42",fill:"none",stroke:"currentColor",strokeWidth:"8",className:"text-muted"}),t.jsx("circle",{cx:"50",cy:"50",r:"42",fill:"none",stroke:"currentColor",strokeWidth:"8",strokeDasharray:`${e/100*2
9564} 264`,strokeLinecap:"round",className:n})]}),t.jsx("div",{className:"absolute inset-0 flex items-center justify-center",children:t.jsx("span",{className:`text-xl font-bold ${n}`,children:e})})]}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[t.jsx(u,{className:`w-4 h-4 ${n}`}),t.jsx("span",{className:`font-semibold text-sm ${n}`,children:l})]}),t.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:e>=70?"Tracking well — focus on closing.":e>=40?"Needs attention to improve close odds.":"High risk — consider adjusting price."})]})]}),s&&t.jsx("div",{className:"mt-3 space-y-1.5",children:Object.entries(s).filter(([,c])=>c!=null).map(([c,d])=>t.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[t.jsx("span",{className:"w-28 text-muted-foreground shrink-0",children:Tf[c]||c}),t.jsx("div",{className:"flex-1 h-1.5 bg-muted rounded-full overflow-hidden",children:t.jsx("div",{className:`h-full ${i}`,style:{width:`${d}%`}})}),t.jsxs("span",{className:"w-8 text-right text-muted-foreground",children:[d,"%"]})]},c))})]})]})}function Ff({quoteId:e,micrositeToken:s,comments:a=[]}){const[r,n]=m.useState(!1),i=s?`${window.location.origin}/microsite?token=${s}`:e?`${window.location.origin}/sign-quote?sign=${e}`:null;if(!i)return null;const l=()=>{navigator.clipboard.writeText(i),n(!0),$.success("Collaborative link copied!"),setTimeout(()=>n(!1),2e3)};return t.jsx(at,{children:t.jsxs(rt,{className:"pt-6",children:[t.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[t.jsx("div",{className:"w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center shrink-0",children:t.jsx(jo,{className:"w-5 h-5 text-primary"})}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsx("p",{className:"font-semibold text-sm",children:"Collaborative Quote Link"}),t.jsx("p",{className:"text-xs text-muted-foreground",children:"Share with spouse or co-decision maker"})]}),a.length>0&&t.jsxs(Tt,{variant:"outline",className:"shrink-0",children:[t.jsx(Rr,{className:"w-3 h-3 mr-1"})," ",a.length]})]}),t.jsxs("div",{className:"flex gap-2",children:[t.jsxs(X,{variant:"outline",size:"sm",className:"flex-1",onClick:l,children:[r?t.jsx(Ba,{className:"w-4 h-4 mr-1"}):t.jsx(Er,{className:"w-4 h-4 mr-1"}),r?"Copied!":"Copy Link"]}),t.jsxs(X,{variant:"outline",size:"sm",className:"flex-1",onClick:()=>window.open(i,"_blank"),children:[t.jsx(Ri,{className:"w-4 h-4 mr-1"})," Open"]})]}),t.jsx("p",{className:"text-[10px] text-muted-foreground mt-2 text-center",children:"Anyone with this link can view and comment on the quote"})]})})}function Lf({sentDate:e,initialDiscountPct:s=5,dailyDecrementPct:a=1}){const[r,n]=m.useState(0);if(m.useEffect(()=>{if(!e)return;const u=()=>{const d=new Date(e);n(Math.floor((new Date-d)/864e5))};u();const c=setInterval(u,6e4);return()=>clearInterval(c)},[e]),!e)return null;const i=Math.max(0,s-r*a),l=Math.ceil(i/a);return t.jsx(at,{className:`border-2 ${i>0?"border-amber-300 bg-amber-50 dark:bg-amber-950/30 dark:border-amber-700":"border-muted"}`,children:t.jsx(rt,{className:"pt-6",children:i>0?t.jsxs("div",{className:"flex items-center gap-3",children:[t.jsx("div",{className:"w-12 h-12 rounded-full bg-amber-500/20 flex items-center justify-center shrink-0",children:t.jsx(ai,{className:"w-6 h-6 text-amber-600"})}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsxs("p",{className:"font-bold text-amber-700 dark:text-amber-400",children:[i,"% Discount Available Today!"]}),t.jsx("p",{className:"text-xs text-amber-600 dark:text-amber-500",children:l>0?`Shrinks by ${a}% in ${l} day${l!==1?"s":""} — accept now to lock it in!`:"This discount expires today!"})]}),t.jsxs("div",{className:"text-right shrink-0",children:[t.jsx(Ai,{className:"w-5 h-5 text-amber-500 ml-auto mb-1"}),t.jsxs("p",{className:"text-[10px] text-muted-foreground",children:["Day ",r+1]})]})]}):t.jsxs("div",{className:"flex items-center gap-3 opacity-60",children:[t.jsx(ai,{className:"w-6 h-6 text-muted-foreground shrink-0"}),t.jsx("p",{className:"text-sm text-muted-foreground",children:"The early-bird discount window has ended."})]})})})}function Af({total:e,marginPct:s,targetMargin:a,onSave:r,canSave:n,isSaving:i,onSaveAndCreateJob:l,canCreateJob:u=!1}){const c=s>=(a||75)?"text-success":s>=30?"text-warning":"text-destructive";return t.jsx("div",{className:"fixed bottom-0 left-0 right-0 z-40 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 border-t shadow-lg",children:t.jsxs("div",{className:"max-w-4xl mx-auto px-4 py-2.5 flex items-center justify-between gap-3",children:[t.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[t.jsxs("div",{className:"min-w-0",children:[t.jsx("p",{className:"text-[10px] text-muted-foreground font-medium uppercase tracking-wide",children:"Total"}),t.jsxs("p",{className:"text-lg font-bold leading-tight truncate",children:["$",e.toLocaleStr
95ing(void 0,{minimumFractionDigits:2,maximumFractionDigits:2})]})]}),s>0&&t.jsxs("div",{className:"hidden sm:block border-l pl-3",children:[t.jsxs("p",{className:"text-[10px] text-muted-foreground font-medium uppercase tracking-wide flex items-center gap-0.5",children:[t.jsx(Aa,{className:"w-2.5 h-2.5"})," Margin"]}),t.jsxs("p",{className:`text-sm font-bold ${c}`,children:[s.toFixed(1),"%"]})]})]}),t.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[l&&u&&t.jsxs(X,{variant:"outline",onClick:l,disabled:!n||i,size:"sm",className:"hidden sm:inline-flex",children:[t.jsx(Ga,{className:"w-4 h-4"}),"Create Job"]}),t.jsxs(X,{onClick:r,disabled:i,className:"gap-1.5 shrink-0",size:"sm",children:[i?t.jsx(Bt,{className:"w-4 h-4 animate-spin"}):t.jsx(Ka,{className:"w-4 h-4"}),i?"Saving…":"Save Quote"]})]})]})})}function $f(e){if(!e)return null;try{const s=new Date(e);return isNaN(s.getTime())?null:s.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}catch{return null}}function Of({quote:e}){if(!e)return null;const s=e.sent_date||e.whatsapp_sent_date,a=!!s,r=e.contract_sent_date,n=r||e.contract_status==="sent"||e.contract_status==="signed",i=e.signature_date,l=!!(i||e.customer_signature),c=(Array.isArray(e.deposits)?e.deposits:[]).filter(w=>w&&w.date).map(w=>new Date(w.date)).sort((w,A)=>A-w)[0],d=e.payment_status==="paid"||(e.payment_amount_paid||0)>0,j=[{id:"sent",label:"Quote Sent",icon:Wr,done:a,date:s,extra:null},{id:"contract",label:"Contract Sent",icon:sc,done:n,date:r,extra:e.contract_status==="signed"?"Signed":e.contract_status==="declined"?"Declined":null},{id:"signed",label:"Customer Signed",icon:Hs,done:l,date:i,extra:null},{id:"payment",label:"Payment Received",icon:la,done:d,date:c?c.toISOString():null,extra:d?`$${(e.payment_amount_paid||0).toLocaleString()}`:null}];return t.jsx("div",{className:"rounded-xl border bg-card p-3 sm:p-4",children:t.jsx("div",{className:"flex items-center justify-between",children:j.map((w,A)=>{const M=w.done?w.icon:js;return t.jsxs(ho.Fragment,{children:[t.jsxs("div",{className:"flex flex-col items-center text-center min-w-0 flex-1",children:[t.jsx("div",{className:hr("w-9 h-9 rounded-full flex items-center justify-center shrink-0 transition-colors",w.done?"bg-success text-success-foreground":"bg-muted text-muted-foreground"),children:t.jsx(M,{className:"w-4 h-4"})}),t.jsx("span",{className:hr("text-xs font-medium mt-1.5 leading-tight",w.done?"text-primary":"text-muted-foreground"),children:w.label}),w.done?t.jsxs("span",{className:"text-[10px] text-muted-foreground mt-0.5 leading-tight",children:[$f(w.date),w.extra?` · ${w.extra}`:""]}):t.jsx("span",{className:"text-[10px] text-muted-foreground/60 mt-0.5",children:"Pending"})]}),A<j.length-1&&t.jsx("div",{className:hr("h-0.5 flex-1 mx-1 rounded-full transition-colors",j[A+1].done?"bg-success":"bg-border")})]},w.id)})})})}const Yf=t.jsx(at,{className:"border-dashed",children:t.jsx(rt,{className:"py-8 text-center text-sm text-muted-foreground",children:"3D preview unavailable in this browser. Edge profiles can still be selected from the dropdown on each line item."})});function tx(){var $n,On,Yn,Rn,In,En,Wn,zn,Un,Hn;const e=ac(),s=xa(),{user:a}=ki(),r=(a==null?void 0:a.role)==="admin",[n,i]=m.useState(!1),[l,u]=m.useState(null),[c,d]=m.useState({customer_name:"",customer_email:"",customer_phone:"",job_address:"",project_type:"kitchen",sqft:"",countertop_shape:"straight",material_type:"",material_name:"",edge_profile:"eased",sink_type:"none",sink_material:"",cooktop_included:!1,backsplash:!1,special_features:[],notes:""}),[j,w]=m.useState(null),[A,M]=m.useState([]),[T,D]=m.useState(null),[Y,P]=m.useState(0),[h,J]=m.useState(!1),[z,B]=m.useState(3),{data:U=[]}=jt({queryKey:["quote-settings-for-tax"],queryFn:()=>ge.entities.QuoteSettings.list(),initialData:[],staleTime:3e4}),oe=(($n=U[0])==null?void 0:$n.cc_fee_enabled)!==!1,Ne=((On=U[0])==null?void 0:On.cc_fee_admin_override)!==!1,ue=((Yn=U[0])==null?void 0:Yn.cc_fee_rate)??3,[je,ye]=m.useState("credit_card"),[W,V]=m.useState(0),[q,E]=m.useState("none"),[be,we]=m.useState(0),[le,me]=m.useState(!1),[De,Ge]=m.useState(null),[Ue,nt]=m.useState(!1),[lt,dt]=m.useState(!1),[fe,Ke]=m.useState(!1),[et,it]=m.useState(!1),[Xe,pt]=m.useState(!1),[x,Q]=m.useState(!1),[C,ne]=m.useState(!1),[ce,te]=m.useState(!1),[Ce,Oe]=m.useState(!1),[b,tt]=m.useState(null),[ms,ws]=m.useState(!1),[ee,k]=m.useState(!1),[Z,_e]=m.useState(!1),[Se,F]=m.useState(!1),[o,_]=m.useState(!1),[O,f]=m.useState(null),[I,N]=m.useState(!1),[p,L]=m.useState([]),[K,ae]=m.useState([]),[pe,xe]=m.useState([]),[ie,Ee]=m.useState(""),[Ae,H]=m.useState("imperial"),Me=m.useRef(!1),[Pe,We]=m.useState(null),[gt,wt]=m.useState([]),[Lt,St]=m.useState(""),[Rt,vs]=m.useState([]),[Zt,Ns]=m.useState(null),[ks,mn]=m.useState(null),[wa,hn]=m.useState(!1),{data:ft=[]}=jt({queryKey:["accounts"],queryFn:()=>ge.entities.Account.list(),staleTime:3e4}),fn=y=>{if(!y)return;const g=ft.find(R=>{var S;return((S=R.account_name)==null?void 0:S.toLowerCase())===y.toLowerCase()});if(g&&!c.job_address&&g.address){const R=[g.address,g.city,g.state,g.zip_code].filter(
95Boolean).join(", ");R&&d(S=>({...S,job_address:R}))}},Zs=new URLSearchParams(window.location.search).get("id");m.useEffect(()=>{const y=new URLSearchParams(window.location.search),g=y.get("customer_name"),R=y.get("account_id"),S=y.get("leadId");if(S&&w(S),g&&d(de=>({...de,customer_name:g,customer_email:y.get("customer_email")||de.customer_email,customer_phone:y.get("customer_phone")||de.customer_phone,job_address:y.get("job_address")||y.get("customer_address")||de.job_address})),R&&ft.length>0){const de=ft.find(qe=>qe.id===R);de&&(f(R),g||d(qe=>({...qe,customer_name:de.account_name||qe.customer_name,customer_email:de.email||qe.customer_email,customer_phone:de.phone||qe.customer_phone,job_address:y.get("job_address")||qe.job_address})),de.account_type==="contractor"&&de.contractor_discount_pct>0&&(E("percentage"),we(de.contractor_discount_pct)))}},[ft]);const{data:pn=[],isLoading:If}=jt({queryKey:["inventory-for-quote"],queryFn:()=>ge.entities.Inventory.list("-created_date",500),staleTime:3e4}),{data:xn=[],isLoading:Ef}=jt({queryKey:["material-price-list-for-quote"],queryFn:()=>ge.entities.MaterialPriceList.list("-created_date",500),staleTime:3e4}),{data:gn=[]}=jt({queryKey:["remnants-for-quote"],queryFn:()=>ge.entities.Remnant.list("-created_date",500),staleTime:3e4}),yn=m.useMemo(()=>gn.filter(y=>y.status==="available").map(y=>({...y,id:`remnant-${y.id}`,selling_price_per_sqft:y.sqft>0?(y.selling_price||0)/y.sqft:0,cost_per_sqft:y.sqft>0?(y.selling_price||0)/y.sqft:0,is_remnant:!0,supplier:"Remnant"})),[gn]),ut=m.useMemo(()=>[...xn.filter(y=>y.is_active!==!1),...pn,...yn],[xn,pn,yn]);m.useEffect(()=>{var y,g;if(U.length>0&&!Me.current&&!Zs&&!o){const R=(y=U[0])==null?void 0:y.tax_rate;R&&R>0&&P(R),Me.current=!0}U.length>0&&((g=U[0])!=null&&g.measurement_unit)&&H(U[0].measurement_unit)},[U]),m.useEffect(()=>{var R;if(U.length===0||ft.length===0)return;const y=((R=U[0])==null?void 0:R.tax_rate)??0,g=O?ft.find(S=>S.id===O):ft.find(S=>{var de;return c.customer_name&&((de=S.account_name)==null?void 0:de.toLowerCase())===c.customer_name.toLowerCase()});g&&(g.is_tax_exempt&&g.tax_id_form_url?(_(!0),P(0)):(_(!1),b||P(y)))},[U,ft,O,c.customer_name,b]);const{data:Ve}=jt({queryKey:["existing-quote",Zs],queryFn:()=>Zs?ge.entities.Quote.get(Zs):null,enabled:!!Zs,staleTime:3e4});m.useEffect(()=>{var y;if(Ve){tt(Ve),f(Ve.account_id||null),k(!1);let g=Ve.notes;if(typeof Ve.notes=="string")try{g=JSON.parse(Ve.notes)}catch{g={}}d({customer_name:Ve.customer_name||"",customer_email:Ve.customer_email||"",customer_phone:Ve.customer_phone||"",job_address:(g==null?void 0:g.job_address)||"",project_type:Ve.project_type||"kitchen",sqft:((y=Ve.sqft)==null?void 0:y.toString())||"",countertop_shape:(g==null?void 0:g.countertop_shape)||"straight",material_type:Ve.material_type||"",material_name:(g==null?void 0:g.material_name)||"",edge_profile:(g==null?void 0:g.edge_profile)||"eased",sink_type:(g==null?void 0:g.sink_type)||"none",sink_material:(g==null?void 0:g.sink_material)||"",cooktop_included:(g==null?void 0:g.cooktop_included)||!1,backsplash:(g==null?void 0:g.backsplash)||!1,special_features:(g==null?void 0:g.special_features)||[],notes:(g==null?void 0:g.notes)||""}),M((g==null?void 0:g.selected_slabs)||[]),D(Ve.customer_signature||null),Ns(Ve.layout_image_url||null),hn((g==null?void 0:g.is_rush)||!1),P(Ve.tax_rate||(g==null?void 0:g.tax_rate)||0),E(Ve.discount_type||"none"),we(Ve.discount_value||0),ye(Ve.payment_method||"credit_card"),J((g==null?void 0:g.apply_credit_card_fee)||!1),B((g==null?void 0:g.credit_card_fee_rate)||ue||3);const R=Ve.line_items||[];L(R.filter(S=>!S.item_type||S.item_type==="material").map(S=>{var de;return{name:S.name||"",area_name:S.area_name||"",length_inches:S.length_inches||"",width_inches:S.width_inches||"",item_type:S.item_type||"material",material_type:S.material_type||"",material_name:S.material_name||"",color:S.color||"",sqft:((de=S.sqft)==null?void 0:de.toString())||"",edge_profile:S.edge_profile||"eased",edge_linear_ft:S.edge_linear_ft||0,sink_type:S.sink_type||"none",sink_material:S.sink_material||"",cooktop_included:S.
95cooktop_included||!1,backsplash:S.backsplash||!1,special_features:S.special_features||[],unit_price_per_sqft:S.unit_price_per_sqft||0,material_cost:S.material_cost||0,labor_cost:S.labor_cost||0,total_cost:S.total_cost||0,selling_price:S.selling_price||0,notes:S.notes||"",markup_pct:S.markup_pct||0,hidden_from_customer:S.hidden_from_customer||!1,discount_pct:S.discount_pct||0,discount_approval_status:S.discount_approval_status||null,discount_requested_by:S.discount_requested_by||""}})),ae(R.filter(S=>S.item_type==="service").map(S=>({description:S.name||"",price:S.unit_price_per_sqft||0,qty:S.sqft||1,unit:S.unit||"each",markup_pct:S.markup_pct||0,notes:S.notes||"",hidden_from_customer:S.hidden_from_customer||!1,discount_pct:S.discount_pct||0,discount_approval_status:S.discount_approval_status||null,discount_requested_by:S.discount_requested_by||""}))),xe(R.filter(S=>S.item_type==="product").map(S=>({name:S.name||"",price:S.unit_price_per_sqft||0,qty:S.sqft||1,unit:S.unit||"each",markup_pct:S.markup_pct||0,notes:S.notes||"",hidden_from_customer:S.hidden_from_customer||!1,discount_pct:S.discount_pct||0,discount_approval_status:S.discount_approval_status||null,discount_requested_by:S.discount_requested_by||""}))),We(Ve.terms_and_conditions||null),wt(Ve.deposit_schedule||[]),St(Ve.expiry_date||""),vs(Ve.version_history||[]),u({id:Ve.id,quoteNumber:Ve.quote_number,sellingPrice:Ve.selling_price}),i(!1)}},[Ve]);const yt=(b==null?void 0:b.converted_to_job_id)||null,{data:_n=[]}=jt({queryKey:["quote-job-payments",yt],queryFn:()=>yt?ge.entities.Payment.filter({job_id:yt},"-payment_date",200):Promise.resolve([]),enabled:!!yt}),$l=m.useMemo(()=>yt?_n.filter(y=>y.status==="completed"&&y.payment_type!=="refund").map(y=>({id:y.id,amount:y.amount||0,method:y.payment_method||"cash",description:y.description||y.payment_type||"Deposit",date:y.payment_date?String(y.payment_date).split("T")[0]:""})):[],[yt,_n]),bn=yt?$l:(b==null?void 0:b.deposits)||[],As=()=>U[0]||{labor_rate_per_sqft:18,edge_profiling_rate_per_sqft:3.5,sink_cutout_flat_fee:75,cooktop_cutout_flat_fee:125,backsplash_rate_per_sqft:12,special_feature_flat_fee:50,default_margin_pct:75,default_timeline_days:7,minimum_sqft:0},{liveQuote:ve,pricedLineItems:Ol,combinedLineItems:Yl,profitabilityWarning:lr}=m.useMemo(()=>{var ea;const y=As(),{pricingSqfts:g}=Ei(p,y.minimum_sqft||0),R=p.map((v,ze)=>{parseFloat(v.sqft);const ot=g[ze],Mt=ut.find(mo=>mo.material_name===v.material_name),so=v.unit_price_per_sqft||(Mt==null?void 0:Mt.selling_price_per_sqft)||0,ao=(Mt==null?void 0:Mt.cost_per_sqft)||0,ro=v.markup_pct||0,Bn=so*(1+ro/100),no=v.sink_type&&v.sink_type!=="none"?y.sink_cutout_flat_fee:0,io=v.cooktop_included?y.cooktop_cutout_flat_fee:0,lo=v.backsplash?ot*y.backsplash_rate_per_sqft:0,oo=(v.special_features||[]).length*y.special_feature_flat_fee,Vn=(parseFloat(v.edge_linear_ft)||0)*(y.finished_edge_rate_per_linear_ft||0),Gn=no+io+lo+oo+Vn,Kn=ao*ot,Zn=(y.labor_rate_per_sqft||0)*ot,co=(Bn*ot+Gn)*(v.discount_approval_status==="approved"&&v.discount_pct?1-v.discount_pct/100:1),uo=Kn+Zn+Gn;return{...v,unit_price_per_sqft:Bn,edge_price_per_linear_ft:y.finished_edge_rate_per_linear_ft||0,edge_cost:Vn,material_cost:Kn,labor_cost:Zn,total_cost:uo,selling_price:co,sqft:v.sqft}}),S=K.filter(v=>v.description&&parseFloat(v.price)>0).map(v=>{const ze=parseFloat(v.price)||0,ot=v.markup_pct||0,Mt=parseFloat(v.qty)||1;return{item_type:"service",name:v.description,sqft:Mt,unit:v.unit||"each",unit_price_per_sqft:ze,selling_price:ze*(1+ot/100)*Mt*(v.discount_approval_status==="approved"&&v.discount_pct?1-v.discount_pct/100:1),markup_pct:ot}}),de=S.reduce((v,ze)=>v+ze.selling_price,0),qe=pe.filter(v=>v.name&&parseFloat(v.price)>0).map(v=>{const ze=parseFloat(v.price)||0,ot=v.markup_pct||0,Mt=parseFloat(v.qty)||1;return{item_type:"product",name:v.name,sqft:Mt,unit:v.unit||"each",unit_price_per_sqft:ze,selling_price:ze*(1+ot/100)*Mt*(v.discount_approval_status==="approved"&&v.discount_pct?1-v.discount_pct/100:1),markup_pct:ot}}),Fe=qe.reduce((v,ze)=>v+ze.selling_price,0),ke=R.reduce((v,ze)=>v+(ze.total_cost||0),0)+de+Fe,mt=R.reduce((v,ze)=>v+(ze.selling_price||0),0)+de+Fe,vt=mt>0?(mt-ke)/mt*100:0;if(!(p.some(v=>v.material_name&&parseFloat(v.sqft)>0)||K.length>0||pe.length>0))return{liveQuote:null,pricedLineItems:p,combinedLineItems:p,profitabilityWarning:null};const va=((ea=p[0])==null?void 0:ea.material_type)||"",Na=va==="quartz",ka=["granite","marble","quartzite","soapstone"].includes(va),Ss=R.reduce((v,ze)=>v+(ze.material_cost||0),0),hs=R.reduce((v,ze)=>v+(ze.labor_cost||0),0),Sa={total_cost:ke,material_cost:Ss,labor_cost:hs,selling_price:mt,margin_pct:vt,timeline_days:y.default_timeline_days,material_selling_points:Na?["Non-porous — never needs sealing","Scratch and stain resistant","Wide range of colors and patterns"]:ka?["Each slab is completely unique","Excellent heat resistance","Timeless natural beauty"]:["Premium material durability","Easy maintenance and cleaning","Adds value to your home"],recommendations:["Schedule template measurement within 2 weeks","Consider upgraded edge profile for enhanced aesthetics"],care_tips:Na?["Clean with mild soap and water","Use trivets for hot items","No sealing required — non-porous surface"]:ka?["Clean with mild soap and water","Use trivets for hot items","Seal annually for optimal protection"]:["Clean with mild soap and water","Use trivets for hot items"]};let Qs=null;vt<10&&(Qs={margin:vt.toFixed(1),totalCost:ke.toFixed(2),sellingPrice:mt.toFixed(2),message:vt<5?"CRITICAL: This quote will lose money!":"WARNING: Very low profit margin!",severity:vt<5?"critical":"high"});const Ct=[...R,...S,...qe];return{liveQuote:Sa,pricedLineItems:R,combinedLineItems:Ct,profitabilityWarning:Qs}},[p,K,pe,ut,U]),[Wf,jn]=m.useState(null),[zf,Rl]=m.useState([null,
95null,null]),or=m.useRef(null);m.useEffect(()=>{const y=p.find(R=>R.material_name),g=(y==null?void 0:y.material_type)||null;or.current!==null&&or.current!==g&&jn(null),or.current=g},[p]),m.useMemo(()=>{if(!p.length||!ut.length)return!1;const y=p.find(R=>R.material_name);return!y||!y.material_type?!1:new Set(ut.filter(R=>R.material_type===y.material_type&&R.is_active!==!1&&(R.cost_per_sqft||0)>0).map(R=>R.material_name)).size>=2},[p,ut]),m.useMemo(()=>{if(!p.length||!ut.length)return[];const y=p.find(Fe=>Fe.material_name);if(!y||!y.material_type)return[];const g=ut.filter(Fe=>Fe.material_type===y.material_type&&Fe.is_active!==!1&&(Fe.cost_per_sqft||0)>0&&Fe.selling_price_per_sqft).sort((Fe,ke)=>(Fe.selling_price_per_sqft||0)-(ke.selling_price_per_sqft||0));if(g.length<3)return[];const R=p.reduce((Fe,ke)=>Fe+(parseFloat(ke.sqft)||0),0),S=g[0],de=g[Math.floor(g.length/2)],qe=g[g.length-1];return[{material_name:S.material_name,price:(S.selling_price_per_sqft||0)*R,price_per_sqft:S.selling_price_per_sqft,image_url:S.image_url,features:["Quality material","Standard edge profile","Professional installation"]},{material_name:de.material_name,price:(de.selling_price_per_sqft||0)*R,price_per_sqft:de.selling_price_per_sqft,image_url:de.image_url,features:["Premium material","Upgraded edge profile","Expert craftsmanship","Enhanced durability"]},{material_name:qe.material_name,price:(qe.selling_price_per_sqft||0)*R,price_per_sqft:qe.selling_price_per_sqft,image_url:qe.image_url,features:["Luxury material","Premium edge profile","White-glove installation","Maximum durability","Extended warranty"]}]},[p,ut]);const wn=m.useMemo(()=>{var g;const y=p.find(R=>R.material_name);return y&&((g=ut.find(R=>R.material_name===y.material_name))==null?void 0:g.image_url)||null},[p,ut]),Il=m.useMemo(()=>O?ft.find(y=>y.id===O):c.customer_name?ft.find(y=>{var g;return((g=y.account_name)==null?void 0:g.toLowerCase())===c.customer_name.toLowerCase()}):null,[ft,c.customer_name,O]),El=m.useMemo(()=>{if(!(b!=null&&b.line_items))return null;const y=b.line_items.filter(g=>!g.item_type||g.item_type==="material").filter(g=>{if(!g.material_name)return!1;const R=p.find(de=>de.material_name===g.material_name);if(R&&Math.abs((R.unit_price_per_sqft||0)-(g.unit_price_per_sqft||0))>.01)return!1;const S=ut.find(de=>de.material_name===g.material_name);return S?Math.abs((S.selling_price_per_sqft||0)-(g.unit_price_per_sqft||0))>.01:!1});return y.length>0?y:null},[b,ut,p]),Wl=async(y,g)=>{const R=(l==null?void 0:l.id)||(b==null?void 0:b.id);if(!R){V(y),ye(g),$.success(`$${y.toFixed(2)} payment will be saved with the quote`);return}if(yt){try{await ge.entities.Payment.create({payment_number:`PAY-${new Date().getFullYear()}-${String(Date.now()).slice(-6)}`,job_id:yt,customer_name:c.customer_name,customer_email:c.customer_email,amount:y,payment_type:"deposit",payment_method:g,payment_processor:"manual",status:"completed",payment_date:new Date().toISOString(),description:"Deposit received",processed_by_id:a==null?void 0:a.id,processed_by_name:(a==null?void 0:a.full_name)||(a==null?void 0:a.email)}),s.invalidateQueries({queryKey:["quote-job-payments",yt]}),s.invalidateQueries({queryKey:["job-payments",yt]}),$.success(`Payment of $${y.toFixed(2)} recorded!`)}catch(ke){$.error("Failed to record payment"),console.error(ke)}return}const S={id:`dep-${Date.now()}`,amount:y,method:g,description:"Deposit received",date:new Date().toISOString().split("T")[0]},de=[...(b==null?void 0:b.deposits)||[],S],qe=de.reduce((ke,mt)=>ke+(Number(mt.amount)||0),0),Fe=(b==null?void 0:b.final_amount)||Xs;try{await ge.entities.Quote.update(R,{deposits:de,payment_amount_paid:qe,payment_status:qe>=Fe?"paid":"pending"}),tt(ke=>({...ke||{},id:(ke==null?void 0:ke.id)||R,final_amount:(ke==null?void 0:ke.final_amount)||Fe,selling_price:(ke==null?void 0:ke.selling_price)||(l==null?void 0:l.sellingPrice)||0,deposits:de,payment_amount_paid:qe,payment_status:qe>=Fe?"paid":"pending"})),s.invalidateQueries({queryKey:["existing-quote",R]}),s.invalidateQueries({queryKey:["customer-quotes"]}),$.success(`Payment of $${y.toFixed(2)} recorded!`)}catch(ke){$.error("Failed to record payment"),console.error(ke)}},zl=async y=>{const g=(l==null?void 0:l.id)||(b==null?void 0:b.id);if(!g)return;if(yt){try{await ge.entities.Payment.delete(y),s.invalidateQueries({queryKey:["quote-job-payments",yt]}),s.invalidateQueries({queryKey:["job-payments",yt]}),$.success("Payment removed")}catch(qe){$.error("Failed to remove payment"),console.error(qe)}return}if(!(b!=null&&b.deposits))return;const R=b.deposits.filter(qe=>qe.id!==y),S=R.reduce((qe,Fe)=>qe+(Number(Fe.amount)||0),0),de=(b==null?void 0:b.final_amount)||Xs;try{await ge.entities.Quote.update(g,{deposits:R,payment_amount_paid:S,payment_status:S>=de?"paid":"pending"}),tt(qe=>({...qe||{},deposits:R,payment_amount_paid:S,payment_status:S>=de?"paid":"pending"})),s.invalidateQueries({queryKey:["existing-quote",g]}),s.invalidateQueries({queryKey:["customer-quotes"]}),$.success("Payment removed")}catch(qe){$.error("Failed to remove payment"),console.error(qe)}},cr=async()=>{var de,qe;const y=O?ft.find(Fe=>Fe.id===O):ft.find(Fe=>{var ke;return((ke=Fe.account_name)==null?void 0:ke.toLowerCase())===c.customer_name.toLowerCase()});let g=y||null;if(!y&&c.customer_name)try{g=await ge.entities.Account.create({account_name:c.customer_name,contact_name:c.customer_name,email:c.customer_email,phone:c.customer_phone,address:c.job_address,account_type:"retail",status:"active"}),f(g.id),await s.invalidateQueries({queryKey:["accounts"]})}catch(Fe){console.error("Failed to create account:",Fe)}const R=await Xt(!0,g);if(!R)return;const S=$.loading("Creating job from quote...");try{const Fe=await ge.functions.invoke("convertQuoteToJob",{quoteId:R.id});(de=Fe.data)!=null&&de.jobId?($.dismiss(S),$.success("Job created! Opening schedule…"),s.invalidateQueries({queryKey:["jobs"]}),e(`/job/${Fe.data.jobId}?schedule=1`)):($.dismiss(S),$.error(((qe=Fe.data)==null?void 0:qe.error)||"Failed to create job"))}catch(Fe){$.dismiss(S),$.error("Failed to create job from quote"),console.error(Fe)}},Xt=async(y=!1,g=null)=>{var S,de,qe,Fe;const R=!!(b!=null&&b.id||l!=null&&l.id);if(!c.customer_name)return $.error("Please add a customer name"),null;if(lr&&lr.severity==="critical"&&!window.confirm(`⚠️ CRITICAL WARNING: This quote has only ${lr.margin}% margin and may lose money.
96
97Are you absolutely sure you want to proceed?`))return null;try{const ke=(b==null?void 0:b.quote_number)||(l==null?void 0:l.quoteNumber)||`Q-${new Date().getFullYear()}
97-${String(Date.now()).slice(-6)}`,mt=p.reduce((v,ze)=>v+(parseFloat(ze.sqft)||0),0),vt=((ve==null?void 0:ve.selling_price)||0)+(wa?Math.round(((ve==null?void 0:ve.selling_price)||0)*.15):0),Js=Ya({basePrice:vt,discountType:q,discountValue:be,taxRate:Y,applyCreditCardFee:h&&oe,ccFeeRate:z}),{discountAmount:va,taxAmount:Na,ccFeeAmount:ka}=Js,Ss=Js.finalTotal,hs=g||(O?ft.find(v=>v.id===O):ft.find(v=>{var ze;return((ze=v.account_name)==null?void 0:ze.toLowerCase())===c.customer_name.toLowerCase()}));let Sa=Zt;if(Zt&&Zt.startsWith("data:"))try{const v=await(await fetch(Zt)).blob(),ze=new File([v],`layout-${ke}.png`,{type:"image/png"}),ot=await ge.integrations.Core.UploadFile({file:ze});ot!=null&&ot.file_url&&(Sa=ot.file_url)}catch(v){console.error("Layout image upload failed:",v)}const Qs={quote_number:ke,customer_name:c.customer_name,customer_email:c.customer_email,customer_phone:c.customer_phone,account_id:(hs==null?void 0:hs.id)||null,account_name:(hs==null?void 0:hs.account_name)||null,project_type:c.project_type,material_type:((S=p.find(v=>v.material_type))==null?void 0:S.material_type)||void 0,sqft:mt,line_items:[...Ol.map(v=>({item_type:"material",name:v.name||v.material_name||"",area_name:v.area_name||"",length_inches:parseFloat(v.length_inches)||0,width_inches:parseFloat(v.width_inches)||0,material_type:v.material_type||"",material_name:v.material_name||"",color:v.color||"",sqft:parseFloat(v.sqft)||0,edge_profile:v.edge_profile||"eased",edge_linear_ft:v.edge_linear_ft||0,edge_price_per_linear_ft:v.edge_price_per_linear_ft||0,edge_cost:v.edge_cost||0,sink_type:v.sink_type||"none",sink_material:v.sink_material||"",cooktop_included:v.cooktop_included||!1,backsplash:v.backsplash||!1,special_features:v.special_features||[],unit_price_per_sqft:v.unit_price_per_sqft||0,material_cost:v.material_cost||0,labor_cost:v.labor_cost||0,total_cost:v.total_cost||0,selling_price:v.selling_price||0,notes:v.notes||"",markup_pct:v.markup_pct||0,hidden_from_customer:v.hidden_from_customer||!1,discount_pct:v.discount_pct||0,discount_approval_status:v.discount_approval_status||null,discount_requested_by:v.discount_requested_by||""})),...K.filter(v=>v.description&&parseFloat(v.price)>0).map(v=>({item_type:"service",name:v.description,material_type:"",material_name:"",sqft:parseFloat(v.qty)||1,unit:v.unit||"each",edge_profile:"",sink_type:"none",sink_material:"",cooktop_included:!1,backsplash:!1,special_features:[],unit_price_per_sqft:parseFloat(v.price)||0,material_cost:0,labor_cost:0,total_cost:(parseFloat(v.price)||0)*(1+(v.markup_pct||0)/100)*(parseFloat(v.qty)||1),selling_price:(parseFloat(v.price)||0)*(1+(v.markup_pct||0)/100)*(parseFloat(v.qty)||1),notes:v.notes||"",markup_pct:v.markup_pct||0,hidden_from_customer:v.hidden_from_customer||!1,discount_pct:v.discount_pct||0,discount_approval_status:v.discount_approval_status||null,discount_requested_by:v.discount_requested_by||""})),...pe.filter(v=>v.name&&parseFloat(v.price)>0).map(v=>({item_type:"product",name:v.name,material_type:"",material_name:"",sqft:parseFloat(v.qty)||1,unit:v.unit||"each",edge_profile:"",sink_type:"none",sink_material:"",cooktop_included:!1,backsplash:!1,special_features:[],unit_price_per_sqft:parseFloat(v.price)||0,material_cost:0,labor_cost:0,total_cost:(parseFloat(v.price)||0)*(1+(v.markup_pct||0)/100)*(parseFloat(v.qty)||1),selling_price:(parseFloat(v.price)||0)*(1+(v.markup_pct||0)/100)*(parseFloat(v.qty)||1),notes:v.notes||"",markup_pct:v.markup_pct||0,hidden_from_customer:v.hidden_from_customer||!1,discount_pct:v.discount_pct||0,discount_approval_status:v.discount_approval_status||null,discount_requested_by:v.discount_requested_by||""}))],material_cost:(ve==null?void 0:ve.material_cost)||(ve==null?void 0:ve.total_cost)||0,labor_cost:(ve==null?void 0:ve.labor_cost)||0,total_cost:(ve==null?void 0:ve.total_cost)||0,selling_price:Ss,margin_pct:(ve==null?void 0:ve.margin_pct)||0,status:T?"accepted":"draft",contract_status:T?"signed":(b==null?void 0:b.contract_status)||"not_sent",created_date:new Date().toISOString().split("T")[0],customer_signature:T,signature_date:T?new Date().toISOString():null,reserved_slab_ids:A.map(v=>v.id),addons:[],addon_total:0,payment_method:je,discount_type:q,discount_value:be,discount_amount:va,tax_rate:Y,tax_amount:Na,credit_card_fee_rate:h&&oe?z:0,credit_card_fee_amount:ka,final_amount:Ss,deposits:W>0?[...(b==null?void 0:b.deposits)||[],{id:`dep-${Date.now()}`,amount:W,method:je,description:"Deposit received",date:new Date().toISOString().split("T")[0]}]:(b==null?void 0:b.deposits)||[],payment_amount_paid:((b==null?void 0:b.payment_amount_paid)||0)+(W>0?W:0),payment_status:((b==null?void 0:b.payment_amount_paid)||0)+(W>0?W:0)>=Ss?"paid":"pending",notes:JSON.stringify({...c,job_address:c.job_address,ai_breakdown:ve||{},selected_slabs:A,addons:[],tax_rate:Y,credit_card_fee_rate:h&&oe?z:0,apply_credit_card_fee:h&&oe,is_rush:wa}),terms_and_conditions:Pe,deposit_schedule:gt,expiry_date:Lt||null,quote_template_id:ks,layout_image_url:Sa||(b==null?void 0:b.layout_image_url)||null,version_history:[...(b==null?void 0:b.version_history)||[],{version:(((de=b==null?void 0:b.version_history)==null?void 0:de.length)||0)+1,saved_at:new Date().toISOString(),saved_by:(a==null?void 0:a.full_name)||(a==null?void 0:a.email)||"Unknown",selling_price:Ss,status:T?"accepted":"draft"}]};let Ct;if(R){const v=(b==null?void 0:b.id)||(l==null?void 0:l.id);Ct=await ge.entities.Quote.update(v,Qs)}else Ct=await ge.entities.Quote.create(Qs);if(R&&((qe=b==null?void 0:b.reserved_slab_ids)!=null&&qe.length)){const v=b.sqft||0;for(const ze of b.reserved_slab_ids)try{const ot=await ge.entities.Inventory.get(ze);await ge.entities.Inventory.update(ze,{reserved_sqft:Math.max(0,((ot==null?void 0:ot.reserved_sqft)||0)-v)})}catch(ot){console.error("Failed to release old slab reservation:",ot)}}for(const v of A)await ge.entities.Inventory.update(v.id,{reserved_sqft:(v.reserved_sqft||0)+mt,reserved_for_quote_id:Ct.id,reserved_date:new Date().toISOString()});if(!R&&A.length>0)try{await ge.functions.invoke("autoHoldSlabsForQuote",{quoteId:Ct.id})}catch(v){console.error("Auto-hold creation failed:",v)}const ea=R?(b==null?void 0:b.converted_to_job_id)||(Ct==null?void 0:Ct.converted_to_job_id):null;if(ea)try{await ge.entities.Job.update(ea,{customer_name:c.customer_name,customer_email:c.customer_email,customer_phone:c.customer_phone,job_address:c.job_address})}catch(v){console.error("Failed to sync customer info to linked job:",v)}return j&&(await ge.entities.Lead.update(j,{status:"quoted",converted_to_job_id:Ct.id}),s.invalidateQueries({queryKey:["leads"]})),s.invalidateQueries({queryKey:["customer-quotes"]}),s.invalidateQueries({queryKey:["accounts"]}),s.invalidateQueries({queryKey:["jobs"]}),u({id:Ct.id,quoteNumber:ke,sellingPrice:Ss}
97),i(!0),V(0),$.success(R?"Quote updated successfully!":"Quote saved successfully!"),Ct}catch(ke){const mt=(Fe=ke==null?void 0:ke.response)==null?void 0:Fe.data,vt=mt&&(mt.error||mt.message||mt.detail)||(ke==null?void 0:ke.message)||(typeof mt=="string"?mt:null),Js=vt?`Failed to save quote: ${vt}`:`Failed to save quote: ${JSON.stringify(mt||(ke==null?void 0:ke.toString())||"unknown error").slice(0,300)}`;return $.error(Js),console.error("Quote save error:",ke),null}},vn=async(y=!1)=>{let g=l==null?void 0:l.id;if(!g){const R=await Xt(!0);if(!R)return;g=R.id}ne(!0),window.open(`/quote-pdf/${g}`,"_blank"),setTimeout(()=>ne(!1),500)},Nn=async()=>{let y=l==null?void 0:l.id;if(Q(!0),!y){const g=await Xt(!0);if(!g){Q(!1);return}y=g.id}Q(!1),e(`/quote-pdf/${y}`)},kn=async()=>{var y,g,R;if(!(l!=null&&l.id)){$.error("Please save the quote first");return}if(!c.customer_email){$.error("Customer email is required to send a payment link");return}me(!0);try{const S=await ge.functions.invoke("sendPaymentLink",{quoteId:l.id});if((y=S.data)!=null&&y.error){$.error(S.data.error);return}Ge(S.data.payment_link_url),$.success("Payment link created & emailed to customer!")}catch(S){$.error(((R=(g=S==null?void 0:S.response)==null?void 0:g.data)==null?void 0:R.error)||S.message||"Failed to create payment link")}finally{me(!1)}},[Ul,Sn]=m.useState(!1),Hl=async()=>{var y,g,R;if(!(l!=null&&l.id)){$.error("Please save the quote first");return}if(!c.customer_email){$.error("Customer email is required to send a payment link");return}Sn(!0);try{const S=await ge.functions.invoke("sendPaymentLink",{quoteId:l.id});if((y=S.data)!=null&&y.error){$.error(S.data.error);return}Ge(S.data.payment_link_url),$.success("Payment link emailed to customer!")}catch(S){$.error(((R=(g=S==null?void 0:S.response)==null?void 0:g.data)==null?void 0:R.error)||S.message||"Failed to send payment link")}finally{Sn(!1)}},Cn=async()=>{if(!(l!=null&&l.id)){$.error("Please save the quote first");return}if(!c.customer_email){$.error("Customer email is required");return}nt(!0);try{(await ge.functions.invoke("sendContractEmail",{quoteId:l.id})).data.success&&(dt(!0),$.success("Contract sent to customer!"))}catch{$.error("Failed to send contract.")}finally{nt(!1)}},Mn=async()=>{var g,R;const y=(l==null?void 0:l.id)||(b==null?void 0:b.id);if(!y){$.error("Save the quote first");return}te(!0);try{const S=await ge.functions.invoke("refreshQuoteCosts",{quoteId:y});(g=S.data)!=null&&g.success?($.success(S.data.message||"Costs refreshed"),s.invalidateQueries({queryKey:["existing-quote",y]}),s.invalidateQueries({queryKey:["customer-quotes"]})):$.error(((R=S.data)==null?void 0:R.error)||"Failed to refresh costs")}catch{$.error("Failed to refresh costs")}finally{te(!1)}},Dn=async()=>{const y=(l==null?void 0:l.id)||(b==null?void 0:b.id);if(!y){$.error("Save the quote first");return}Oe(!0);try{const g=`SO-${new Date().getFullYear()}-${String(Date.now()).slice(-6)}`;await ge.entities.Quote.update(y,{status:"sales_order",sales_order_number:g,sales_order_date:new Date().toISOString()}),$.success(`Sales order ${g} created`),s.invalidateQueries({queryKey:["existing-quote",y]}),s.invalidateQueries({queryKey:["customer-quotes"]}),e("/sales-orders")}catch{$.error("Failed to create sales order")}finally{Oe(!1)}},Pn=async()=>{var R,S;if(!c.customer_email){$.error("Customer email is required");return}let y=l==null?void 0:l.id;if(!y){const de=await Xt(!0);if(!de)return;y=de.id}Ke(!0);const g=$.loading("Generating PDF & sending email…");try{const de=await ge.functions.invoke("sendQuoteWithContract",{quoteId:y,customerEmail:c.customer_email});$.dismiss(g),(R=de.data)!=null&&R.success?$.success("Quote PDF emailed to customer!"):$.error(((S=de.data)==null?void 0:S.error)||"Failed to send quote email")}catch(de){$.dismiss(g),$.error("Failed to send quote: "+(de.message||"Unknown error")),console.error(de)}finally{Ke(!1)}},Tn=async()=>{var g,R;if(!c.customer_phone){$.error("Customer phone is required");return}let y=l==null?void 0:l.id;if(!y){const S=await Xt(!0);if(!S)return;y=S.id}it(!0);try{const S=`${window.location.origin}/sign-quote?sign=${y}`,de=["granite","marble","quartzite","soapstone"],qe=c.material_type==="quartz",Fe=de.includes(c.material_type),ke=qe?"Clean with mild soap & water. Use trivets for hot items. No sealing needed - quartz is non-porous!":Fe?"Clean with mild soap & water. Use trivets for hot items. Seal annually for optimal protection.":"Clean with mild soap & water. Use trivets for hot items.",mt=`Hi ${c.customer_name}! Your countertop quote is ready.
98
99View & sign your quote here: ${S}
100
101Care Tips: ${ke}`,vt=await ge.functions.invoke("sendSms",{to:c.customer_phone,body:mt});(g=vt.data)!=null&&g.success?$.success(`Quote link sent to ${c.customer_phone}`):$.error(((R=vt.data)==null?void 0:R.error)||"Failed to send SMS")}
101catch(S){$.error("Failed to send SMS"),console.error(S)}finally{it(!1)}},qn=async()=>{if(!c.customer_phone){$.error("Customer phone is required");return}let y=l==null?void 0:l.id;if(!y){const g=await Xt(!0);if(!g)return;y=g.id}try{const g=`${window.location.origin}/sign-quote?sign=${y}`,R=`Hi ${c.customer_name}! Your countertop quote is ready.
102
103📄 View Quote: ${g}
104✍️ Sign Your Quote: ${g}`,S=encodeURIComponent(R);pt(!0);let de=c.customer_phone.replace(/\D/g,"");de.length===10&&(de="1"+de);const qe=`https://wa.me/${de}?text=${S}`;window.open(qe,"_blank"),await ge.entities.Quote.update(y,{whatsapp_sent_date:new Date().toISOString()}),$.success("WhatsApp opened with quote details!")}catch(g){$.error("Failed to prepare WhatsApp message"),console.error(g)}finally{pt(!1)}},Bl=y=>{const g=ft.find(S=>S.id===y);if(!g){f(null);return}f(y);const R=[g.address,g.city,g.state,g.zip_code].filter(Boolean).join(", ");d(S=>({...S,customer_name:g.account_name||S.customer_name,customer_email:g.email||S.customer_email,customer_phone:g.phone||S.customer_phone,job_address:R||S.job_address})),g.account_type==="contractor"&&g.contractor_discount_pct>0&&(E("percentage"),we(g.contractor_discount_pct)),fn(g.account_name)},Vl=async y=>{if(!c.customer_name){$.error("Please enter a customer name first");return}const g=ft.find(R=>{var S;return((S=R.account_name)==null?void 0:S.toLowerCase())===c.customer_name.toLowerCase()});if(g){$.error(`An account already exists for "${c.customer_name}"`),f(g.id);return}N(!0);try{const R=await ge.entities.Account.create({account_name:c.customer_name,contact_name:c.customer_name,email:c.customer_email,phone:c.customer_phone,address:c.job_address,account_type:y||"retail",status:"active"});return await s.invalidateQueries({queryKey:["accounts"]}),f(R.id),$.success("Account created and linked!"),R}catch(R){$.error("Failed to create account"),console.error(R)}finally{N(!1)}},Gl=(y,g)=>d(R=>({...R,[y]:g})),Kl=y=>{var g;mn(y.id),d(R=>({...R,project_type:y.project_type||R.project_type,material_type:y.material_type||R.material_type})),(g=y.default_line_items)!=null&&g.length&&L(y.default_line_items.map(R=>({...R,sqft:"",unit_price_per_sqft:0,material_cost:0,labor_cost:0,total_cost:0,selling_price:0,markup_pct:0})))},Zl=()=>{i(!1),u(null),tt(null),d({customer_name:"",customer_email:"",customer_phone:"",job_address:"",project_type:"kitchen",sqft:"",countertop_shape:"straight",material_type:"",material_name:"",edge_profile:"eased",sink_type:"none",sink_material:"",cooktop_included:!1,backsplash:!1,special_features:[],notes:""}),L([]),ae([]),xe([]),D(null),dt(!1),Ge(null),jn(null),Rl([null,null,null]),We(null),wt([]),St(""),vs([]),mn(null)},Xl=y=>{d(g=>({...g,project_type:y.projectType||g.project_type,material_type:y.materialType||"",sqft:y.approximateSize||g.sqft})),ws(!1)},dr=p.reduce((y,g)=>y+(parseFloat(g.sqft)||0),0),Fn=(ve==null?void 0:ve.selling_price)||(l==null?void 0:l.sellingPrice)||(b==null?void 0:b.selling_price)||0,Ln=wa?Math.round(Fn*.15):0,Jl=Fn+Ln,{discountAmount:Ql,taxAmount:eo,ccFeeAmount:to,finalTotal:Xs}=Ya({basePrice:Jl,discountType:q,discountValue:be,taxRate:Y,applyCreditCardFee:h&&oe,ccFeeRate:z}),ur=bn.reduce((y,g)=>y+(Number(g.amount)||0),0)+W,An=b!=null&&b.converted_to_job_id?"job_created":T||b!=null&&b.customer_signature||(b==null?void 0:b.contract_status)==="signed"?"accepted":lt||b!=null&&b.contract_sent_date||(b==null?void 0:b.contract_status)==="sent"?"sent":"draft",mr=m.useMemo(()=>{if(An!=="sent"||!(b!=null&&b.contract_sent_date))return null;const y=Math.floor((Date.now()-new Date(b.contract_sent_date).getTime())/864e5);return y>=7?{label:"Stale — needs follow-up",tone:"bg-destructive/10 text-destructive border-destructive/20",days:y}:y>=3?{label:"Awaiting signature",tone:"bg-warning/10 text-warning border-warning/20",days:y}:{label:"Sent — awaiting reply",tone:"bg-info/10 text-info border-info/20",days:y}},[An,b==null?void 0:b.contract_sent_date]);return t.jsxs("div",{className:"bg-gradient-to-b from-background to-slate-50 dark:to-slate-900 p-4 sm:p-6 pb-24",children:[t.jsxs("div",{className:"max-w-4xl mx-auto 
104space-y-4",children:[t.jsx(Vo,{icon:Ps,title:b?`Quote #${b.quote_number}`:"New Quote",subtitle:b?c.customer_name:"Enter customer info, pick a material, and save",children:t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[(b==null?void 0:b.converted_to_job_id)&&t.jsxs(X,{variant:"default",size:"sm",onClick:()=>e(`/job/${b.converted_to_job_id}`),className:"shrink-0 gap-1",title:"Open the job created from this quote",children:[t.jsx(Ga,{className:"w-4 h-4"}),"Job Detail"]}),ve&&t.jsx(_f,{isCustomerView:Se,onToggle:F}),!Se&&t.jsx(wf,{onClick:()=>ws(!0),hasItems:p.length>0}),t.jsxs(X,{variant:"outline",size:"sm",onClick:()=>H(Ae==="imperial"?"metric":"imperial"),className:"shrink-0",title:"Toggle measurement unit",children:[t.jsx(ua,{className:"w-4 h-4 mr-1"}),Ae==="imperial"?"sq ft":"sq m"]})]})}),b&&t.jsx(Of,{quote:b}),n&&t.jsx(at,{className:"border-success/20 bg-success/5",children:t.jsx(rt,{className:"pt-3 pb-3",children:t.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[t.jsx("div",{className:"w-8 h-8 rounded-full bg-success/10 flex items-center justify-center shrink-0",children:t.jsx(qs,{className:"w-4 h-4 text-success"})}),t.jsxs("div",{className:"flex-1 min-w-0",children:[t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsxs("p",{className:"font-semibold text-sm truncate",children:["Quote saved — ",l==null?void 0:l.quoteNumber]}),mr&&t.jsxs("span",{className:`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px] font-medium border ${mr.tone}`,children:[t.jsx(js,{className:"w-2.5 h-2.5"}),mr.label]})]}),t.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[c.customer_name," • $",((b==null?void 0:b.final_amount)||Xs).toLocaleString()]})]})]})})}),b&&t.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[t.jsx(qf,{score:b==null?void 0:b.acceptance_score,factors:b==null?void 0:b.acceptance_score_factors,lastUpdated:b==null?void 0:b.acceptance_score_date,isAdmin:r}),t.jsx(Lf,{sentDate:(b==null?void 0:b.contract_sent_date)||(b==null?void 0:b.sent_date),initialDiscountPct:5,dailyDecrementPct:1})]}),Se&&ve?t.jsx(jf,{quoteData:c,lineItems:Yl,aiQuote:ve,allMaterials:ut,depositSchedule:gt,discountType:q,discountValue:be,taxRate:Y,applyCreditCardFee:h&&oe,creditCardFeeRate:z,paymentsReceived:ur,customerSignature:T,layoutImageUrl:Zt,onSign:()=>{l!=null&&l.id?e(`/sign-quote?sign=${l.id}`):$.info("Save the quote first to enable e-signature")},measurementUnit:Ae,pricingConfig:As()}):t.jsxs(t.Fragment,{children:[El&&t.jsxs("div",{className:"flex items-center gap-2 p-3 bg-warning/10 border border-warning/20 rounded-lg text-sm text-warning",children:[t.jsx(Ci,{className:"w-4 h-4 shrink-0"}),t.jsx("span",{children:"Material prices have changed since this quote was last saved — review the line items."})]}),t.jsx(xd,{quoteData:c,updateQuoteData:Gl,checkTaxExemptAccount:fn,isTaxExemptAccount:o,accounts:ft,selectedAccountId:O,onSelectAccount:Bl,onCreateAccount:Vl,isCreatingAccount:I,matchedAccount:Il}),t.jsx(at,{children:t.jsx(rt,{className:"p-3",children:t.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[t.jsx(fd,{quoteData:c,lineItems:p,onApplyTemplate:Kl}),t.jsx(sd,{onLineItemsAdd:y=>L(g=>[...g,...y]),allMaterials:ut}),t.jsxs(X,{variant:"outline",size:"sm",onClick:()=>_e(!Z),className:Z?"bg-primary/10":"",children:[t.jsx(Ps,{className:"w-4 h-4"})," ",Z?"Hide Takeoff":"PDF Takeoff"]}),t.jsxs(X,{variant:"outline",size:"sm",onClick:()=>k(!ee),className:ee?"bg-primary/10":"",children:[t.jsx(mc,{className:"w-4 h-4"})," ",ee?"Hide Canvas":"Live Draw"]})]})})}),t.jsxs(wc,{lineItems:p,services:K,products:pe,onUpdateItems:L,onUpdateServices:ae,onUpdateProducts:xe,allMaterials:ut,pricingConfig:As(),discountType:q,discountValue:be,taxRate:Y,applyCreditCardFee:h&&oe,creditCardFeeRate:z,paymentsReceived:ur,depositSchedule:gt,measurementUnit:Ae,actionBar:t.jsx(zi,{onSave:()=>Xt(),isSaved:n,onSaveAndCreateJob:cr,canCreateJob:!!ve,onPrint:Nn,canPrint:!0,isPrinting:x,onPdf:()=>
104vn(!1),canPdf:!0,isExportingPdf:C,onEmail:Pn,canEmail:!!c.customer_email,isEmailing:fe,onText:Tn,canText:!!c.customer_phone,isTexting:et,onWhatsApp:qn,canWhatsApp:!!c.customer_phone,isWhatsApping:Xe,onEsign:Cn,isSendingContract:Ue,contractSent:lt,onPayment:()=>{De?(navigator.clipboard.writeText(De),$.success("Payment link copied!")):kn()},isCreatingPaymentLink:le,paymentLinkUrl:De,onRevisions:()=>{l!=null&&l.id&&e(`/quote-revisions/${l.id}`)},onRefreshCosts:Mn,isRefreshingCosts:ce,onCreateSalesOrder:Dn,isCreatingSalesOrder:Ce}),children:[Z&&t.jsx(md,{allMaterials:ut,onLineItemsChange:L}),ee&&t.jsx(Xc,{allMaterials:ut,onLineItemsChange:L,onLayoutImageChange:Ns,pricingConfig:As()}),dr>0&&t.jsx(td,{totalSqft:dr,materialName:(Rn=p.find(y=>y.material_name))==null?void 0:Rn.material_name,slabSizeSqft:(In=ut.find(y=>{var g;return y.material_name===((g=p.find(R=>R.material_name))==null?void 0:g.material_name)}))==null?void 0:In.slab_size_sqft,materialType:(En=p.find(y=>y.material_name))==null?void 0:En.material_type,colorField:(Wn=ut.find(y=>{var g;return y.material_name===((g=p.find(R=>R.material_name))==null?void 0:g.material_name)}))==null?void 0:Wn.color,costPerSqft:(zn=ut.find(y=>{var g;return y.material_name===((g=p.find(R=>R.material_name))==null?void 0:g.material_name)}))==null?void 0:zn.cost_per_sqft})]}),dr>0&&wn&&t.jsx(wo,{fallback:Yf,children:t.jsx(kf,{materialImageUrl:wn,materialName:(Un=p.find(y=>y.material_name))==null?void 0:Un.material_name})}),ve&&t.jsxs(t.Fragment,{children:[t.jsx(Pf,{isRush:wa,onToggleRush:hn,rushPremiumPct:15,rushPremiumAmount:Ln,subtotal:(ve==null?void 0:ve.selling_price)||0,discountAmount:Ql,taxAmount:eo,ccFeeAmount:to,total:Xs,taxRate:Y,onTaxRateChange:P,isTaxExemptAccount:o,discountType:q,onDiscountTypeChange:E,discountValue:be,onDiscountValueChange:we,applyCreditCardFee:h,onApplyCreditCardFeeChange:J,creditCardFeeRate:z,ccFeeEnabled:oe,ccFeeAdminOverride:Ne,effectiveFeeRate:ue,isAdmin:r,depositSchedule:gt,onDepositScheduleChange:wt,deposits:bn,paymentsReceived:ur,stagedPayment:W,paymentMethod:je,onPaymentMethodChange:y=>{ye(y),y==="credit_card"&&oe&&J(!0),y==="debit_card"&&J(!1)},onRecordPayment:Wl,onRemoveDeposit:zl,canRecord:!0,quoteId:(l==null?void 0:l.id)||(b==null?void 0:b.id),onEmailPaymentLink:Hl,isEmailingPaymentLink:Ul,paymentLinkUrl:De}),t.jsx(Nc,{totalCost:(ve==null?void 0:ve.total_cost)||0,sellingPrice:(ve==null?void 0:ve.selling_price)||0,marginPct:(ve==null?void 0:ve.margin_pct)||0,targetMargin:As().default_margin_pct||75}),(b==null?void 0:b.expiry_date)&&t.jsx(xi,{expiryDate:b.expiry_date,isEditing:!1}),t.jsxs(vo,{type:"single",collapsible:!0,value:ie,onValueChange:Ee,children:[p.some(y=>y.material_name)&&t.jsxs(ta,{value:"slabs",className:"border rounded-lg px-4",children:[t.jsxs(sa,{className:"text-sm font-semibold",children:[t.jsx(Yr,{className:"w-4 h-4 mr-2 inline"})," Slab Availability"]}),t.jsx(aa,{className:"pt-2",children:t.jsx(fc,{selectedMaterial:((Hn=p.find(y=>y.material_name))==null?void 0:Hn.material_name)||"",requiredSqft:p.reduce((y,g)=>y+(parseFloat(g.sqft)||0),0),onSlabSelect:M})})]}),t.jsxs(ta,{value:"terms",className:"border rounded-lg px-4",children:[t.jsxs(sa,{className:"text-sm font-semibold",children:[t.jsx(Ps,{className:"w-4 h-4 mr-2 inline"})," Terms & Expiry"]}),t.jsxs(aa,{className:"space-y-3 pt-2",children:[t.jsx(xi,{expiryDate:Lt,onSetExpiry:St}),t.jsx(hd,{terms:Pe,onChange:We})]})]}),n&&t.jsxs(ta,{value:"history",className:"border rounded-lg px-4",children:[t.jsxs(sa,{className:"text-sm font-semibold",children:[t.jsx(js,{className:"w-4 h-4 mr-2 inline"})," Version History"]}),t.jsx(aa,{className:"pt-2",children:t.jsx(pd,{versions:(b==null?void 0:b.version_history)||Rt})})]}),n&&(l==null?void 0:l.id)&&t.jsxs(ta,{value:"comments",className:"border rounded-lg px-4",children:[t.jsxs(sa,{className:"text-sm font-semibold",children:[t.jsx(Rr,{className:"w-4 h-4 mr-2 inline"})," Comments"]}),t.jsx(aa,{className:"pt-2",children:t.jsx(yf,{quoteId:l.id})})]}),n&&((l==null?void 0:l.id)||(b==null?void 0:b.id))&&t.jsxs(ta,{value:"share",className:"border rounded-lg px-4",children:[t.jsxs(sa,{className:"text-sm font-semibold",children:[t.jsx(Pi,{className:"w-4 h-4 mr-2 inline"})," Collaborative Link"]}),t.jsx(aa,{className:"pt-2",children:t.jsx(Ff,{quoteId:(l==null?void 0:l.id)||(b==null?void 0:b.id),micrositeToken:b==null?void 0:b.microsite_token,comments:(b==null?void 0:b.comments)||[]})})]})]})]})]}),n&&t.jsx(Nf,{quoteId:(l==null?void 0:l.id)||(b==null?void 0:b.id),quoteNumber:l==null?void 0:l.quoteNumber,onEdit:()=>{F(!1)}
104,onEmail:Pn,canEmail:!!c.customer_email,isEmailing:fe,onText:Tn,canText:!!c.customer_phone,isTexting:et,onWhatsApp:qn,canWhatsApp:!!c.customer_phone,isWhatsApping:Xe,onPrint:Nn,canPrint:!0,isPrinting:x,onPdf:()=>vn(!1),canPdf:!0,isExportingPdf:C,onRevisions:()=>{l!=null&&l.id&&e(`/quote-revisions/${l.id}`)},onPayment:()=>{De?(navigator.clipboard.writeText(De),$.success("Payment link copied!")):kn()},isCreatingPaymentLink:le,paymentLinkUrl:De,onEsign:Cn,isSendingContract:Ue,contractSent:lt,onRefreshCosts:Mn,isRefreshingCosts:ce,onCreateSalesOrder:Dn,isCreatingSalesOrder:Ce,onNewQuote:()=>{Zl(),F(!1)},onSave:()=>Xt(),onSaveAndCreateJob:cr,canCreateJob:!!ve,isSaving:!1}),!n&&t.jsx(Af,{total:Xs,marginPct:(ve==null?void 0:ve.margin_pct)||0,targetMargin:As().default_margin_pct||75,onSave:()=>Xt(),canSave:!!c.customer_name&&(!!ve||!!b),isSaving:!1,measurementUnit:Ae,onSaveAndCreateJob:cr,canCreateJob:!!ve})]}),t.jsx(vc,{open:ms,onOpenChange:ws,onComplete:Xl,existingQuoteData:c})]})}export{tx as default};

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.