1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[66311],{59682:function(e,t,r){r.d(t,{e:function(){return E}});var n=r(27573),o=r(7653),s=r(20054),a=r(3172),l=r(10997),i=r(79901),d=r(75721),c=r(99134),u=r(88623),m=r(74720),p=r(50466),x=r(76529),b=r(98609),h=r(5364);let f="h-8 rounded-lg border border-border bg-background px-2 text-[13px] text-foreground focus:outline-none focus:ring-2 focus:ring-primary/40 disabled:opacity-50 w-full",g="h-8 min-h-0 rounded-lg border-border bg-background text-[13px] text-foreground";function v(e){return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD"}).format(e/100)}function y(e){switch(e.kind){case"number":return"number"==typeof e.example?String(e.example):"";case"select":var t,r;return null!==(r=null===(t=e.options)||void 0===t?void 0:t[0])&&void 0!==r?r:"";case"boolean":return!1;case"list":return[]}}function j(e,t){let r={};for(let n of e){let e=t[n.key];switch(n.kind){case"number":{let t=parseFloat(String(null!=e?e:""));isNaN(t)||(r[n.key]=t);break}case"select":void 0!==e&&""!==e&&(r[n.key]=e);break;case"boolean":r[n.key]=!0===e||"true"===e;break;case"list":{let t=(null!=e?e:[]).filter(e=>!e._id||Object.keys(e).some(t=>"_id"!==t&&""!==e[t])).map(e=>{var t,r;let o={};for(let s of null!==(t=n.itemFields)&&void 0!==t?t:[])if("number"===s.kind){let t=parseFloat(String(null!==(r=e[s.key])&&void 0!==r?r:""));isNaN(t)||(o[s.key]=t)}else o[s.key]=e[s.key];return o}
1);t.length>0&&(r[n.key]=t)}}}return r}function N(e){let{field:t,value:r,error:o,onChange:a,fieldId:l}=e,i=void 0!==t.example?String(t.example):t.unit?"e.g. 10":"";return(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsxs)(x._,{htmlFor:l,className:"text-[12px] font-semibold text-muted-foreground",children:[t.label,t.required&&(0,n.jsx)("span",{className:"text-destructive ml-0.5",children:"*"}),t.unit&&(0,n.jsxs)("span",{className:"ml-1 text-muted-foreground font-normal",children:["(",t.unit,")"]})]}),(0,n.jsxs)("div",{className:"relative",children:[(0,n.jsx)("input",{id:l,type:"number",min:t.min,max:t.max,step:"ft"===t.unit?.1:1,value:r,onChange:e=>a(e.target.value),placeholder:i,className:f}),t.unit&&(0,n.jsx)("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-[11px] text-muted-foreground pointer-events-none",children:t.unit})]}),o&&(0,n.jsxs)("p",{className:"text-[11px] text-destructive flex items-center gap-1",children:[(0,n.jsx)(s.Z,{className:"h-3 w-3 shrink-0"}),o]})]})}function k(e){var t;let{field:r,value:o,error:a,onChange:l,fieldId:i}=e;return(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsxs)(x._,{htmlFor:i,className:"text-[12px] font-semibold text-muted-foreground",children:[r.label,r.required&&(0,n.jsx)("span",{className:"text-destructive ml-0.5",children:"*"})]}),(0,n.jsxs)(b.Ph,{value:o,onValueChange:l,children:[(0,n.jsx)(b.i4,{id:i,className:g,children:(0,n.jsx)(b.ki,{})}),(0,n.jsx)(b.Bw,{children:(null!==(t=r.options)&&void 0!==t?t:[]).map(e=>(0,n.jsx)(b.Ql,{value:e,children:e.charAt(0).toUpperCase()+e.slice(1)},e))})]}),a&&(0,n.jsxs)("p",{className:"text-[11px] text-destructive flex items-center gap-1",children:[(0,n.jsx)(s.Z,{className:"h-3 w-3 shrink-0"}),a]})]})}function w(e){let{field:t,value:r,onChange:o}=e;return(0,n.jsxs)("label",{className:"flex items-center gap-2.5 text-[13px] text-foreground cursor-pointer select-none",children:[(0,n.jsx)("input",{type:"checkbox",checked:r,onChange:e=>o(e.target.checked),className:"h-4 w-4 rounded border-border text-primary focus:ring-primary/40"}),t.label]})}function C(e){var t;let{field:r,rows:s,errors:i,onChange:d,baseId:c}=e,u=null!==(t=r.itemFields)&&void 0!==t?t:[],m=(0,o.useCallback)(()=>{d([...s,function(e){let t={_id:Math.random().toString(36).slice(2)};for(let o of e)switch(o.kind){case"number":default:t[o.key]="";break;case"select":var r,n;t[o.key]=null!==(n=null===(r=o.options)||void 0===r?void 0:r[0])&&void 0!==n?n:"";break;case"boolean":t[o.key]="false"}return t}(u)])},[s,u,d]),h=(0,o.useCallback)(e=>{d(s.filter((t,r)=>r!==e))},[s,d]),v=(0,o.useCallback)((e,t,r)=>{d(s.map((n,o)=>o===e?{...n,[t]:r}:n))},[s,d]);return(0,n.jsxs)("div",{className:"space-y-2",children:[(0,n.jsxs)("div",{className:"flex items-center justify-between",children:[(0,n.jsxs)(x._,{className:"text-[12px] font-semibold text-muted-foreground",children:[r.label,!r.required&&(0,n.jsx)("span",{className:"ml-1 text-muted-foreground font-normal text-[11px]",children:"(optional)"})]}),(0,n.jsxs)(p.z,{type:"button",variant:"outline",size:"sm",className:"h-6 text-xs px-2 border-primary/60 text-primary hover:bg-amber-50 dark:hover:bg-amber-950/40",onClick:m,children:[(0,n.jsx)(a.Z,{className:"h-3 w-3 mr-1"}),"Add"]})]}),0===s.length&&(0,n.jsx)("p",{className:"text-[12px] text-muted-foreground",children:"None added â click Add to include openings."}),s.map((e,t)=>{var o;return(0,n.jsxs)("div",{className:"flex items-center gap-2 rounded-lg border border-border bg-muted px-2 py-2",children:[u.map(r=>{var o,s,a,l,i,d;let u="".concat(c,"-row").concat(t,"-").concat(r.key);return"select"===r.kind?(0,n.jsx)("div",{className:"w-24",children:(0,n.jsxs)(b.Ph,{value:String(null!==(a=null!==(s=e[r.key])&&void 0!==s?s:null===(o=r.options)||void 0===o?void 0:o[0])&&void 0!==a?a:""),onValueChange:e=>v(t,r.key,e),children:[(0,n.jsx)(b.i4,{className:"".concat(g," text-[12px]"),children:(0,n.jsx)(b.ki,{})}),(0,n.jsx)(b.Bw,{children:(null!==(l=r.options)&&void 0!==l?l:[]).map(e=>(0,n.jsx)(b.Ql,{value:e,children:e.charAt(0).toUpperCase()+e.slice(1)},e))})]})},r.key):"number"===r.kind?(0,n.jsxs)("div",{className:"relative flex-1 min-w-[60px] max-w-[90px]",children:[(0,n.jsx)("input",{id:u,type:"number",min:r.min,max:r.max,step:.1,value:String(null!==(i=e[r.key])&&void 0!==i?i:""),onChange:e=>v(t,r.key,e.target.value),placeholder:null!==(d=r.unit)&&void 0!==d?d:r.key,className:"".concat(f," text-[12px]")}),r.unit&&(0,n.jsx)("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-[10px] text-muted-foreground pointer-events-none",children:r.unit})]},r.key):null}),(0,n.jsx)("button",{type:"button",onClick:()=>h(t),"aria-label":"Remove row",className:"h-6 w-6 flex items-center justify-center rounded text-muted-foreground hover:text-destructive hover:bg-red-50 dark:hover:bg-red-950/40 shrink-0",children:(0,n.jsx)(l.Z,{className:"h-3.5 w-3.5"})}),i["".concat(r.key,".").concat(t)]&&(0,n.jsx)("p",{className:"text-[11px] text-destructive",children:i["".concat(r.key,".").concat(t)]})]},null!==(o=e._id)&&void 0!==o?o:t)})]})}function S(e){let{variantAxes:t,selectionAttributes:r,variantSelections:o,selections:s,onVariantChange:a,onSelectionChange:l,baseId:i}=e;return t.length>0||r.length>0?(0,n.jsxs)("div",{className:"space-y-3",children:[(0,n.jsx)("p",{className:"text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",children:"Options"}),t.map(e=>{var t;let r="".concat(i,"-variant-").concat(e.key),s=null!==(t=o[e.key])&&void 0!==t?t:e.default;return(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsxs)(x._,{htmlFor:r,className:"text-[12px] font-semibold text-muted-foreground",children:[e.label,(0,n.jsx)("span",{className:"ml-1 text-muted-foreground font-normal text-[11px]",children:"(affects price)"})]}),(0,n.jsxs)(b.Ph,{value:s,onValueChange:t=>a(e.key,t),children:[(0,n.jsx)(b.i4,{id:r,className:g,children:(0,n.jsx)(b.ki,{})}),(0,n.jsx)(b.Bw,{children:e.options.map(e=>(0,n.jsx)(b.Ql,{value:e.value,children:e.label},e.value))})]})]},e.key)}),r.map(e=>{var t;let r="".concat(i,"-sel-").concat(e.key),o=null!==(t=s[e.key])&&void 0!==t?t:"";return"select"===e.kind&&e.options&&e.options.length>0?(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsxs)(x._,{htmlFor:r,className:"text-[12px] font-semibold text-muted-foreground",children:[e.label,!e.required&&(0,n.jsx)("span",{className:"ml-1 text-muted-foreground font-normal text-[11px]",children:"(optional)"})]}),(0,n.jsxs)(b.Ph,{value:o||"__none__",onValueChange:t=>l(e.key,"__none__"===t?"":t),children:[(0,n.jsx)(b.i4,{id:r,className:g,children:(0,n.jsx)(b.ki,{placeholder:"Selectâ¦"})}),(0,n.jsxs)(b.Bw,{children:[!e.required&&(0,n.jsx)(b.Ql,{value:"__none__",children:(0,n.jsx)("span",{className:"text-muted-foreground",children:"None"})}),e.options.map(e=>(0,n.jsx)(b.Ql,{value:e,children:e},e))]})]})]},e.key):(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsxs)(x._,{htmlFor:r,className:"text-[12px] font-semibold text-muted-foreground",children:[e.label,!e.required&&(0,n.jsx)("span",{className:"ml-1 text-muted-foreground font-normal text-[11px]",children:"(optional)"})]}),(0,n.jsx)("input",{id:r,type:"text",value:o,onChange:t=>l(e.key,t.target.value),placeholder:"e.g. ".concat(e.label),className:f})]},e.key)})]}):null}function I(e){let{fields:t,values:r,errors:o,onChange:s,baseId:a}=e,l=t.filter(e=>"list"!==e.kind),i=t.filter(e=>"list"===e.kind);return(0,n.jsxs)("div",{className:"space-y-4",children:[l.length>0&&(0,n.jsx)("div",{className:l.length>=3?"grid grid-cols-3 gap-3":2===l.length?"grid grid-cols-2 gap-3":"grid grid-cols-1 gap-3",children:l.map(e=>{var t,l;let i="".concat(a,"-").concat(e.key);return"number"===e.kind?(0,n.jsx)(N,{field:e,value:String(null!==(t=r[e.key])&&void 0!==t?t:""),error:o[e.key],onChange:t=>s(e.key,t),fieldId:i},e.key):"select"===e.kind?(0,n.jsx)(k,{field:e,value:String(null!==(l=r[e.key])&&void 0!==l?l:""),error:o[e.key],onChange:t=>s(e.key,t),fieldId:i},e.key):"boolean"===e.kind?(0,n.jsx)(w,{field:e,value:!!r[e.key],onChange:t=>s(e.key,t)},e.key):null})}),i.map(e=>{var t;return(0,n.jsx)(C,{field:e,rows:null!==(t=r[e.key])&&void 0!==t?t:[],errors:o,onChange:t=>s(e.key,t),baseId:"".concat(a,"-").concat(e.key)},e.key)})]})}function A(e){let{result:t}=e,r=t.line_items.filter(e=>"MATERIAL"!==e.costType),o=t.line_items.filter(e=>"MATERIAL"===e.costType);return(0,n.jsxs)("div",{className:"space-y-2",children:[(0,n.jsx)("div",{className:"overflow-y-auto max-h-56 rounded-xl border border-border",children:(0,n.jsxs)("table",{className:"w-full text-[12px]",children:[(0,n.jsx)("thead",{children:(0,n.jsxs)("tr",{className:"bg-muted text-muted-foreground uppercase tracking-wide text-[10px]",children:[(0,n.jsx)("th",{className:"px-3 py-1.5 text-left font-semibold",children:"Description"}),(0,n.jsx)("th",{className:"px-2 py-1.5 text-right font-semibold",children:"Qty"}),(0,n.jsx)("th",{className:"px-2 py-1.5 text-right font-semibold",children:"Unit"}),(0,n.jsx)("th",{className:"px-2 py-1.5 text-right font-semibold",children:"Price"})]})}),(0,n.jsxs)("tbody",{className:"divide-y divide-border",children:[r.length>0&&(0,n.jsx)("tr",{children:(0,n.jsx)("td",{colSpan:4,className:"px-3 py-1 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground bg-muted",children:"Labor"})}),r.map((e,t)=>(0,n.jsxs)("tr",{className:"odd:bg-muted",children:[(0,n.jsx)("td",{className:"px-3 py-1.5 text-foreground truncate max-w-[180px]",children:e.description}),(0,n.jsx)("td",{className:"px-2 py-1.5 text-right tabular-nums text-muted-foreground",children:e.quantity.toFixed(2)}),(0,n.jsx)("td",{className:"px-2 py-1.5 text-right text-muted-foreground",children:e.unit}),(0,n.jsx)("td",{className:"px-2 py-1.5 text-right tabular-nums font-medium text-foreground",children:v(e.priceCents)})]},t)),o.length>0&&(0,n.jsx)("tr",{children:(0,n.jsx)("td",{colSpan:4,className:"px-3 py-1 text-[10px] font-semibold uppercase tracking-wide text-muted-foreground bg-muted",children:"Materials"})}),o.map((e,t)=>(0,n.jsxs)("tr",{className:"odd:bg-muted",children:[(0,n.jsx)("td",{className:"px-3 py-1.5 text-foreground truncate max-w-[180px]",children:e.description}),(0,n.jsx)("td",{className:"px-2 py-1.5 text-right tabular-nums text-muted-foreground",children:e.quantity.toFixed(2)}),(0,n.jsx)("td",{className:"px-2 py-1.5 text-right text-muted-foreground",children:e.unit}),(0,n.jsx)("td",{className:"px-2 py-1.5 text-right tabular-nums font-medium text-foreground",children:v(e.priceCents)})]},"m-".concat(t)))]})]})}),(0,n.jsxs)("div",{className:"flex items-center justify-between px-3 py-2 rounded-xl bg-muted border border-border",children:[(0,n.jsxs)("div",{className:"flex items-center gap-4 text-[12px] text-muted-foreground",children:[t.totals.laborCents>0&&(0,n.jsxs)("span",{children:["Labor: ",v(t.totals.laborCents)]}),t.totals.materialCents>0&&(0,n.jsxs)("span",{children:["Materials: ",v(t.totals.materialCents)]})]}),(0,n.jsx)("div",{className:"text-[14px] font-bold text-foreground",children:v(t.totals.totalCents)})]})]})}function E(e){var t,r,a,l,p;let{open:b,onClose:g,assemblyId:v,assemblyName:N,estimateId:k,onAdded:w,initialInputs:C,replaceGroupId:E,initialVariantSelections:T,initialSelections:P,parentGroupId:D,onExpandResult:F}=e,O=(0,o.useId)(),M=!!E,{data:Z,isLoading:G,error:L}=(0,h.ZF)(b?v:null),[R,B]=(0,o.useState)({}),[q,W]=(0,o.useState)(""),[_,U]=(0,o.useState)(1),[z,K]=(0,o.useState)({}),[V,H]=(0,o.useState)({}),[J,Q]=(0,o.useState)({}),[$,Y]=(0,o.useState)(null),[X,ee]=(0,o.useState)(null),[et,er]=(0,o.useState)(null),[en,eo]=(0,o.useState)(!1),es=(0,h.bZ)(),ea=Z?"".concat(Z.assemblyId,":").concat(null!=E?E:""):null,[el,ei]=(0,o.useState)(null);if(Z&&ea!==el){let e=function(e){let t={};for(let r of e)t[r.key]=y(r);return t}(Z.fields);if(M&&C){let t={...e};for(let e of Z.fields){let r=C[e.key];void 0!==r&&("number"===e.kind?t[e.key]=String(r):"list"===e.kind&&Array.isArray(r)?t[e.key]=r.map(e=>({_id:Math.random().toString(36).slice(2),...e})):t[e.key]=r)}e=t}B(e),W("".concat(Z.instanceNoun.charAt(0).toUpperCase()).concat(Z.instanceNoun.slice(1)," ").concat(_)),ei(ea),K({}),Y(null),ee(null),er(null),eo(!1);let r={};for(let e of null!==(t=Z.variantAxes)&&void 0!==t?t:[])r[e.key]=e.default;M&&T?H({...r,...T}):H(r),M&&P?Q({...P}):Q({})}let ed=(0,o.useCallback)((e,t)=>{B(r=>({...r,[e]:t})),K(t=>{if(!t[e])return t;let r={...t};return delete r[e],r}),Y(null),ee(null),er(null),eo(!1)},[]),ec=(0,o.useCallback)((e,t)=>{H(r=>({...r,[e]:t})),Y(null),ee(null),er(null),eo(!1)},[]),eu=(0,o.useCallback)((e,t)=>{Q(r=>
1{if(!t){let t={...r};return delete t[e],t}return{...r,[e]:t}}),Y(null),er(null),eo(!1)},[]),em=(0,o.useCallback)(async()=>{if(!Z)return;K({}),ee(null),er(null),eo(!1);let e=j(Z.fields,R),t=Object.keys(V).length>0?V:void 0,r=Object.keys(J).length>0?J:void 0;try{let n=await es.mutateAsync({assemblyId:v,inputs:e,audience:"internal",variant_selections:t,selections:r});Y(n)}catch(e){if(e instanceof h.Pe){let t={};for(let r of e.detail.missing){let n=e.detail.hints[r];if(n){let e=n.unit?" (".concat(n.unit,")"):"",o=void 0!==n.example?" e.g. ".concat(n.example):"";t[r]="".concat(n.label).concat(e," is required.").concat(o)}else t[r]="This field is required."}K(t),ee("Some required fields are missing â see the highlighted fields above.")}else ee(e instanceof Error?e.message:"Failed to calculate. Please try again.")}},[Z,R,v,es,V,J]),ep=(0,o.useCallback)(async()=>{if(!Z||!k||!$)return;er(null);let e=j(Z.fields,R),t=q.trim()||N,r=Object.keys(V).length>0?V:void 0,n=Object.keys(J).length>0?J:void 0;try{let o=await es.mutateAsync({assemblyId:v,inputs:e,audience:"internal",persist:{estimateId:k,groupName:t,...M&&E?{replaceGroupId:E}:{},...!M&&D?{parentGroupId:D}:{}},variant_selections:r,selections:n});eo(!0),!M&&F&&F(o,N),w()}catch(e){e instanceof h.Pe?er("Validation failed â please recalculate before adding."):er(e instanceof Error?e.message:"Failed to add to estimate.")}},[Z,k,$,R,q,N,v,es,w,M,E,D,V,J]),ex=(0,o.useCallback)(()=>{if(!Z)return;let e=_+1;U(e);let t={};for(let e of Z.fields)if("list"===e.kind)t[e.key]=[];else{var r;t[e.key]=null!==(r=R[e.key])&&void 0!==r?r:y(e)}B(t),W("".concat(Z.instanceNoun.charAt(0).toUpperCase()).concat(Z.instanceNoun.slice(1)," ").concat(e)),Y(null),ee(null),er(null),K({}),eo(!1)},[Z,_,R]),eb=(0,o.useCallback)(()=>{U(1),B({}),K({}),Y(null),ee(null),er(null),eo(!1),ei(null),H({}),Q({}),g()},[g]),eh=!!k,ef=!!$&&!en,eg=es.isPending,ev=(0,n.jsxs)("div",{className:"space-y-2",children:[et&&(0,n.jsxs)("div",{className:"flex items-start gap-2 rounded-lg border border-red-200 dark:border-red-800 bg-red-50 dark:bg-red-950/40 px-3 py-2 text-[12px] text-red-700 dark:text-red-300",children:[(0,n.jsx)(s.Z,{className:"h-3.5 w-3.5 shrink-0 mt-0.5"}),et]}),en&&(null==Z?void 0:Z.supportsMultiInstance)&&(0,n.jsxs)("div",{className:"flex items-center gap-2 rounded-lg border border-emerald-200 dark:border-emerald-800 bg-emerald-50 dark:bg-emerald-950/40 px-3 py-2 text-[12px] text-emerald-700 dark:text-emerald-300",children:[(0,n.jsx)(i.Z,{className:"h-3.5 w-3.5 shrink-0 text-emerald-600 dark:text-emerald-400"}),"Added! Click below to add another"," ",Z.instanceNoun,"."]}),(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsxs)("button",{type:"button",onClick:()=>void em(),disabled:eg||G,className:"flex items-center gap-1.5 rounded-lg bg-primary px-3 py-2 text-[13px] font-semibold text-primary-foreground shadow-sm transition-all hover:bg-primary/90 disabled:opacity-50",children:[eg&&!$?(0,n.jsx)(d.Z,{className:"h-3.5 w-3.5 animate-spin"}):(0,n.jsx)(c.Z,{className:"h-3.5 w-3.5"}),$?"Recalculate":"Calculate"]}),eh?en&&(null==Z?void 0:Z.supportsMultiInstance)&&!M?(0,n.jsxs)("button",{type:"button",onClick:ex,className:"flex flex-1 items-center justify-center gap-1.5 rounded-lg border-2 border-primary px-3 py-2 text-[13px] font-semibold text-primary transition-all hover:bg-amber-50 dark:hover:bg-amber-950/40",children:[(0,n.jsx)(u.Z,{className:"h-3.5 w-3.5"}),"Add another ",Z.instanceNoun]}):(0,n.jsxs)("button",{type:"button",onClick:()=>void ep(),disabled:!ef||eg,title:$?void 0:"Calculate first to preview",className:"flex flex-1 items-center justify-center gap-1.5 rounded-lg bg-primary px-3 py-2 text-[13px] font-semibold text-primary-foreground shadow-sm transition-all hover:bg-primary/90 disabled:opacity-40",children:[eg&&$?(0,n.jsx)(d.Z,{className:"h-3.5 w-3.5 animate-spin"}):(0,n.jsx)(i.Z,{className:"h-3.5 w-3.5"}),M?"Update group":"Add to estimate"]}):(0,n.jsxs)("div",{title:"Save the estimate first",className:"flex flex-1 items-center justify-center gap-1.5 rounded-lg bg-primary/30 px-3 py-2 text-[13px] font-semibold text-foreground
1/50 cursor-not-allowed",children:[(0,n.jsx)(i.Z,{className:"h-3.5 w-3.5"}),M?"Update group":"Add to estimate"]})]})]});return(0,n.jsx)(m.R,{open:b,onOpenChange:e=>{e||eb()},title:M?"Edit parameters â ".concat(N):N,footer:ev,children:(0,n.jsxs)("div",{className:"space-y-5 px-1 py-2",children:[G&&(0,n.jsxs)("div",{className:"space-y-3 animate-pulse",children:[(0,n.jsx)("div",{className:"h-4 w-2/3 rounded bg-muted"}),(0,n.jsx)("div",{className:"grid grid-cols-3 gap-3",children:[0,1,2].map(e=>(0,n.jsx)("div",{className:"h-14 rounded-lg bg-muted"},e))})]}),L&&!G&&(0,n.jsxs)("div",{className:"flex items-start gap-2 rounded-lg border border-red-200 dark:border-red-800 bg-red-50 dark:bg-red-950/40 px-4 py-3 text-[13px] text-red-700 dark:text-red-300",children:[(0,n.jsx)(s.Z,{className:"h-4 w-4 shrink-0 mt-0.5"}),(0,n.jsxs)("div",{children:[(0,n.jsx)("p",{className:"font-semibold",children:"Failed to load form"}),(0,n.jsx)("p",{className:"text-[12px] mt-0.5",children:L instanceof Error?L.message:"Please close and try again."})]})]}),Z&&(0,n.jsxs)(n.Fragment,{children:[Z.supportsMultiInstance&&(0,n.jsxs)("div",{className:"space-y-1",children:[(0,n.jsxs)(x._,{htmlFor:"".concat(O,"-instance-label"),className:"text-[12px] font-semibold text-muted-foreground",children:["Label for this"," ",Z.instanceNoun]}),(0,n.jsx)("input",{id:"".concat(O,"-instance-label"),value:q,onChange:e=>W(e.target.value),placeholder:"e.g. ".concat(Z.instanceNoun.charAt(0).toUpperCase()).concat(Z.instanceNoun.slice(1)," 1"),className:f})]}),!eh&&(0,n.jsx)("div",{className:"rounded-lg border border-border bg-amber-50 dark:bg-amber-950/40 px-3 py-2 text-[12px] text-amber-700 dark:text-amber-300",children:"Save the estimate first to add assembly lines."}),(0,n.jsx)(I,{fields:Z.fields,values:R,errors:z,onChange:ed,baseId:O}),((null!==(r=Z.variantAxes)&&void 0!==r?r:[]).length>0||(null!==(a=Z.selectionAttributes)&&void 0!==a?a:[]).length>0)&&(0,n.jsx)(S,{variantAxes:null!==(l=Z.variantAxes)&&void 0!==l?l:[],selectionAttributes:null!==(p=Z.selectionAttributes)&&void 0!==p?p:[],variantSelections:V,selections:J,onVariantChange:ec,onSelectionChange:eu,baseId:O}),X&&(0,n.jsxs)("div",{className:"flex items-start gap-2 rounded-lg border border-red-200 dark:border-red-800 bg-red-50 dark:bg-red-950/40 px-3 py-2.5 text-[12px] text-red-700 dark:text-red-300",children:[(0,n.jsx)(s.Z,{className:"h-3.5 w-3.5 shrink-0 mt-0.5"}),X]}),$&&(0,n.jsxs)("div",{className:"space-y-2",children:[(0,n.jsx)("p",{className:"text-[12px] font-semibold uppercase tracking-wide text-muted-foreground",children:"Preview â calculated lines"}),(0,n.jsx)(A,{result:$})]})]})]})})}},41169:function(e,t,r){r.d(t,{O:function(){return er}});var n=r(27573),o=r(7653),s=r(17787),a=r(8604),l=r(11465),i=r(6315),d=r(51856),c=r(29077),u=r(73794),m=r(72829),p=r(10997),x=r(2966),b=r(3172),h=r(70844),f=r(74720),g=r(45782);function v(e){return e>=25?"#3D6442":e>=15?"#F59E0B":"#A84B3D"}let y=[{value:"labor",label:"Labor",short:"L",bg:"hsl(var(--primary))",text:"hsl(var(--primary-foreground))",ring:"border-[hsl(var(--primary))]"},{value:"material",label:"Material",short:"M",bg:"#475569",text:"#fff",ring:"border-[#334155] dark:border-[#94A3B8]"},{value:"equipment",label:"Equipment",short:"E",bg:"#64748B",text:"#fff",ring:"border-[#475569] dark:border-[#CBD5E1]"},{value:"subcontractor",label:"Subcontract",short:"S",bg:"#94A3B8",text:"#1E293B",ring:"border-[#64748B] dark:border-[#E2E8F0]"},{value:"other",label:"Other",short:"O",bg:"#CBD5E1",text:"#1E293B",ring:"border-[#94A3B8] dark:border-[#F1F5F9]"}],j=["each","hr","sqft","lf","lbs","unit","job","day"];function N(e){var t,r,s,i;let{item:d,groupId:c,itemNumber:u,isLocked:m,onEdit:p,onOpenActions:x}=e,b=(0,o.useRef)(null),h=(0,o.useRef)(!1),f=(0,o.useRef)(null),j={...d,unitCost:d.cost,costType:null!==(r=d.lineItemType)&&void 0!==r?r:"labor"},N=(0,g.et)(j),k=(0,g.AM)(j),w=(s=d.lineItemType,null!==(i=y.find(e=>e.value===(null!=s?s:"labor")))&&void 0!==i?i:y[0]),C=(0,o.useCallback)(()=>{m||x(c,d.id)},[m,x,c,d.id]),S=(0,o.useCallback)(()=>{b.current&&(clearTimeout(b.current),b.current=null)},[]),I=(0,o.useCallback)((e,t)=>{m||(h.current=!1,f.current={x:e,y:t},b.current=setTimeout(()=>{h.current=!0;try{var e,t;null===(e=(t=navigator).vibrate)||void 0===e||e.call(t,12)}catch(e){}C()},450))},[m,C]);return(0,n.jsxs)("div",{"data-brion-line-item-row":"","data-brion-line-item-row-id":d.id,className:"relative rounded-lg border border-border bg-card overflow-visible",children:[(0,n.jsxs)("button",{type:"button",disabled:m,onClick:()=>
1{if(h.current){h.current=!1;return}m||p(c,d.id)},onTouchStart:e=>{let t=e.touches[0];t&&I(t.clientX,t.clientY)},onTouchMove:e=>{let t=e.touches[0],r=f.current;t&&r&&(Math.abs(t.clientX-r.x)>10||Math.abs(t.clientY-r.y)>10)&&S()},onTouchEnd:S,onTouchCancel:S,onContextMenu:e=>{e.preventDefault(),C()},className:"w-full select-none px-3 py-3 text-left focus:outline-none [touch-action:pan-y]","aria-label":"Edit ".concat(d.description||"line item"),children:[(0,n.jsxs)("div",{className:"flex items-start gap-2",children:[(0,n.jsxs)("span",{className:"mt-0.5 inline-flex flex-shrink-0 items-center gap-1 text-[10px] font-semibold leading-none text-muted-foreground",title:w.label,children:[(0,n.jsx)("span",{className:"inline-flex h-2 w-2 flex-shrink-0 rounded-full border-2 bg-transparent ".concat(w.ring),"aria-hidden":"true"}),w.short]}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("span",{className:"block text-[14px] font-semibold leading-snug text-foreground",children:d.description||(0,n.jsx)("span",{className:"text-muted-foreground",children:"Untitled item"})}),d.isOptional&&(0,n.jsx)("span",{className:"mt-0.5 inline-block rounded bg-amber-100 dark:bg-amber-950/40 px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-wide text-amber-900 dark:text-amber-300",children:"Optional"})]}),(0,n.jsxs)("span",{className:"ml-1 flex-shrink-0 text-[11px] font-mono tabular-nums text-muted-foreground select-none",children:["#",u]})]}),(0,n.jsxs)("div",{className:"mt-2 flex items-baseline justify-between gap-2",children:[(0,n.jsxs)("span",{className:"text-[12px] text-muted-foreground",children:[(0,n.jsx)("span",{className:"font-mono tabular-nums",children:d.qty}),(0,n.jsx)("span",{className:"mx-1 text-muted-foreground",children:d.unit}),(0,n.jsx)("span",{className:"text-muted-foreground",children:"\xd7"}),(0,n.jsx)("span",{className:"ml-1 font-mono tabular-nums",children:(0,g.xG)(d.unitPrice)})]}),(0,n.jsx)("span",{className:"font-mono text-[14px] font-bold tabular-nums text-foreground",children:(0,g.xG)(N)})]}),d.cost>0&&(0,n.jsxs)("div",{className:"mt-1.5 flex items-center gap-2 text-[11px] text-muted-foreground",children:[(0,n.jsxs)("span",{children:["cost ",(0,g.xG)(d.cost)]}),d.cost>0&&d.unitPrice>0&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{children:"\xb7"}),(0,n.jsxs)("span",{children:["markup ",Math.round((d.unitPrice-d.cost)/d.cost*100),"%"]}),(0,n.jsx)("span",{children:"\xb7"}),(0,n.jsxs)("span",{className:"inline-flex items-center gap-0.5 rounded-full px-1.5 py-0.5 text-[10px] font-bold",style:{background:"".concat(v(k),"18"),color:v(k)},children:[(0,n.jsx)("span",{className:"h-1.5 w-1.5 rounded-full inline-block",style:{background:v(k)}}),k.toFixed(1),"%"]})]})]}),(null===(t=d.notes)||void 0===t?void 0:t.trim())&&(0,n.jsxs)("div",{className:"mt-1.5 flex items-center gap-1 text-[11px] text-muted-foreground",children:[(0,n.jsx)(a.Z,{className:"h-2.5 w-2.5 flex-shrink-0",strokeWidth:2}),(0,n.jsx)("span",{className:"truncate",children:d.notes})]})]}),!m&&(0,n.jsx)("div",{className:"absolute right-2 top-2 z-10",children:(0,n.jsx)("button",{type:"button",onClick:e=>{e.stopPropagation(),C()},className:"flex h-8 w-8 items-center justify-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground","aria-label":"Item actions",children:(0,n.jsx)(l.Z,{className:"h-4 w-4",strokeWidth:2})})})]})}function k(e){let{icon:t,label:r,onClick:o,destructive:s}=e;return(0,n.jsxs)("button",{type:"button",onClick:o,className:"flex h-12 w-full items-center gap-3 rounded-lg px-3 text-left text-[14px] font-medium ".concat(s?"text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-950/40":"text-foreground hover:bg-muted"),children:[(0,n.jsx)(t,{className:"h-[18px] w-[18px] ".concat(s?"":"text-muted-foreground"),strokeWidth:2}),r]})}function w(e){var t,r,o;let{item:a,groupId:l,onEdit:x,onDuplicate:b,onUpdateItem:h,onDelete:g,onOpenCatalogPicker:v,onClose:y}=e,j=null!==(r=a.isOptional)&&void 0!==r&&r,N=null===(o=a.taxable)||void 0===o||o,w=e=>{e(),y()};return(0,n.jsx)(f.R,{open:!0,onOpenChange:e=>{e||y()},title:(null===(t=a.description)||void 0===t?void 0:t.trim())||"Line item",snapPoints:[60],children:(0,n.jsxs)("div",{className:"space-y-0.5 pb-2",children:[(0,n.jsx)(k,{icon:i.Z,label:"Edit details",onClick:()=>w(()=>x(l,a.id))}),(0,n.jsx)(k,{icon:d.Z,label:"Duplicate",onClick:()=>w(()=>b(l,a.id))}),(0,n.jsx)(k,{icon:c.Z,label:j?"Mark as required":"Mark as optional",onClick:()=>w(()=>h(l,a.id,{isOptional:!j}))}),(0,n.jsx)(k,{icon:u.Z,label:N?"Mark as non-taxable":"Mark as taxable",onClick:()=>w(()=>h(l,a.id,{taxable:!N}))}),v&&(0,n.jsx)(k,{icon:m.Z,label:"Pick from catalog",onClick:()=>w(()=>v(l,a.id))}),(0,n.jsx)("div",{className:"my-1 border-t border-border"}),(0,n.jsx)(k,{icon:p.Z,label:"Delete",destructive:!0,onClick:()=>{y(),(0,s.A)("Delete this line item?",{duration:8e3,action:{label:"Delete",onClick:()=>g(l,a.id)},cancel:{label:"Cancel",onClick:()=>{}}})}})]})})}function C(e){var t;let{group:r,depth:a,itemNumberStart:l,isLocked:i,markupDefaults:d,tradeLabel:c,groupHeaderExtras:u,onEdit:m,onAddItem:h,onDeleteGroup:f,onOpenActions:v}=e,[y,j]=(0,o.useState)(a>0),k={...r,items:r.items.map(e=>{var t;return{...e,unitCost:e.cost,costType:null!==(t=e.lineItemType)&&void 0!==t?t:"labor"}})},w=(0,g.BQ)(k),C=(0,o.useCallback)(()=>{(0,s.A)("Delete this section and all its items?",{duration:8e3,action:{label:"Delete",onClick:()=>f(r.id)},cancel:{label:"Cancel",onClick:()=>{}}})},[r.id,f]),S=0===a?"hsl(var(--primary))":1===a?"#64748B":"#94A3B8";return(0,n.jsxs)("div",{"data-brion-line-item-group":r.id,"data-brion-line-item-group-name":r.name,"data-brion-line-item-group-depth":String(a),"data-brion-line-item-group-parent-id":null!==(t=r.parentGroupId)&&void 0!==t?t:"",className:"rounded-lg border border-border bg-muted overflow-hidden",style:{borderLeft:"3px solid ".concat(S)},children:[(0,n.jsxs)("button",{type:"button",onClick:()=>j(e=>!e),className:"flex w-full items-center gap-2 px-3 py-3 text-left","aria-expanded":!y,children:[(0,n.jsx)(x.Z,{className:"h-4 w-4 flex-shrink-0 text-muted-foreground transition-transform ".concat(y?"":"rotate-90"),strokeWidth:2.25}),(0,n.jsx)("span",{className:"flex-1 font-montserrat text-[13px] font-bold tracking-tight text-foreground",children:r.name||"Untitled section"}),c&&(0,n.jsx)("span",{className:"flex-shrink-0 rounded border border-border bg-card px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-wide text-amber-700 dark:text-amber-300",children:c}),(0,n.jsx)("span",{className:"font-mono text-[13px] font-bold tabular-nums text-muted-foreground",children:(0,g.xG)(w.revenue)})]}),!y&&(0,n.jsxs)("div",{className:"px-3 pb-3 space-y-2",children:[u&&(0,n.jsx)("div",{className:"flex flex-wrap items-center gap-1.5 pt-0.5",children:u(r.id,a)}),r.items.map((e,t)=>(0,n.jsx)(N,{item:e,groupId:r.id,itemNumber:l+t,isLocked:i,markupDefaults:d,onEdit:m,onOpenActions:v},e.id)),0===r.items.length&&!i&&(0,n.jsx)("p",{className:"px-1 py-2 text-[12px] italic text-muted-foreground",children:"No items yet â tap below to add one."}),!i&&(0,n.jsxs)("button",{type:"button","data-brion-action":"add-line-item",onClick:()=>h(r.id),className:"flex h-11 w-full items-center justify-center gap-2 rounded-lg border-2 border-dashed border-primary/50 text-[13px] font-semibold text-primary transition-colors hover:border-primary hover:bg-muted",children:[(0,n.jsx)(b.Z,{className:"h-4 w-4",strokeWidth:2.5}),"Add line to ",r.name.split("â")[0].trim()]}),!i&&(0,n.jsxs)("button",{type:"button",onClick:C,className:"flex items-center gap-1.5 px-1 py-1 text-[11px] text-muted-foreground hover:text-red-600 dark:hover:text-red-400",children:[(0,n.jsx)(p.Z,{className:"h-3 w-3",strokeWidth:2}),"Delete section"]})]}),y&&(0,n.jsx)("div",{className:"px-3 pb-2",children:(0,n.jsxs)("span",{className:"text-[11.5px] text-muted-foreground",children:[r.items.length," item",1!==r.items.length?"s":""]})})]})}function S(e){var t,r,a,l,i,d;let{item:c,groupId:u,isLocked:m,markupDefaults:x,onSave:b,onDelete:N,onClose:k}=e,[w,C]=(0,o.useState)({...c}),S=(0,o.useCallback)(e=>{C(t=>({...t,...e}))},[]),I=(0,o.useCallback)(e=>{let t={cost:e};if(x&&e>0){var r;let n=null!==(r=w.lineItemType)&&void 0!==r?r:"labor",o=x["subcontractor"===n?"subcontract":n];if("number"==typeof o&&o<100){let r=1-o/100;r>0&&(t.unitPrice=Math.round(e/r*100)/100)}}S(t)},[w.lineItemType,x,S]),A=(0,o.useCallback)(e=>{w.cost>0&&e<100&&S({unitPrice:Math.round(w.cost*(1+e/100)*100)/100})},[w.cost,S]),E=(0,o.useCallback)(e=>{S({unitPrice:e})},[S]),T=(0,o.useCallback)(e=>{if(w.cost>0&&e<100){let t=1-e/100;if(t>0){let e=w.cost*w.qty/t;S({unitPrice:Math.round(100*(w.qty>0?e/w.qty:0))/100})}}},[w.cost,w.qty,S]),P={...w,unitCost:w.cost,costType:null!==(t=w.lineItemType)&&void 0!==t?t:"labor"},D=(0,g.et)(P),F=(0,g.AM)(P),O=w.cost>0&&w.unitPrice>0?(w.unitPrice-w.cost)/w.cost*100:0,M=m?(0,n.jsx)("button",{type:"button",onClick:k,className:"flex h-11 w-full items-center justify-center rounded-lg border border-border text-[13px] font-semibold text-muted-foreground",children:"Close"}):(0,n.jsxs)("div",{className:"flex gap-2",children:[(0,n.jsxs)("button",{type:"button",onClick:()=>{(0,s.A)("Delete this line item?",{duration:8e3,action:{label:"Delete",onClick:()=>{N(u,c.id),k()}},cancel:{label:"Cancel",onClick:()=>{}}})},className:"flex h-11 items-center justify-center gap-2 rounded-lg border border-red-200 dark:border-red-800 px-4 text-[13px] font-semibold text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-950/40",children:[(0,n.jsx)(p.Z,{className:"h-4 w-4",strokeWidth:2}),"Delete"]}),(0,n.jsx)("button",{type:"button",onClick:()=>{b(u,c.id,w),k()},className:"flex h-11 flex-1 items-center justify-center gap-2 rounded-lg bg-primary text-[13px] font-bold text-primary-foreground hover:bg-primary/90",children:"Save"})]});return(0,n.jsx)(f.R,{open:!0,onOpenChange:e=>{e||k()},title:m?w.description||"Line item":"Edit line item",footer:M,snapPoints:[85
1],children:(0,n.jsxs)("div",{"data-brion-line-item-row":"","data-brion-line-item-row-id":c.id,className:"space-y-4",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("label",{className:"mb-1 block text-[11px] font-bold uppercase tracking-wider text-muted-foreground",children:"Description"}),(0,n.jsx)("textarea",{"data-brion-line-item-field":"description",rows:2,autoFocus:!0,readOnly:m,value:w.description,onChange:e=>S({description:e.target.value}),onInput:e=>{let t=e.currentTarget;t.style.height="auto",t.style.height="".concat(t.scrollHeight,"px")},placeholder:"Item description",className:"w-full resize-none rounded-lg border border-border bg-muted px-3 py-2.5 text-[14px] text-foreground placeholder:text-muted-foreground/50 focus:border-primary focus:bg-background focus:outline-none"})]}),(0,n.jsxs)("div",{className:"grid grid-cols-2 gap-3",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("label",{className:"mb-1 block text-[11px] font-bold uppercase tracking-wider text-muted-foreground",children:"Qty"}),(0,n.jsx)("input",{type:"number",inputMode:"decimal","data-brion-line-item-field":"qty",readOnly:m,value:w.qty||"",onChange:e=>S({qty:parseFloat(e.target.value)||0}),min:0,step:"0.01",placeholder:"0",className:"h-11 w-full rounded-lg border border-border bg-muted px-3 text-right font-mono text-[14px] tabular-nums text-foreground focus:border-primary focus:bg-background focus:outline-none [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("label",{className:"mb-1 block text-[11px] font-bold uppercase tracking-wider text-muted-foreground",children:"Unit"}),(0,n.jsx)("select",{"data-brion-line-item-field":"unit",disabled:m,value:w.unit,onChange:e=>S({unit:e.target.value}),className:"h-11 w-full rounded-lg border border-border bg-muted px-3 text-[13px] font-mono uppercase text-muted-foreground focus:border-primary focus:bg-background focus:outline-none",children:(!(d=w.unit)||j.includes(d)?j:[d,...j]).map(e=>(0,n.jsx)("option",{value:e,children:e},e))})]})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("label",{className:"mb-1 block text-[11px] font-bold uppercase tracking-wider text-muted-foreground",children:"Cost (per unit)"}),(0,n.jsxs)("div",{className:"flex h-11 items-center rounded-lg border border-border bg-muted px-3 focus-within:border-primary focus-within:bg-background",children:[(0,n.jsx)("span",{className:"text-[13px] text-muted-foreground",children:"$"}),(0,n.jsx)("input",{type:"number",inputMode:"decimal",readOnly:m,value:w.cost||"",onChange:e=>I(parseFloat(e.target.value)||0),step:"0.01",placeholder:"0.00",className:"h-full flex-1 bg-transparent pl-1 text-right font-mono text-[14px] tabular-nums text-foreground focus:outline-none [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"})]})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("label",{className:"mb-1 block text-[11px] font-bold uppercase tracking-wider text-muted-foreground",children:"Pricing"}),(0,n.jsxs)("div",{className:"grid grid-cols-3 gap-2",children:[(0,n.jsxs)("div",{className:"flex flex-col",children:[(0,n.jsx)("span",{className:"mb-1 text-[10px] text-muted-foreground",children:"Markup%"}),(0,n.jsxs)("div",{className:"flex h-11 items-center rounded-lg border border-border bg-muted px-2 focus-within:border-primary focus-within:bg-background",children:[(0,n.jsx)("input",{type:"number",inputMode:"decimal","data-brion-line-item-field":"markupPercent",readOnly:m,value:w.cost>0?O.toFixed(1):"",onChange:e=>A(parseFloat(e.target.value)||0),step:"0.1",placeholder:"â",className:"h-full w-full bg-transparent text-right font-mono text-[13px] tabular-nums text-foreground focus:outline-none [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"}),(0,n.jsx)("span",{className:"ml-0.5 text-[11px] text-muted-foreground",children:"%"})]})]}),(0,n.jsxs)("div",{className:"flex flex-col",children:[(0,n.jsx)("span",{className:"mb-1 text-[10px] text-muted-foreground",children:"Price"}),(0,n.jsxs)("div",{className:"flex h-11 items-center rounded-lg border border-border bg-muted px-2 focus-within:border-primary focus-within:bg-background",children:[(0,n.jsx)("span",{className:"text-[11px] text-muted-foreground",children:"$"}),(0,n.jsx)("input",{type:"number",inputMode:"decimal","data-brion-line-item-field":"unitPrice",readOnly:m,value:w.unitPrice||"",onChange:e=>E(parseFloat(e.target.value)||0),step:"0.01",placeholder:"0.00",className:"h-full flex-1 bg-transparent text-right font-mono text-[13px] tabular-nums text-foreground focus:outline-none [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none"})]})]}),(0,n.jsxs)("div",{className:"flex flex-col",children:[(0,n.jsx)("span",{className:"mb-1 text-[10px] text-muted-foreground",children:"Margin"}),(0,n.jsxs)("div",{className:"flex h-11 items-center rounded-lg border px-2 focus-within:border-primary",style:{borderColor:w.cost>0?"".concat(v(F),"60"):"hsl(var(--border))",background:w.cost>0?"".concat(v(F),"0D"):"hsl(var(--muted))"},children:[(0,n.jsx)("input",{type:"number",inputMode:"decimal","data-brion-line-item-field":"marginPercent",readOnly:m,value:w.cost>
10?F.toFixed(1):"",onChange:e=>T(parseFloat(e.target.value)||0),step:"0.1",placeholder:"â",className:"h-full w-full bg-transparent text-right font-mono text-[13px] tabular-nums focus:outline-none [appearance:textfield] [&::-webkit-inner-spin-button]:appearance-none [&::-webkit-outer-spin-button]:appearance-none",style:{color:w.cost>0?v(F):"hsl(var(--foreground))"}}),(0,n.jsx)("span",{className:"ml-0.5 text-[11px]",style:{color:w.cost>0?v(F):"hsl(var(--muted-foreground))"},children:"%"})]})]})]}),w.qty>0&&w.unitPrice>0&&(0,n.jsxs)("div",{className:"mt-1.5 flex items-center justify-between text-[12px]",children:[(0,n.jsxs)("span",{className:"text-muted-foreground",children:[w.qty," \xd7 ",(0,g.xG)(w.unitPrice)]}),(0,n.jsxs)("span",{className:"font-mono font-bold tabular-nums text-foreground",children:["= ",(0,g.xG)(D)]})]})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("label",{className:"mb-1 block text-[11px] font-bold uppercase tracking-wider text-muted-foreground",children:"Cost type"}),(0,n.jsx)("div",{className:"flex flex-wrap gap-1.5",children:y.map(e=>(0,n.jsx)("button",{type:"button",disabled:m,onClick:()=>S({lineItemType:e.value}),className:"flex h-9 items-center gap-1.5 rounded-lg border px-3 text-[12px] font-semibold transition-colors disabled:opacity-60",style:w.lineItemType!==e.value&&(w.lineItemType||"labor"!==e.value)?{background:"hsl(var(--muted))",color:"hsl(var(--foreground))",borderColor:"hsl(var(--border))"}:{background:e.bg,color:e.text,borderColor:e.bg},children:e.label},e.value))})]}),(0,n.jsxs)("div",{className:"flex gap-3",children:[(0,n.jsxs)("label",{className:"flex flex-1 items-center justify-between rounded-lg border border-border bg-muted px-3 py-2.5",children:[(0,n.jsx)("span",{className:"text-[13px] font-medium text-foreground",children:"Optional"}),(0,n.jsx)("input",{type:"checkbox",disabled:m,checked:null!==(r=w.isOptional)&&void 0!==r&&r,onChange:e=>S({isOptional:e.target.checked}),className:"h-4 w-4 rounded border-border accent-primary disabled:opacity-50"})]}),(0,n.jsxs)("label",{className:"flex flex-1 items-center justify-between rounded-lg border border-border bg-muted px-3 py-2.5",children:[(0,n.jsx)("span",{className:"text-[13px] font-medium text-foreground",children:"Taxable"}),(0,n.jsx)("input",{type:"checkbox",disabled:m,checked:null===(a=w.taxable)||void 0===a||a,onChange:e=>S({taxable:e.target.checked}),className:"h-4 w-4 rounded border-border accent-primary disabled:opacity-50"})]})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("label",{className:"mb-1 block text-[11px] font-bold uppercase tracking-wider text-muted-foreground",children:"Internal notes"}),(0,n.jsx)("textarea",{rows:2,readOnly:m,value:null!==(l=w.notes)&&void 0!==l?l:"",onChange:e=>S({notes:e.target.value}),placeholder:"Notes visible only to youâ¦",className:"w-full resize-none rounded-lg border border-border bg-muted px-3 py-2.5 text-[13px] text-muted-foreground placeholder:text-muted-foreground/50 focus:border-primary focus:bg-background focus:outline-none"})]}),(0,n.jsxs)("div",{children:[(0,n.jsxs)("label",{className:"mb-1 flex items-center gap-2 text-[11px] font-bold uppercase tracking-wider text-muted-foreground",children:["Customer-visible name",(0,n.jsx)("span",{className:"rounded bg-amber-100 dark:bg-amber-950/40 px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-wide text-amber-900 dark:text-amber-300 normal-case",children:"optional"})]}),(0,n.jsx)("textarea",{rows:1,readOnly:m,value:null!==(i=w.customerDescription)&&void 0!==i?i:"",onChange:e=>S({customerDescription:e.target.value}),placeholder:"Different name for the customerâ¦",className:"w-full resize-none rounded-lg border border-border bg-muted px-3 py-2.5 text-[13px] text-muted-foreground placeholder:text-muted-foreground/50 focus:border-primary focus:bg-background focus:outline-none"})]}),m&&(0,n.jsxs)("div",{className:"flex items-center gap-2 rounded-lg border border-amber-200 dark:border-amber-700/50 bg-amber-100 dark:bg-amber-950/40 px-3 py-2.5 text-[12px] text-amber-900 dark:text-amber-300",children:[(0,n.jsx)(h.Z,{className:"h-3.5 w-3.5 flex-shrink-0",strokeWidth:2}),"This estimate is locked â create a revision to edit."]})]})})}function I(e){var t;let{lineGroups:r,groupTradeLabels:s,isLocked:a,markupDefaults:l,onUpdateItem:i,onDeleteItem:d,onDuplicateItem:c,onAddItem:u,onAddGroup:m,onDeleteGroup:p,onOpenCatalogPicker:x,groupHeaderExtras:h}=e,[f,y]=(0,o.useState)(null),[j,N]=(0,o.useState)(null),k=(0,o.useCallback)((e,t)=>{y({groupId:e,itemId:t})},[]),I=(0,o.useCallback)(()=>{y(null)},[]),A=(0,o.useCallback)((e,t)=>{N({groupId:e,itemId:t})},[]),E=(0,o.useCallback)(()=>{N(null)},[]),T=(0,o.useCallback)((e,t,r)=>{i(e,t,r)},[i]),P=(0,o.useCallback)(()=>{let e=r[r.length-1];if(!e){m();return}u(e.id),requestAnimationFrame(()=>{y(()=>{let t=e.items[e.items.length-1];return t?{groupId:e.id,itemId:t.id}:null})})},[r,m,u]),D=1,F=new Map;for(let e of r)for(let t of e.items)F.set(t.id,D++);let{revenue:O,marginPct:M}=function(e){let t=0,r=0;for(let o of e)for(let e of o.items){var n;let o={...e,unitCost:e.cost,costType:null!==(n=e.lineItemType)&&void 0!==n?n:"labor"};t+=(0,g.et)(o),r+=(0,g.vS)(o)}let o=t>0?(t-r)/t*100:0;return{revenue:t,cost:r,marginPct:o}}(r),Z=f?r.find(e=>e.id===f.groupId):void 0,G=Z?Z.items.find(e=>e.id===(null==f?void 0:f.itemId)):void 0,L=j?null===(t=r.find(e=>e.id===j.groupId))||void 0===t?void 0:t.items.find(e=>e.id===j.itemId):void 0;return(0,n.jsxs)("div",{className:"flex flex-col",children:[(0,n.jsxs)("div",{className:"space-y-3 px-3 pb-32",children:[0===r.length&&(0,n.jsx)("p",{className:"py-8 text-center text-[13px] italic text-muted-foreground",children:"No sections yet â tap âAdd sectionâ below to start."}),r.map((e,t)=>{let o=1;for(let e=0;e<t;e++)o+=r[e].items.length;return(0,n.jsx)(C,{group:e,depth:0,itemNumberStart:o,isLocked:a,markupDefaults:l,tradeLabel:null==s?void 0:s[e.id],groupHeaderExtras:h,onEdit:k,onAddItem:u,onDeleteGroup:p,onOpenActions:A},e.id)}),!a&&(0,n.jsxs)("button",{type:"button","data-brion-action":"add-line-item-group",onClick:m,className:"flex h-11 w-full items-center justify-center gap-2 rounded-lg border-2 border-dashed border-border text-[13px] font-medium text-muted-foreground transition-colors hover:border-primary/50 hover:text-primary",children:[(0,n.jsx)(b.Z,{className:"h-4 w-4",strokeWidth:2}),"Add section"]})]}),(0,n.jsxs)("div",{className:"fixed bottom-0 left-0 right-0 z-40 border-t border-border bg-card px-3 pb-[calc(0.75rem+env(safe-area-inset-bottom,0px))] pt-3 shadow-[0_-4px_16px_rgba(28,21,9,0.08)]",children:[(0,n.jsxs)("div",{className:"mb-2.5 flex items-center justify-between",children:[(0,n.jsx)("span",{className:"text-[12px] text-muted-foreground",children:"Total"}),(0,n.jsxs)("div",{className:"flex items-center gap-3",children:[(0,n.jsxs)("span",{className:"inline-flex items-center gap-1 rounded-full px-2.5 py-1 text-[11px] font-bold",style:{background:O>0?"".concat(v(M),"14"):"hsl(var(--muted))",color:O>0?v(M):"hsl(var(--muted-foreground))"},children:[(0,n.jsx)("span",{className:"h-1.5 w-1.5 rounded-full",style:{background:O>0?v(M):"hsl(var(--muted-foreground))"}}),O>0?"".concat(M.toFixed(1),"%"):"â"]}),(0,n.jsx)("span",{className:"font-mono text-[18px] font-bold tabular-nums text-foreground","data-brion-form-total":String(O),children:(0,g.xG)(O)})]})]}),!a&&(0,n.jsxs)("button",{type:"button","data-brion-action":"add-line-item",onClick:P,className:"flex h-12 w-full items-center justify-center gap-2 rounded-xl bg-primary text-[14px] font-bold text-primary-foreground hover:bg-primary/90 active:scale-[0.98] transition-all",children:[(0,n.jsx)(b.Z,{className:"h-5 w-5",strokeWidth:2.5}),"Add line item"]})]}),f&&G&&(0,n.jsx)(S,{item:G,groupId:f.groupId,isLocked:a,markupDefaults:l,onSave:T,onDelete:d,onClose:I}
1),j&&L&&!a&&(0,n.jsx)(w,{item:L,groupId:j.groupId,onEdit:k,onDuplicate:c,onUpdateItem:i,onDelete:d,onOpenCatalogPicker:x,onClose:E})]})}var A=r(3458),E=r(14699),T=r(35995),P=r(20144),D=r(96825),F=r(85481),O=r(38333),M=r(38983),Z=r(47586),G=r(84792),L=r(36673),R=r(31003),B=r(22503),q=r(20361),W=r(31751);let _=(0,o.forwardRef)(function(e,t){let{isOptional:r,taxable:i,recentChanges:c,notesOpen:u,hasNotes:x,onToggleNotes:b,customerDescOpen:h,hasCustomerDesc:f,onToggleCustomerDesc:g,onDuplicate:v,onDelete:y,onToggleOptional:j,onToggleTaxable:N,onApplyToScope:k,onOpenCatalog:w,onMoveProject:C,onOfferChoices:S,optionCount:I=0}=e,[A,E]=(0,o.useState)(!1),T=(0,o.useRef)(null);(0,o.useImperativeHandle)(t,()=>({open:()=>E(!0)}),[]),(0,o.useEffect)(()=>{let e=e=>{T.current&&!T.current.contains(e.target)&&E(!1)};return A&&document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e)},[A]),(0,o.useEffect)(()=>{let e=e=>{"Escape"===e.key&&E(!1)};return A&&document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[A]);let P=c.size>0;return(0,n.jsxs)("div",{ref:T,className:"relative",children:[(0,n.jsx)("button",{type:"button",onClick:()=>E(e=>!e),title:"Line options","aria-haspopup":"true","aria-expanded":A,className:"flex h-6 w-6 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:(0,n.jsx)(l.Z,{className:"h-3.5 w-3.5",strokeWidth:2})}),A&&(0,n.jsxs)("div",{role:"menu",className:"absolute right-0 top-full z-30 mt-1 w-56 rounded-lg border border-border bg-card py-1 text-[12.5px] shadow-lg",children:[(0,n.jsxs)("button",{type:"button",role:"menuitem",onClick:()=>{b(),E(!1)},className:"flex w-full items-center gap-2 px-3 py-1.5 text-left text-foreground hover:bg-muted",children:[(0,n.jsx)(a.Z,{className:"h-3.5 w-3.5 text-muted-foreground",strokeWidth:2}),u?"Hide internal note":x?"Edit internal note":"Add internal note"]}),(0,n.jsxs)("button",{type:"button",role:"menuitem",onClick:()=>{g(),E(!1)},className:"flex w-full items-center gap-2 px-3 py-1.5 text-left text-foreground hover:bg-muted",children:[(0,n.jsx)(B.Z,{className:"h-3.5 w-3.5 text-muted-foreground",strokeWidth:2}),h?"Hide customer description":f?"Edit customer description":"Add customer description"]}),w&&(0,n.jsxs)("button",{type:"button",role:"menuitem",onClick:()=>{w(),E(!1)},className:"flex w-full items-center gap-2 px-3 py-1.5 text-left text-foreground hover:bg-muted",children:[(0,n.jsx)(m.Z,{className:"h-3.5 w-3.5 text-muted-foreground",strokeWidth:2}),"Pick from catalog"]}),S&&(0,n.jsxs)("button",{type:"button",role:"menuitem","data-brion-action":"offer-choices-on-line",onClick:()=>{S(),E(!1)},className:"flex w-full items-center gap-2 px-3 py-1.5 text-left text-foreground hover:bg-muted",children:[(0,n.jsx)(q.Z,{className:"h-3.5 w-3.5 text-primary",strokeWidth:2}),(0,n.jsx)("span",{className:"flex-1",children:I>0?"Edit choices on this line":"Offer choices on this line"}),I>0&&(0,n.jsx)("span",{className:"ml-auto rounded-full bg-primary/10 px-1.5 py-0.5 text-[9.5px] font-semibold text-primary",children:I})]}),(0,n.jsxs)("button",{type:"button",role:"menuitem","data-brion-action":"duplicate-line-item",onClick:()=>{v(),E(!1)},className:"flex w-full items-center gap-2 px-3 py-1.5 text-left text-foreground hover:bg-muted",children:[(0,n.jsx)(d.Z,{className:"h-3.5 w-3.5 text-muted-foreground",strokeWidth:2}),"Duplicate item"]}),(0,n.jsxs)("button",{type:"button",role:"menuitem","data-brion-action":"delete-line-item",onClick:()=>{(0,s.A)("Delete this line?",{duration:8e3,action:{label:"Delete",onClick:()=>y()},cancel:{label:"Cancel",onClick:()=>{}}}),E(!1)},className:"flex w-full items-center gap-2 px-3 py-1.5 text-left text-red-600 hover:bg-red-50",children:[(0,n.jsx)(p.Z,{className:"h-3.5 w-3.5",strokeWidth:2}),"Delete item"]}),C&&(0,n.jsxs)("button",{type:"button",role:"menuitem",onClick:()=>{C(),E(!1)},className:"flex w-full items-center gap-2 px-3 py-1.5 text-left text-foreground hover:bg-muted",children:[(0,n.jsx)(W.Z,{className:"h-3.5 w-3.5 text-muted-foreground",strokeWidth:2}),"Move to another project"]}),(0,n.jsx)("div",{className:"my-1 border-t border-border"}),(0,n.jsxs)("button",{type:"button",role:"menuitemcheckbox","aria-checked":r,onClick:()=>{j()},className:"flex w-full items-center gap-2 px-3 py-1.5 text-left text-foreground hover:bg-muted",children:[(0,n.jsx)("span",{className:"flex h-3.5 w-3.5 flex-shrink-0 items-center justify-center rounded border border-muted-foreground text-[9px] font-bold text-muted-foreground",children:r?"â":""}),"Optional"]}),(0,n.jsxs)("button",{type:"button",role:"menuitemcheckbox","aria-checked":null==i||i,onClick:()=>{N()},className:"flex w-full items-center gap-2 px-3 py-1.5 text-left text-foreground hover:bg-muted",children:[(0,n.jsx)("span",{className:"flex h-3.5 w-3.5 flex-shrink-0 items-center justify-center rounded border border-muted-foreground text-[9px] font-bold text-muted-foreground",children:null==i||i?"â":""}),"Taxable"]}),P&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"my-1 border-t border-border"}),(0,n.jsx)("div",{className:"px-3 py-1 text-[10.5px] font-bold uppercase tracking-[0.08em] text-muted-foreground",children:"Apply last change toâ¦"}),Array.from(c).map(e=>(0,n.jsxs)("div",{children:[(0,n.jsxs)("button",{type:"button",role:"menuitem",onClick:()=>{k(e,"group"),E(!1)},className:"flex w-full items-center gap-2 px-3 py-1.5 text-left text-foreground hover:bg-muted",children:[(0,n.jsx)("span",{className:"h-3.5 w-3.5 flex-shrink-0"}),"All lines in this group",(0,n.jsx)("span",{className:"ml-auto text-[10.5px] text-muted-foreground",children:"isOptional"===e?"optional":"taxable"})]}),(0,n.jsxs)("button",{type:"button",role:"menuitem",onClick:()=>{k(e,"estimate"),E(!1)},className:"flex w-full items-center gap-2 px-3 py-1.5 text-left text-foreground hover:bg-muted",children:[(0,n.jsx)("span",{className:"h-3.5 w-3.5 flex-shrink-0"}),"All lines in estimate",(0,n.jsx)("span",{className:"ml-auto text-[10.5px] text-muted-foreground",children:"isOptional"===e?"optional":"taxable"})]})]},e))]})]})]})});var U=r(46295),z=r(60537),K=r(37145);let V=[{key:"costType",label:"Cost type"},{key:"productionRate",label:"Production rate"},{key:"catalog",label:"Catalog ref"},{key:"notes",label:"Line notes"},{key:"optional",label:"Optional"},{key:"taxable",label:"Taxable"},{key:"specialOrder",label:"Special order",section:"Tracking"},{key:"orderStatus",label:"Order status",section:"Tracking"},{key:"supplier",label:"Supplier",section:"Tracking"},{key:"supplierEta",label:"Supplier ETA",section:"Tracking"},{key:"customerPromiseDate",label:"Customer promise date",section:"Tracking"},{key:"orderRef",label:"Order ref (PO#)",section:"Tracking"},{key:"bills",label:"Bills (coming soon)",section:"Job costing"},{key:"timeCost",label:"Time cost (coming soon)",section:"Job costing"},{key:"pctComplete",label:"% Done (coming soon)",section:"Job costing"},{key:"invoiced",label:"Invoiced (coming soon)",section:"Job costing"},{key:"variance",label:"Variance (coming soon)",section:"Job costing"},{key:"finalProfit",label:"Final profit (coming soon)",section:"Job costing"}],H=["each","hr","sqft","lf","lbs","unit","job","day"],J={draft:{label:"Draft",bg:"hsl(var(--muted))",text:"hsl(var(--muted-foreground))"},pending_client_approval:{label:"Pending client approval",bg:"#FDF3DC",text:"#92600B"},client_approved:{label:"Client approved",bg:"#E8F0EA",text:"#3D6442"},pending_org_approval:{label:"Pending org approval",bg:"#FDF3DC",text:"#92600B"},ordered:{label:"Ordered",bg:"#EFF6FF",text:"#1D4ED8"},confirmed:{label:"Confirmed",bg:"#EFF6FF",text:"#1D4ED8"},in_production:{label:"In production",bg:"#F3E8FF",text:"#6C5390"}
1,shipped:{label:"Shipped",bg:"#E0F2FE",text:"#075985"},delivered:{label:"Delivered",bg:"#ECFDF5",text:"#065F46"},delayed:{label:"Delayed",bg:"#FEF3C7",text:"#92400E"},cancelled:{label:"Cancelled",bg:"#FEF2F2",text:"#991B1B"}};function Q(e){if(!e)return"â";try{return new Date(e).toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})}catch(t){return e}}let $=[{value:"labor",label:"Labor",short:"L",ring:"border-[#3E6B8B] dark:border-[#7FA6C9]"},{value:"material",label:"Material",short:"M",ring:"border-[#3F7D6E] dark:border-[#6FB3A0]"},{value:"equipment",label:"Equipment",short:"E",ring:"border-[#B0842F] dark:border-[#D9B45F]"},{value:"subcontractor",label:"Subcontract",short:"S",ring:"border-[#6B5B8A] dark:border-[#A594C4]"},{value:"other",label:"Other",short:"O",ring:"border-[#A6705A] dark:border-[#C99B87]"}],Y="h-2 w-2 flex-shrink-0 rounded-full bg-transparent ".concat("border-[1.25px] dark:border-[1.5px]");function X(e){return"group:".concat(e)}function ee(e,t){return"item:".concat(e,":").concat(t)}function et(e){if(e.startsWith("group:"))return{kind:"group",groupId:e.slice(6)};if(e.startsWith("item:")){let[,t,r]=e.split(":");return{kind:"item",groupId:t,itemId:r}}return null}function er(e){let t,{lineGroups:r,estimateId:a,pinnedColumns:l,onSavePinnedColumns:i,phaseLabel:d="Estimating",isLocked:c,markupDefaults:u,showQuantity:m=!0,showUnit:p=!0,showPrice:x=!0,showAmount:f=!0,showOrderStatus:g=!1,onToggleColumns:v,detailLevel:y=null,onApplyD
1ocumentOptions:j,onUpdateItem:N,onDeleteItem:k,onDuplicateItem:w,onAddItem:C,onAddGroup:S,onAddSubGroup:A,onUpdateGroup:P,onDeleteGroup:Z,onMoveGroupToParent:G,onOpenCatalogPicker:L,onReorderItem:R,onMoveItemBetweenGroups:B,onReorderGroups:q,onApplyToScope:W,onOfferChoicesOnLine:_,onEditGroupParameters:K,assemblySourcedGroupIds:H,groupTradeLabels:J,groupHeaderExtras:Q,lineRowExtras:$,descriptionRowExtras:Y}=e,[ee,er]=(0,o.useState)(!1),[eo,es]=(0,o.useState)(null),ea=(0,z.j)(null!=a?a:""),el=!!a&&null!==eo,[ed,ec]=(0,o.useState)(null),eu=(0,E.Dy)((0,E.VT)(E.we,{activationConstraint:{distance:6}}),(0,E.VT)(E.Lg,{coordinateGetter:T.is})),em=r.reduce((e,t)=>e+t.items.length,0),ep=function(e){let t=new Map,r=1;for(let n of e)for(let e of n.items)t.set(e.id,r++);return t}(r),ex=12+l.size,eb=["description","qty","unit","unitPrice"],eh=(0,o.useRef)({}),ef=(0,o.useCallback)((e,t,r,n)=>{let o="".concat(e,":").concat(t,":").concat(r);eh.current[o]=n},[]),eg=(0,o.useCallback)(()=>{let e=[];for(let t of r)t.collapsed||t.items.forEach((r,n)=>{for(let r of eb)e.push({groupId:t.id,itemIndex:n,field:r})});return e},[r]),ev=(0,o.useCallback)((e,t,r)=>{let n=eh.current["".concat(e,":").concat(t,":").concat(r)];n&&(n.focus(),(n instanceof HTMLInputElement||n instanceof HTMLTextAreaElement)&&n.select())},[]),ey=(0,o.useCallback)((e,t,n,o)=>{if(c)return!1;if("Tab"===e.key||"Enter"===e.key){let s=eg(),a="".concat(t,":").concat(n,":").concat(o),l=s.findIndex(e=>"".concat(e.groupId,":").concat(e.itemIndex,":").concat(e.field)===a);if(-1===l)return!1;if("Tab"===e.key){let t=l+(e.shiftKey?-1:1);if(t>=0&&t<s.length){e.preventDefault();let r=s[t];return ev(r.groupId,r.itemIndex,r.field),!0}if(!e.shiftKey&&l===s.length-1){e.preventDefault();let t=r[r.length-1];if(t){C(t.id);let e=t.id,r=t.items.length;requestAnimationFrame(()=>ev(e,r,"description"))}return!0}return!1}e.preventDefault();let i=s.findIndex((e,r)=>r>l&&"description"===e.field&&(e.groupId!==t||e.itemIndex!==n));if(-1!==i){let e=s[i];return ev(e.groupId,e.itemIndex,"description"),!0}let d=r[r.length-1];if(d){C(d.id);let e=d.id,t=d.items.length;requestAnimationFrame(()=>ev(e,t,"description"))}return!0}return"Escape"===e.key&&(e.target.blur(),!0)},[c,eg,ev,r,C]),ej=(0,o.useRef)(null);(0,o.useEffect)(()=>{var e,t,n;if(c)return;let o=r[r.length-1];if(!o)return;let s=o.items[o.items.length-1];if(!s)return;let a=!(null===(e=s.description)||void 0===e?void 0:e.trim())&&(1===s.qty||0===s.qty)&&(!s.cost||0===s.cost)&&(!s.unitPrice||0===s.unitPrice)&&!(null===(t=s.notes)||void 0===t?void 0:t.trim())&&!(null===(n=s.customerDescription)||void 0===n?void 0:n.trim())&&(!s.lineItemType||"labor"===s.lineItemType);if(null===ej.current){ej.current=a;return}ej.current&&!a&&C(o.id),ej.current=a},[r,c,C]);let eN=ed?et(ed):null,ek=null;if((null==eN?void 0:eN.kind)==="group"){let e=r.find(e=>e.id===eN.groupId);e&&(ek=(0,n.jsxs)("div",{className:"flex items-center gap-2 rounded-lg border border-primary bg-amber-50 dark:bg-amber-950/40 px-3 py-2 shadow-lg text-[13px] font-bold text-foreground",children:[(0,n.jsx)(D.Z,{className:"h-4 w-4 text-muted-foreground"}),e.name]}))}else if((null==eN?void 0:eN.kind)==="item"){let e=r.find(e=>e.id===eN.groupId),t=null==e?void 0:e.items.find(e=>e.id===eN.itemId);t&&(ek=(0,n.jsxs)("div",{className:"flex items-center gap-2 rounded border border-border bg-card px-3 py-1.5 shadow-lg text-[13px] text-foreground",children:[(0,n.jsx)(D.Z,{className:"h-3.5 w-3.5 text-muted-foreground"}),t.description||"(empty)"]}))}let ew=r.filter(e=>{var t;return(null!==(t=e.parentGroupId)&&void 0!==t?t:null)===null}).map(e=>X(e.id)),eC=function(e){let t=[],r=(n,o)=>{for(let s of e.filter(e=>{var t;return(null!==(t=e.parentGroupId)&&void 0!==t?t:null)===n}))t.push({group:s,depth:o}),s.collapsed||r(s.id,o+1)};return r(null,0),t}(r),eS=a?Object.fromEntries(Object.entries(ea.grouped).map(e=>{let[t,r]=e;return[t,r.length]})):{},eI=(0,o.useCallback)((e,t)=>{if(_){_(e,t);return}if(!a)return;let n=r.find(t=>t.id===e),o=null==n?void 0:n.items.find(e=>e.id===t);o&&es({groupId:e,item:o})},[_,a,r]);return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"md:hidden",children:(0,n.jsx)(I,{lineGroups:r,groupTradeLabels:J,isLocked:c,markupDefaults:u,onUpdateItem:N,onDeleteItem:k,onDuplicateItem:w,onAddItem:C,onAddGroup:S,onDeleteGroup:Z,onOpenCatalogPicker:L,groupHeaderExtras:Q})}),(0,n.jsx)("div",{className:"hidden md:block",children:(0,n.jsxs)(E.LB,{sensors:eu,collisionDetection:E.pE,onDragStart:e=>{ec(String(e.active.id))},onDragEnd:e=>{ec(null);let{active:t,over:n}=e;if(!n||t.id===n.id)return;let o=et(String(t.id)),a=et(String(n.id));if(o&&a){if("group"===o.kind&&"group"===a.kind){let e=r.findIndex(e=>e.id===o.groupId),t=r.findIndex(e=>e.id===a.groupId);if(-1!==e&&-1!==t&&e!==t){var l,i;let n=r[e],o=r[t];if((null!==(l=n.parentGroupId)&&void 0!==l?l:null)!==(null!==(i=o.parentGroupId)&&void 0!==i?i:null)){s.A.error('Drag-and-drop reordering only works within the same parent level. Use "Move to parent" to re-nest.');return}q(e,t)}return}if("item"===o.kind){let e=r.find(e=>e.id===o.groupId);if(!e)return;let t=e.items.findIndex(e=>e.id===o.itemId);if(-1===t)return;if("item"===a.kind){let e=r.find(e=>e.id===a.groupId);if(!e)return;let n=e.items.findIndex(e=>e.id===a.itemId);if(-1===n)return;o.groupId===a.groupId?t!==n&&R(o.groupId,t,n):B(o.groupId,t,a.groupId,n)}else if("group"===a.kind&&o.groupId!==a.groupId){let e=r.find(e=>e.id===a.groupId);if(!e)return;B(o.groupId,t,a.groupId,e.items.length)}}}},children:[(0,n.jsxs)("div",{className:"rounded-lg border border-border bg-card",children:[(0,n.jsxs)("div",{className:"flex items-center justify-between border-b border-border bg-card px-4 py-2.5",children:[(0,n.jsx)("div",{className:"flex items-center gap-3 flex-wrap",children:(0,n.jsxs)("div",{className:"flex items-baseline gap-2",children:[(0,n.jsx)("h2",{className:"font-montserrat text-[14px] font-bold text-foreground",children:"Line items"}),(0,n.jsxs)("span",{className:"text-[12px] text-muted-foreground",children:["\xb7 ",em," item",1!==em?"s":""," in ",r.length," group",1!==r.length?"s":""]})]})}),(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsxs)("span",{className:"hidden items-center gap-1.5 rounded-md border border-border bg-muted px-2 py-1 text-[11px] font-medium text-muted-foreground sm:flex",children:[(0,n.jsx)("span",{className:"h-1.5 w-1.5 rounded-full bg-emerald-600 dark:bg-emerald-500"}),d," \xb7 ",ex," column",1!==ex?"s":""]}),(0,n.jsxs)("div",{className:"relative",children:[(0,n.jsxs)("button",{type:"button",onClick:()=>er(!ee),className:"flex h-7 items-center gap-1.5 rounded-md border border-border bg-card px-2.5 text-[12px] font-medium text-muted-foreground transition-colors hover:border-primary hover:bg-muted hover:text-foreground",children:[(0,n.jsx)(F.Z,{className:"h-3.5 w-3.5",
1strokeWidth:2}),"Columns"]}),ee&&(0,n.jsxs)("div",{className:"absolute right-0 top-9 z-20 w-64 rounded-lg border border-border bg-card p-1 shadow-[0_8px_24px_rgba(28,21,9,0.12)]",children:[(0,n.jsx)("div",{className:"px-2 py-1.5 text-[10.5px] font-bold uppercase tracking-[0.08em] text-muted-foreground",children:"Hidden columns"}),V.map(e=>{let r=e.section!==t;return t=e.section,(0,n.jsxs)("div",{children:[r&&e.section&&(0,n.jsxs)("div",{className:"mx-2 mb-0.5 mt-1.5 flex items-center gap-1.5",children:[(0,n.jsx)("span",{className:"text-[9.5px] font-bold uppercase tracking-[0.1em] ".concat("Tracking"===e.section?"text-emerald-600 dark:text-emerald-400":"text-muted-foreground"),children:e.section}),"Job costing"===e.section&&(0,n.jsx)("span",{className:"rounded bg-muted px-1 py-0 text-[8.5px] font-semibold uppercase tracking-wide text-muted-foreground",children:"Coming soon"}),"Tracking"===e.section&&(0,n.jsx)("span",{className:"rounded bg-emerald-100 dark:bg-emerald-950/40 px-1 py-0 text-[8.5px] font-semibold uppercase tracking-wide text-emerald-600 dark:text-emerald-400",children:"Special-order"})]}),(0,n.jsxs)("label",{className:"flex cursor-pointer items-center gap-2 rounded px-2 py-1.5 text-[12.5px] text-foreground hover:bg-muted ".concat("Job costing"===e.section?"opacity-50 cursor-not-allowed":""),children:[(0,n.jsx)("input",{type:"checkbox",checked:l.has(e.key),onChange:t=>{if("Job costing"===e.section)return;let r=new Set(l);t.target.checked?r.add(e.key):r.delete(e.key),i(r)},disabled:"Job costing"===e.section,className:"h-3.5 w-3.5 rounded border-border accent-primary disabled:opacity-40"}),(0,n.jsx)("span",{children:e.label})]})]},e.key)}),(0,n.jsx)("div",{className:"my-1 border-t border-border"}),(0,n.jsx)("button",{type:"button",className:"w-full rounded px-2 py-1.5 text-left text-[11.5px] font-medium text-muted-foreground hover:bg-muted hover:text-foreground",onClick:()=>er(!1),children:"â Customize phase columnsâ¦"})]})]})]})]}),(0,n.jsx)("div",{className:"overflow-x-auto estimate-hscroll",children:(0,n.jsxs)("table",{className:"w-full table-fixed border-collapse text-[13px] min-w-[1290px]",children:[(0,n.jsxs)("colgroup",{children:[(0,n.jsx)("col",{className:"w-[28px]"}),(0,n.jsx)("col",{className:"w-[30px]"}),(0,n.jsx)("col",{className:"w-[356px]"}),(0,n.jsx)("col",{className:"w-[64px]"}),(0,n.jsx)("col",{className:"w-[64px]"}),(0,n.jsx)("col",{className:"w-[104px]"}),(0,n.jsx)("col",{className:"w-[100px]"}),(0,n.jsx)("col",{className:"w-[80px]"}),(0,n.jsx)("col",{className:"w-[104px]"}),(0,n.jsx)("col",{className:"w-[100px]"}),l.has("costType")&&(0,n.jsx)("col",{className:"w-[96px]"}),l.has("productionRate")&&(0,n.jsx)("col",{className:"w-[110px]"}),l.has("catalog")&&(0,n.jsx)("col",{className:"w-[100px]"}),l.has("notes")&&(0,n.jsx)("col",{className:"w-[160px]"}),l.has("optional")&&(0,n.jsx)("col",{className:"w-[72px]"}),l.has("taxable")&&(0,n.jsx)("col",{className:"w-[68px]"}),l.has("specialOrder")&&(0,n.jsx)("col",{className:"w-[92px]"}),l.has("orderStatus")&&(0,n.jsx)("col",{className:"w-[112px]"}),l.has("supplier")&&(0,n.jsx)("col",{className:"w-[120px]"}),l.has("supplierEta")&&(0,n.jsx)("col",{className:"w-[96px]"}),l.has("customerPromiseDate")&&(0,n.jsx)("col",{className:"w-[112px]"}),l.has("orderRef")&&(0,n.jsx)("col",{className:"w-[104px]"}),l.has("bills")&&(0,n.jsx)("col",{className:"w-[80px]"}),l.has("timeCost")&&(0,n.jsx)("col",{className:"w-[80px]"}),l.has("pctComplete")&&(0,n.jsx)("col",{className:"w-[80px]"}),l.has("invoiced")&&(0,n.jsx)("col",{className:"w-[90px]"}),l.has("variance")&&(0,n.jsx)("col",{className:"w-[80px]"}),l.has("finalProfit")&&(0,n.jsx)("col",{className:"w-[90px]"}),(0,n.jsx)("col",{className:"w-[84px]"}),(0,n.jsx)("col",{className:"w-[108px]"}),!c&&(0,n.jsx)("col",{className:"w-[64px]"})]}),(0,n.jsxs)("thead",{children:[(0,n.jsxs)("tr",{className:"border-b border-border bg-muted",children:[(0,n.jsx)("th",{colSpan:2,className:"px-0 py-0","aria-hidden":"true"}),(0,n.jsx)("th",{colSpan:1,className:"sticky left-0 z-10 bg-muted px-3 py-[3px] text-left text-[9.5px] font-bold uppercase tracking-[0.12em] text-muted-foreground",children:"Details"}),(0,n.jsx)("th",{colSpan:8+l.size,className:"border-l border-border px-3 py-[3px] text-left text-[9.5px] font-bold uppercase tracking-[0.12em] text-muted-foreground",children:"Estimating"}),(0,n.jsx)("th",{colSpan:1,className:"border-l border-border px-3 py-[3px] text-right text-[9.5px] font-bold uppercase tracking-[0.12em] text-muted-foreground",children:"Total"}),!c&&(0,n.jsx)("th",{className:"sticky right-0 z-[3] bg-muted px-0 py-0 border-l border-border","aria-hidden":"true"})]}),(0,n.jsxs)("tr",{className:"border-b border-border bg-muted",children:[(0,n.jsx)(ei,{className:"w-7 border-r border-border"}),(0,n.jsx)(ei,{align:"right",className:"border-r border-border pr-2 text-muted-foreground",children:"#"}),(0,n.jsx)(ei,{align:"left",className:"sticky left-0 z-10 bg-muted border-r border-border",children:"Description"}),(0,n.jsx)(ei,{align:"right",className:"border-r border-border",children:!c&&v?(0,n.jsxs)("button",{type:"button",title:m?"Hide Qty + Unit from customer":"Show Qty + Unit to customer",onClick:()=>v({showQuantity:!m,showUnit:!m}),className:"inline-flex items-center gap-1 text-[11px] font-bold uppercase tracking-[0.07em] transition-colors hover:text-primary ".concat(m?"text-muted-foreground":"text-amber-500 dark:text-amber-400"),children:[m?(0,n.jsx)(O.Z,{className:"h-3 w-3",strokeWidth:2}):(0,n.jsx)(h.Z,{className:"h-3 w-3",strokeWidth:2}),"Qty"]}):"Qty"}),(0,n.jsx)(ei,{align:"left",className:"border-r border-border",children:"Unit"}),(0,n.jsx)(ei,{align:"right",className:"border-r border-border",children:"Cost"}),(0,n.jsx)(ei,{align:"right",className:"border-r border-border text-muted-foreground",children:"Ext. Cost"}),(0,n.jsx)(ei,{align:"right",className:"border-r border-border",children:(0,n.jsx)("span",{className:"inline-flex items-center gap-0.5 text-muted-foreground",children:"Markup%"})}),(0,n.jsx)(ei,{align:"right",className:"border-r border-border",children:!c&&v?(0,n.jsxs)("button",{type:"button",title:x?"Hide Price + Total from customer":"Show Price + Total to customer",onClick:()=>v({showPrice:!x,showAmount:!x}),className:"inline-flex items-center gap-1 text-[11px] font-bold uppercase tracking-[0.07em] transition-colors hover:text-primary ".concat(x?"text-muted-foreground":"text-amber-500 dark:text-amber-400"),children:[x?(0,n.jsx)(O.Z,{className:"h-3 w-3",strokeWidth:2}):(0,n.jsx)(h.Z,{className:"h-3 w-3",strokeWidth:2}),"Price"]}):"Price"}),(0,n.jsx)(ei,{align:"right",className:"border-r border-border text-muted-foreground",children:"Ext. Price"}),l.has("costType")&&(0,n.jsx)(ei,{align:"left",className:"border-r border-border",children:"Cost type"}),l.has("productionRate")&&(0,n.jsx)(ei,{align:"left",className:"border-r border-border",children:"Prod rate"}),l.has("catalog")&&(0,n.jsx)(ei,{align:"left",className:"border-r border-border",children:"Catalog"}),l.has("notes")&&(0,n.jsx)(ei,{align:"left",className:"border-r border-border",children:"Notes"}),l.has("optional")&&(0,n.jsx)(ei,{align:"center",className:"border-r border-border",children:"Optional"}),l.has("taxable")&&(0,n.jsx)(ei,{align:"center",className:"border-r border-border",children:"Taxable"}),l.has("specialOrder")&&(0,n.jsx)(ei,{align:"center",className:"border-r border-border bg-emerald-50 dark:bg-emerald-950/40 text-emerald-600 dark:text-emerald-400",children:"Special order"}),l.has("orderStatus")&&(0,n.jsx)(ei,{align:"left",className:"border-r border-border bg-emerald-50 dark:bg-emerald-950/40",children:!c&&v?(0,n.jsxs)("button",{type:"button",title:g?"Hide order status from customer document":"Show order status on customer document",onClick:()=>v({showOrderStatus:!g}),className:"inline-flex items-center gap-1 text-[11px] font-bold uppercase tracking-[0.07em] transition-colors hover:text-primary ".concat(g?"text-emerald-600 dark:text-emerald-400":"text-amber-500 dark:text-amber-400"),children:[g?(0,n.jsx)(O.Z,{className:"h-3 w-3",strokeWidth:2}):(0,n.jsx)(h.Z,{className:"h-3 w-3",strokeWidth:2}),"Order status"]}):(0,n.jsx)("span",{className:"text-emerald-600 dark:text-emerald-400",children:"Order status"})}),l.has("supplier")&&(0,n.jsx)(ei,{align:"left",className:"border-r border-border bg-emerald-50 dark:bg-emerald-950/40 text-emerald-600 dark:text-emerald-400",children:"Supplier"}),l.has("supplierEta")&&(0,n.jsx)(ei,{align:"left",className:"border-r border-border bg-emerald-50 dark:bg-emerald-950/40 text-emerald-600 dark:text-emerald-400",children:"Supplier ETA"}),l.has("customerPromiseDate")&&(0,n.jsx)(ei,{align:"left",className:"border-r border-border bg-emerald-50 dark:bg-emerald-950/40",children:!c&&v?(0,n.jsxs)("button",{type:"button",title:g?"Customer promise date is visible on customer document":"Enable order status to show customer promise date",onClick:()=>v({showOrderStatus:!g}),className:"inline-flex items-center gap-1 text-[11px] font-bold uppercase tracking-[0.07em] transition-colors hover:text-primary ".concat(g?"text-emerald-600 dark:text-emerald-400":"text-amber-500 dark:text-amber-400"),children:[g?(0,n.jsx)(O.Z,{className:"h-3 w-3",strokeWidth:2}):(0,n.jsx)(h.Z,{className:"h-3 w-3",strokeWidth:2}),"Promise date"]}):(0,n.jsx)("span",{className:"text-emerald-600 dark:text-emerald-400",children:"Promise date"})}),l.has("orderRef")&&(0,n.jsx)(ei,{align:"left",className:"border-r border-border bg-emerald-50 dark:bg-emerald-950/40 text-emerald-600 dark:text-emerald-400",children:"Order ref"}),l.has("bills")&&(0,n.jsx)(ei,{align:"right",className:"border-r border-border text-muted-foreground",children:"Bills"}),l.has("timeCost")&&(0,n.jsx)(ei,{align:"right",className:"border-r border-border",children:"Time cost"}),l.has("pctComplete")&&(0,n.jsx)(ei,{align:"right",className:"border-r border-border",children:"% Done"}),l.has("invoiced")&&(0,n.jsx)(ei,{align:"right",className:"border-r border-border",children:"Invoiced"}),l.has("variance")&&(0,n.jsx)(ei,{align:"right",className:"border-r border-border",children:"Variance"}),l.has("finalProfit")&&(0,n.jsx)(ei,{align:"right",className:"border-r border-border",children:"Final profit"}),(0,n.jsx)(ei,{align:"right",className:"border-r border-border",children:(0,n.jsxs)("span",{className:"inline-flex items-center gap-1",children:["Margin ",(0,n.jsx)(M.Z,{className:"h-3 w-3 opacity-60",strokeWidth:2.25})]})}),(0,n.jsx)(ei,{align:"right",className:"text-foreground",children:"Total"}),!c&&(0,n.jsx)(ei,{className:"sticky right-0 z-[3] bg-muted border-l border-border"})]})]}),(0,n.jsx)(T.Fo,{items:ew,strategy:T.qw,children:eC.map(e=>{let{group:t,depth:o}=e;return(0,n.jsx)(en,{group:t,depth:o,allGroups:r,isLocked:c,pinnedColumns:l,markupDefaults:u,itemNumberMap:ep,showOrderStatus:g,onUpdateItem:N,onDeleteItem:k,onDuplicateItem:w,onAddItem:C,onAddSubGroup:A,onUpdateGroup:P,onDeleteGroup:Z,onMoveGroupToParent:G,onOpenCatalogPicker:L,onApplyToScope:W,onOfferChoicesOnLine:a?eI:void 0,optionCountByLine:eS,onEditGroupParameters:K,assemblySourcedGroupIds:
1H,groupHeaderExtras:Q,lineRowExtras:$,descriptionRowExtras:Y,tradeLabel:null==J?void 0:J[t.id],registerCellRef:ef,handleCellKeyDown:ey},t.id)})}),!c&&(0,n.jsx)("tfoot",{children:(0,n.jsx)("tr",{children:(0,n.jsx)("td",{colSpan:ex+1,className:"px-4 py-3",children:(0,n.jsxs)("button",{type:"button",onClick:S,"data-brion-action":"add-line-item-group",className:"flex h-9 items-center gap-1.5 rounded-md border border-dashed border-border bg-card px-3 text-[12.5px] font-medium text-muted-foreground transition-colors hover:border-primary hover:bg-muted hover:text-foreground",children:[(0,n.jsx)(b.Z,{className:"h-3.5 w-3.5",strokeWidth:2}),"Add Group"]})})})})]})})]}),(0,n.jsx)(E.y9,{children:ek})]})}),a&&eo&&(0,n.jsx)(U.i,{open:el,onOpenChange:e=>{e||es(null)},estimateId:a,lineId:eo.item.id,lineDescription:eo.item.description,existingOptions:ea.getLineOptions(eo.item.id),isLocked:c,onCreate:ea.createOption,onUpdate:ea.updateOption,onDelete:ea.deleteOption})]})}function en(e){var t,r,a;let{group:l,depth:i,allGroups:d,isLocked:c,pinnedColumns:u,markupDefaults:m,itemNumberMap:h,showOrderStatus:f,onUpdateItem:v,onDeleteItem:y,onDuplicateItem:j,onAddItem:N,onAddSubGroup:k,onUpdateGroup:w,onDeleteGroup:C,onMoveGroupToParent:S,onOpenCatalogPicker:I,onApplyToScope:A,onOfferChoicesOnLine:E,optionCountByLine:F,onEditGroupParameters:B,assemblySourcedGroupIds:q,groupHeaderExtras:W,lineRowExtras:_,descriptionRowExtras:U,tradeLabel:z,registerCellRef:V,handleCellKeyDown:H}=e,J=11+u.size,Q=i<K.BG,$=!l.collapsed,Y=l.displayMode,[et,er]=(0,o.useState)(!1),en=!!(null===(t=l.description)||void 0===t?void 0:t.trim()),es=en?l.description.length>60?l.description.slice(0,60)+"â¦":l.description:null,{attributes:ea,listeners:ei,setNodeRef:ed,transform:ec,transition:eu,isDragging:em}=(0,T.nB)({id:X(l.id)}),ep={transform:P.ux.Transform.toString(ec),transition:eu,opacity:em?.4:1},ex={...l,items:l.items.map(e=>{var t;return{...e,unitCost:e.cost,costType:null!==(t=e.lineItemType)&&void 0!==t?t:"labor"}})},eb=(0,g.BQ)(ex),[eh,ef]=(0,o.useState)(!1),eg=(0,o.useRef)(null),ev=l.items.map(e=>ee(l.id,e.id)),ey=16*i;return(0,n.jsxs)("tbody",{ref:ed,style:ep,"data-brion-line-item-group":l.id,"data-brion-line-item-group-name":l.name,"data-brion-line-item-group-depth":String(i),"data-brion-line-item-group-parent-id":null!==(r=l.parentGroupId)&&void 0!==r?r:"",children:[(0,n.jsxs)("tr",{className:"border-y border-border",children:[(0,n.jsx)("td",{colSpan:J-1,className:"px-0 py-0",style:{background:0===i?"linear-gradient(90deg, hsl(var(--primary) / 0.08) 0%, hsl(var(--primary) / 0.03) 60%, transparent 100%)":1===i?"linear-gradient(90deg, rgba(100,116,139,0.07) 0%, rgba(100,116,139,0.02) 60%, rgba(255,255,255,0) 100%)":"linear-gradient(90deg, rgba(148,163,184,0.06) 0%, rgba(148,163,184,0.01) 60%, rgba(255,255,255,0) 100%)",borderLeft:"3px solid ".concat(0===i?"hsl(var(--primary))":1===i?"#64748B":"#94A3B8"),paddingLeft:ey>0?"".concat(ey,"px"):void 0},children:(0,n.jsxs)("div",{className:"flex items-center gap-3 px-3 py-2.5",children:[!c&&(0,n.jsx)("button",{type:"button",title:"Drag to reorder section",className:"flex h-6 w-6 cursor-grab items-center justify-center rounded text-muted-foreground hover:text-foreground active:cursor-grabbing",...ea,...ei,children:(0,n.jsx)(D.Z,{className:"h-4 w-4",strokeWidth:2})}),(0,n.jsx)("button",{type:"button",onClick:()=>w(l.id,{collapsed:$}),className:"flex h-6 w-6 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground",children:(0,n.jsx)(x.Z,{className:"h-4 w-4 transition-transform ".concat($?"rotate-90":""),strokeWidth:2.25})}),c?(0,n.jsx)("span",{className:"flex-1 font-montserrat text-[14px] font-bold tracking-tight text-foreground",children:l.name}):(0,n.jsx)("input",{type:"text",value:l.name,onChange:e=>w(l.id,{name:e.target.value}),className:"flex-1 bg-transparent font-montserrat text-[14px] font-bold tracking-tight text-foreground focus:outline-none",placeholder:"Section name"}),z&&(0,n.jsx)("span",{className:"flex-shrink-0 rounded border border-border bg-muted px-1.5 py-0.5 text-[9.5px] font-semibold uppercase tracking-wide text-amber-700 dark:text-amber-400",children:z}),(0,n.jsxs)("span",{className:"font-mono text-[11px] tabular-nums text-muted-foreground",children:[l.items.length," item",1!==l.items.length?"s":""]}),!c&&(0,n.jsxs)("div",{className:"relative",children:[(0,n.jsxs)("button",{ref:eg,type:"button",title:"Controls what the customer sees. Editor always shows all lines.",onClick:()=>ef(e=>!e),className:"flex h-7 items-center gap-1.5 rounded-md border px-2 text-[10.5px] font-semibold uppercase tracking-wider transition-colors ".concat("itemsNoPrice"===Y?"border-blue-300 bg-blue-50 dark:bg-blue-950/40 text-blue-600 dar
1k:text-blue-400":"summary"===Y?"border-primary bg-amber-50 dark:bg-amber-950/40 text-primary":"hidden"===Y?"border-red-300 bg-red-50 dark:bg-red-950/40 text-red-600 dark:text-red-400":"subtotal"===Y?"border-purple-300 bg-purple-50 dark:bg-purple-950/40 text-purple-600 dark:text-purple-400":"inherit"===Y?"border-border bg-muted text-muted-foreground":"border-border bg-card text-muted-foreground hover:border-primary/50"),children:["expanded"===Y&&(0,n.jsx)(O.Z,{className:"h-3 w-3",strokeWidth:2}),"itemsNoPrice"===Y&&(0,n.jsx)(Z.Z,{className:"h-3 w-3",strokeWidth:2}),"summary"===Y&&(0,n.jsx)(M.Z,{className:"h-3 w-3",strokeWidth:2}),"hidden"===Y&&(0,n.jsx)(G.Z,{className:"h-3 w-3",strokeWidth:2}),"subtotal"===Y&&(0,n.jsx)(M.Z,{className:"h-3 w-3",strokeWidth:2}),"inherit"===Y&&(0,n.jsx)(O.Z,{className:"h-3 w-3",strokeWidth:2}),"expanded"===Y?"All lines":"itemsNoPrice"===Y?"Lines, no amounts":"summary"===Y?"Total only":"subtotal"===Y?"Subtotals only":"inherit"===Y?"Follow doc":"Hidden"]}),eh&&(0,n.jsx)(el,{currentMode:Y,onSelect:e=>{w(l.id,{displayMode:e}),ef(!1)},onClose:()=>ef(!1),anchorRef:eg})]}),!c&&(0,n.jsxs)("button",{type:"button",title:"Add description for customer",onClick:()=>er(e=>!e),className:"relative flex h-6 w-6 items-center justify-center rounded text-muted-foreground transition-colors hover:bg-muted hover:text-primary",style:en?{color:"hsl(var(--primary))"}:void 0,children:[(0,n.jsx)(L.Z,{className:"h-3.5 w-3.5",strokeWidth:2}),en&&(0,n.jsx)("span",{className:"absolute -top-0.5 -right-0.5 h-1.5 w-1.5 rounded-full bg-primary"})]}),!c&&Q&&k&&(0,n.jsxs)("button",{type:"button",title:'Add sub-group under "'.concat(l.name,'"'),onClick:()=>k(l.id),className:"flex h-6 items-center gap-1 rounded px-1.5 text-[10.5px] font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:[(0,n.jsx)(b.Z,{className:"h-3 w-3",strokeWidth:2}
1),"Sub-group"]}),null==W?void 0:W(l.id,i),!c&&i>0&&S&&(0,n.jsx)("button",{type:"button",title:"Promote to top-level group",onClick:()=>S(l.id,null),className:"flex h-6 items-center gap-1 rounded px-1.5 text-[10.5px] font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-muted-foreground",children:"â Top"})]})}),(0,n.jsx)("td",{className:"border-l border-border px-2 py-2.5 text-right align-middle",style:{background:"linear-gradient(90deg, hsl(var(--primary) / 0.05) 0%, transparent 100%)"},children:eb.revenue>0&&(0,n.jsxs)("span",{className:"inline-flex h-5 items-center gap-1 rounded-full px-1.5 text-[10px] font-semibold tabular-nums",style:{background:eb.margin>=25?"rgba(61,100,66,0.12)":eb.margin>=15?"rgba(245,158,11,0.12)":"rgba(168,75,61,0.12)",color:eb.margin>=25?"#3D6442":eb.margin>=15?"#F59E0B":"#A84B3D"},title:"Group margin: ".concat(eb.margin.toFixed(1),"%"),children:[(0,n.jsx)("span",{className:"h-1.5 w-1.5 rounded-full",style:{background:eb.margin>=25?"#3D6442":eb.margin>=15?"#F59E0B":"#A84B3D"}}),eb.margin.toFixed(0),"%"]})}),(0,n.jsx)("td",{className:"border-l border-border px-3 py-2.5 text-right align-middle",style:{background:"linear-gradient(90deg, hsl(var(--primary) / 0.05) 0%, transparent 100%)"},children:(0,n.jsx)("span",{className:"font-mono text-[14px] font-bold tabular-nums text-foreground",children:(0,g.xG)(eb.revenue)})}),!c&&(0,n.jsx)("td",{className:"sticky right-0 z-[2] pl-1 pr-2 py-2.5 text-right align-middle bg-card border-l border-border",children:(0,n.jsxs)("div",{className:"flex items-center justify-end gap-0.5",children:[(null==q?void 0:q.has(l.id))&&B&&(0,n.jsx)("button",{type:"button",onClick:()=>B(l.id),title:"Edit assembly parameters",className:"flex h-6 w-6 items-center justify-center rounded text-muted-foreground hover:bg-amber-50 dark:hover:bg-amber-950/40 hover:text-primary",children:(0,n.jsx)(R.Z,{className:"h-3.5 w-3.5",strokeWidth:2})}),(0,n.jsx)("button",{type:"button",onClick:()=>{(0,s.A)("Delete this section and all its items?",{duration:8e3,action:{label:"Delete",onClick:()=>C(l.id)},cancel:{label:"Cancel",onClick:()=>{}}})},title:"Delete section",className:"flex h-6 w-6 items-center justify-center rounded text-muted-foreground hover:bg-red-50 dark:hover:bg-red-950/40 hover:text-red-600 dark:hover:text-red-400",children:(0,n.jsx)(p.Z,{className:"h-3.5 w-3.5",strokeWidth:2})})]})})]}),!c&&et&&(0,n.jsx)("tr",{children:(0,n.jsx)("td",{colSpan:J+2,className:"px-4 pb-2 pt-1",children:(0,n.jsx)("textarea",{value:null!==(a=l.description)&&void 0!==a?a:"",onChange:e=>w(l.id,{description:e.target.value}),placeholder:"Customer-visible description of this section. Shown above the line items on the sent estimate.",rows:2,className:"w-full rounded border border-border bg-muted px-3 py-2 text-[12.5px] text-muted-foreground placeholder:text-muted-foreground/50 resize-none focus:outline-none focus:border-primary"})})}),!c&&!et&&!$&&en&&(0,n.jsx)("tr",{children:(0,n.jsx)("td",{colSpan:J+2,className:"px-4 pb-1.5 pt-0",children:(0,n.jsx)("p",{className:"text-[11.5px] italic text-muted-foreground",children:es})})}),$&&(0,n.jsx)(T.Fo,{items:ev,strategy:T.qw,children:l.items.map((e,t)=>{var r,o;return(0,n.jsx)(eo,{item:e,itemIndex:t,itemNumber:null!==(r=h.get(e.id))&&void 0!==r?r:t+1,groupId:l.id,groupName:l.name,isLocked:c,pinnedColumns:u,markupDefaults:m,showOrderStatus:f,onUpdateItem:v,onDeleteItem:y,onDuplicateItem:j,onOpenCatalogPicker:I,onApplyToScope:A,onOfferChoicesOnLine:E,optionCount:null!==(o=null==F?void 0:F[e.id])&&void 0!==o?o:0,lineRowExtras:_,descriptionRowExtras:U,registerCellRef:V,handleCellKeyDown:H},e.id)})}),$&&!c&&(0,n.jsx)("tr",{children:(0,n.jsx)("td",{colSpan:J+2,className:"px-3 py-1.5",children:(0,n.jsxs)("button",{type:"button",onClick:()=>N(l.id),className:"flex h-7 items-center gap-1.5 rounded-md px-2 text-[12px] font-medium text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:[(0,n.jsx)(b.Z,{className:"h-3.5 w-3.5",strokeWidth:2}),"Add item to ",l.name.split("â")[0].trim()]})})})]})}function eo(e){var t,r,s,l,i,d,c,u,p,x,b,h,f,v,y,j,N;let{item:k,itemIndex:w,itemNumber:C,groupId:S,isLocked:I,pinnedColumns:A,markupDefaults:E,showOrderStatus:F,onUpdateItem:O,onDeleteItem:Z,onDuplicateItem:G,onOpenCatalogPicker:L,onApplyToScope:R,onOfferChoicesOnLine:B,optionCount:q=0,lineRowExtras:W,descriptionRowExtras:U,registerCellRef:z,handleCellKeyDown:K}=e,V={...k,unitCost:k.cost,costType:null!==(s=k.lineItemType)&&void 0!==s?s:"labor"},X=(0,g.et)(V),et=(0,g.vS)(V),er=(0,g.AM)(V),en=k.qty*k.cost,[eo,ea]=(0,o.useState)(!1),[el,ei]=(0,o.useState)(!1),[ep,ex]=(0,o.useState)(!1),eb=(0,o.useRef)(null),eh=(0,o.useRef)(null),ef=(0,o.useRef)(null),[eg,ev]=(0,o.useState)(new Set),{attributes:ey,listeners:ej,setNodeRef:eN,transform:ek,transition:ew,isDragging:eC}=(0,T.nB)({id:ee(S,k.id)}),eS={transform:P.ux.Transform.toString(ek),transition:ew,opacity:eC?.4:1},eI=(y=k.lineItemType,null!==(j=$.find(e=>e.value===(null!=y?y:"labor")))&&void 0!==j?j:$[0]),eA=!I&&!A.has("costType");return(0,n.jsxs)("tr",{ref:eN,style:eS,"data-brion-line-item-row":"","data-brion-line-item-row-id":k.id,onContextMenu:e=>{var t;!I&&(e.target.closest('input, textarea, select, [contenteditable="true"]')||(e.preventDefault(),null===(t=ef.current)||void 0===t||t.open()))},className:"group border-b border-border hover:bg-muted",children:[(0,n.jsx)("td",{className:"border-r border-border px-1.5 py-1.5 align-middle",children:(0,n.jsx)("button",{type:"button",title:"Drag to reorder",className:"flex h-5 w-5 cursor-grab items-center justify-center text-muted-foreground opacity-0 hover:text-muted-foreground active:cursor-grabbing group-hover:opacity-100 transition-opacity",...ey,...ej,children:(0,n.jsx)(D.Z,{className:"h-3.5 w-3.5",
1strokeWidth:2})})}),(0,n.jsx)("td",{className:"border-r border-border px-1.5 py-1.5 text-right align-middle",children:(0,n.jsx)("span",{className:"font-mono text-[11px] tabular-nums text-muted-foreground select-none",children:C})}),(0,n.jsx)("td",{className:"sticky left-0 z-[1] border-r border-border bg-card pl-2 pr-1 py-1.5 align-top group-hover:bg-muted focus-within:bg-muted/50",children:(0,n.jsxs)("div",{className:"flex flex-col gap-1 min-w-0",children:[I?(0,n.jsx)("span",{className:"whitespace-normal break-words text-[13px] font-medium text-foreground",children:k.description}):(0,n.jsxs)("div",{className:"flex items-start gap-2.5 min-w-0",children:[eA&&(0,n.jsxs)("div",{className:"flex-shrink-0",children:[(0,n.jsxs)("button",{ref:eb,type:"button",title:"Change cost type",onClick:()=>ex(e=>!e),className:"mt-px inline-flex h-6 items-center gap-1.5 rounded-md px-2 text-[11px] font-medium leading-none text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring ".concat(ep?"bg-muted text-foreground":""),children:[(0,n.jsx)("span",{className:"".concat(Y," ").concat(eI.ring),"aria-hidden":"true"}),eI.label,(0,n.jsx)(M.Z,{className:"h-3 w-3 opacity-50",strokeWidth:2.5})]}),ep&&(0,n.jsx)(es,{currentValue:null!==(l=k.lineItemType)&&void 0!==l?l:"labor",onSelect:e=>{O(S,k.id,{lineItemType:e}),ex(!1)},onClose:()=>ex(!1),anchorRef:eb})]}),(0,n.jsx)("textarea",{rows:1,"data-brion-line-item-field":"description",value:k.description,onChange:e=>{O(S,k.id,{description:e.target.value})},onInput:e=>{let t=e.currentTarget;t.style.height="auto",t.style.height="".concat(t.scrollHeight,"px")},onKeyDown:e=>{if("Enter"===e.key&&!e.shiftKey){e.preventDefault(),K(e,S,w,"description");return}K(e,S,w,"description")&&e.preventDefault()},ref:e=>{z(S,w,"description",e),e&&(e.style.height="auto",e.style.height="".concat(e.scrollHeight,"px"))},placeholder:"Item description",className:"flex-1 min-w-0 resize-none overflow-hidden bg-transparent pr-1 text-[13px] font-medium leading-snug text-foreground focus:outline-none placeholder:text-muted-foreground/50"})]}),k.notes&&!A.has("notes")&&(0,n.jsxs)("span",{className:"flex items-center gap-1 text-[11px] text-muted-foreground",children:[(0,n.jsx)(a.Z,{className:"h-2.5 w-2.5",strokeWidth:2.25}),k.notes]}),eo&&!I&&(0,n.jsx)("textarea",{value:null!==(i=k.notes)&&void 0!==i?i:"",onChange:e=>O(S,k.id,{notes:e.target.value}),placeholder:"Add an internal noteâ¦",rows:2,className:"mt-1 w-full rounded border border-border bg-muted px-2 py-1 text-[11px] text-muted-foreground placeholder:text-muted-foreground/50 resize-none focus:outline-none focus:border-primary"}),k.customerDescription&&!el&&(0,n.jsxs)("span",{className:"flex items-center gap-1.5 text-[11px] italic text-muted-foreground",children:[(0,n.jsx)("span",{className:"inline-flex items-center rounded px-1 py-0.5 text-[9px] font-semibold uppercase tracking-wide bg-amber-100 dark:bg-amber-950/60 text-amber-800 dark:text-amber-200",children:"Customer-visible"}),k.customerDescription]}),el&&!I&&(0,n.jsx)("textarea",{value:null!==(d=k.customerDescription)&&void 0!==d?d:"",onChange:e=>O(S,k.id,{customerDescription:e.target.value}),placeholder:"Add a customer-visible descriptionâ¦",rows:2,className:"mt-1 w-full rounded border border-border bg-muted px-2 py-1 text-[11px] text-muted-foreground placeholder:text-muted-foreground/50 resize-none focus:outline-none focus:border-primary"}),null==U?void 0:U(S,k.id)]})}),(0,n.jsx)("td",{className:"border-r border-border px-2 py-1.5 align-middle focus-within:bg-muted/50",children:I?(0,n.jsx)("span",{className:"block w-full text-right font-mono text-[13px] tabular-nums text-foreground",children:k.qty}):(0,n.jsx)("input",{type:"number","data-brion-line-item-field":"qty",value:k.qty||"",onChange:e=>O(S,k.id,{qty:parseFloat(e.target.value)||0}),onKeyDown:e=>{K(e,S,w,"qty")&&e.preventDefault()},ref:e=>z(S,w,"qty",e),min:0,step:"0.01",className:"w-full bg-transparent text-right font-mono text-[13px] tabular-nums text-foreground focus:outline-none [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"})}),(0,n.jsx)("td",{className:"border-r border-border px-2 py-1.5 align-middle focus-within:bg-muted/50",children:I?(0,n.jsx)("span",{className:"font-mono text-[11px] uppercase tracking-wider text-muted-foreground",children:k.unit}):(0,n.jsx)("select",{value:k.unit,onChange:e=>O(S,k.id,{unit:e.target.value}),onKeyDown:e=>{K(e,S,w,"unit")&&e.preventDefault()},ref:e=>z(S,w,"unit",e),"data-brion-line-item-field":"unit",className:"h-6 w-full rounded border border-transparent bg-transparent px-1 text-[10.5px] font-mono uppercase text-muted-foreground hover:border-border hover:bg-card focus:outline-none focus:border-primary focus:bg-card cursor-pointer",children:(!(N=k.unit)||H.includes(N)?H:[N,...H]).map(e=>(0,n.jsx)("option",{value:e,children:e},e))})}),(0,n.jsx)("td",{className:"border-r border-border px-1.5 py-1.5 align-middle focus-within:bg-muted/50",children:(0,n.jsx)(em,{value:k.cost,onChange:e=>{let t={cost:e};if(E){var r;let n=null!==(r=k.lineItemType)&&void 0!==r?r:"labor",o=E["subcontractor"===n?"subcontract":n];if("number"==typeof o&&o<100){let r=1-o/100;r>0&&(t.unitPrice=Math.round(e/r*100)/100)}}O(S,k.id,t)},readOnly:I})}),(0,n.jsx)("td",{className:"border-r border-border px-2 py-1.5 text-right al
1ign-middle",children:(0,n.jsx)("span",{className:"font-mono text-[12px] tabular-nums text-muted-foreground",children:(0,g.xG)(en)})}),(0,n.jsx)("td",{className:"border-r border-border px-1.5 py-1.5 text-right align-middle",children:(0,n.jsx)(eu,{markupPct:k.cost>0?(k.unitPrice/k.cost-1)*100:0,hasCost:k.cost>0,isLocked:I,onCommit:e=>{if(k.cost>0&&e>=0){let t=Math.round(k.cost*(1+e/100)*100)/100;O(S,k.id,{unitPrice:t})}}})}),(0,n.jsx)("td",{className:"border-r border-border px-1.5 py-1.5 align-middle focus-within:bg-muted/50",children:(0,n.jsx)(em,{value:k.unitPrice,onChange:e=>O(S,k.id,{unitPrice:e}),readOnly:I,brionFieldName:"unitPrice",inputRef:e=>z(S,w,"unitPrice",e),onKeyDown:e=>{K(e,S,w,"unitPrice")&&e.preventDefault()}})}),(0,n.jsx)("td",{className:"border-r border-border px-2 py-1.5 text-right align-middle",children:(0,n.jsx)("span",{className:"font-mono text-[12px] tabular-nums text-muted-foreground",children:(0,g.xG)(X)})}),A.has("costType")&&(0,n.jsx)("td",{className:"border-r border-border px-2 py-1.5 align-middle",children:I?(0,n.jsxs)("span",{className:"inline-flex items-center gap-1.5 rounded-md px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground",children:[(0,n.jsx)("span",{className:"".concat(Y," ").concat(eI.ring),"aria-hidden":"true"}),eI.label]}):(0,n.jsxs)("div",{children:[(0,n.jsxs)("button",{ref:eh,type:"button",title:"Change cost type",onClick:()=>ex(e=>!e),className:"inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-[10px] font-medium leading-none text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring ".concat(ep?"bg-muted text-foreground":""),children:[(0,n.jsx)("span",{className:"".concat(Y," ").concat(eI.ring),"aria-hidden":"true"}),eI.label,(0,n.jsx)(M.Z,{className:"h-2.5 w-2.5 opacity-50",strokeWidth:2.5})]}),ep&&(0,n.jsx)(es,{currentValue:null!==(c=k.lineItemType)&&void 0!==c?c:"labor",onSelect:e=>{O(S,k.id,{lineItemType:e}),ex(!1)},onClose:()=>ex(!1),anchorRef:eh})]})}),A.has("productionRate")&&(0,n.jsx)("td",{className:"border-r border-border px-2 py-1.5 align-middle text-[12px] text-muted-foreground",children:null!==(u=k.productionRateId)&&void 0!==u?u:"â"}),A.has("catalog")&&(0,n.jsx)("td",{className:"border-r border-border px-2 py-1.5 align-middle text-[12px] text-muted-foreground",children:null!==(p=k.materialItemId)&&void 0!==p?p:"â"}),A.has("notes")&&(0,n.jsxs)("td",{className:"border-r border-border px-2 py-1.5 align-middle",children:[(0,n.jsx)("button",{type:"button",onClick:()=>!I&&ea(e=>!e),className:"flex max-w-[150px] items-center gap-1 text-left text-[11px] text-muted-foreground hover:text-primary truncate",title:k.notes||"Add noteâ¦",children:k.notes?(0,n.jsx)("span",{className:"truncate",children:k.notes}):(0,n.jsx)("span",{className:"text-muted-foreground/50",children:"â"})}),eo&&!I&&(0,n.jsx)("textarea",{value:null!==(x=k.notes)&&void 0!==x?x:"",onChange:e=>O(S,k.id,{notes:e.target.value}),placeholder:"Add an internal noteâ¦",rows:2,className:"mt-1 w-full rounded border border-border bg-muted px-2 py-1 text-[11px] text-muted-foreground placeholder:text-muted-foreground/50 resize-none focus:outline-none focus:border-primary"})]}),A.has("optional")&&(0,n.jsx)("td",{className:"border-r border-border px-2 py-1.5 align-middle text-center",children:(0,n.jsx)("input",{type:"checkbox",checked:null!==(b=k.isOptional)&&void 0!==b&&b,onChange:e=>O(S,k.id,{isOptional:e.target.checked}),disabled:I,className:"h-3.5 w-3.5 rounded border-border accent-primary disabled:opacity-50"})}),A.has("taxable")&&(0,n.jsx)("td",{className:"border-r border-border px-2 py-1.5 align-middle text-center",children:(0,n.jsx)("input",{type:"checkbox",checked:null===(h=k.taxable)||void 0===h||h,onChange:e=>O(S,k.id,{taxable:e.target.checked}),disabled:I,className:"h-3.5 w-3.5 rounded border-border accent-primary disabled:opacity-50"})}),A.has("specialOrder")&&(0,n.jsx)("td",{className:"border-r border-border bg-amber-50/60 dark:bg-amber-950/30 px-2 py-1.5 align-middle text-center",children:k.isSpecialOrder?(0,n.jsxs)("span",{className:"inline-flex items-center rounded bg-amber-100 px-1.5 py-0.5 text-[10px] font-semibold text-amber-700 dark:bg-amber-950/50 dark:text-amber-300",children:[(0,n.jsx)(m.Z,{className:"mr-0.5 h-2.5 w-2.5",strokeWidth:2}
1),"Special"]}):(0,n.jsx)("span",{className:"text-[11px] text-muted-foreground",children:"â"})}),A.has("orderStatus")&&(0,n.jsx)("td",{className:"border-r border-border bg-emerald-50/60 dark:bg-emerald-950/30 px-2 py-1.5 align-middle",children:(()=>{var e,t;let r=(e=k.orderStatus)?null!==(t=J[e])&&void 0!==t?t:{label:e,bg:"hsl(var(--muted))",text:"hsl(var(--muted-foreground))"}:null;return r?(0,n.jsx)("span",{className:"inline-flex items-center rounded px-1.5 py-0.5 text-[10px] font-semibold",style:{background:r.bg,color:r.text},children:r.label}):(0,n.jsx)("span",{className:"text-[11px] text-muted-foreground",children:"â"})})()}),A.has("supplier")&&(0,n.jsx)("td",{className:"border-r border-border bg-emerald-50/60 dark:bg-emerald-950/30 px-2 py-1.5 align-middle text-[11.5px] text-muted-foreground",children:k.supplierName?(0,n.jsx)("span",{className:"truncate block max-w-[110px]",title:k.supplierName,children:k.supplierName}):(0,n.jsx)("span",{className:"text-muted-foreground",children:"â"})}),A.has("supplierEta")&&(0,n.jsx)("td",{className:"border-r border-border bg-emerald-50/60 dark:bg-emerald-950/30 px-2 py-1.5 align-middle text-[11.5px] text-muted-foreground",children:k.supplierEta?(0,n.jsx)("span",{className:"font-mono tabular-nums",children:Q(k.supplierEta)}):(0,n.jsx)("span",{className:"text-muted-foreground",children:"â"})}),A.has("customerPromiseDate")&&(0,n.jsx)("td",{className:"border-r border-border bg-emerald-50/60 dark:bg-emerald-950/30 px-2 py-1.5 align-middle text-[11.5px]",children:k.customerPromiseDate?(0,n.jsxs)("span",{className:"font-mono tabular-nums ".concat(F?"text-emerald-700 dark:text-emerald-400 font-semibold":"text-muted-foreground"),children:[Q(k.customerPromiseDate),F&&(0,n.jsx)("span",{className:"ml-1 text-[9px] font-normal text-emerald-600 dark:text-emerald-400",children:"visible"})]}):(0,n.jsx)("span",{className:"text-muted-foreground",children:"â"})}),A.has("orderRef")&&(0,n.jsx)("td",{className:"border-r border-border bg-emerald-50/60 dark:bg-emerald-950/30 px-2 py-1.5 align-middle text-[11.5px] text-muted-foreground",children:k.orderReference?(0,n.jsx)("span",{className:"truncate block max-w-[94px] font-mono",title:k.orderReference,children:k.orderReference}):(0,n.jsx)("span",{className:"text-muted-foreground",children:"â"})}),A.has("bills")&&(0,n.jsx)("td",{className:"border-r border-border px-2 py-1.5 align-middle text-right text-[12px] text-muted-foreground",children:"â"}),A.has("timeCost")&&(0,n.jsx)("td",{className:"border-r border-border px-2 py-1.5 align-middle text-right text-[12px] text-muted-foreground",children:"â"}),A.has("pctComplete")&&(0,n.jsx)("td",{className:"border-r border-border px-2 py-1.5 align-middle text-right text-[12px] text-muted-foreground",children:"â"}),A.has("invoiced")&&(0,n.jsx)("td",{className:"border-r border-border px-2 py-1.5 align-middle text-right text-[12px] text-muted-foreground",children:"â"}),A.has("variance")&&(0,n.jsx)("td",{className:"border-r border-border px-2 py-1.5 align-middle text-right text-[12px] text-muted-foreground",children:"â"}),A.has("finalProfit")&&(0,n.jsx)("td",{className:"border-r border-border px-2 py-1.5 align-middle text-right text-[12px] text-muted-foreground",children:"â"}),(0,n.jsx)("td",{className:"border-r border-border px-2 py-1.5 text-right align-middle",children:I||et<=0?(0,n.jsx)("span",{className:"font-mono text-[13px] font-semibold tabular-nums",style:{color:et>0?ed(er):"#C8BC9C"},children:et>0?"".concat(er.toFixed(1),"%"):"â"}):(0,n.jsx)(ec,{marginPct:er,onCommit:e=>{if(Number.isNaN(e)||e>=100)return;let t=k.cost*k.qty/(1-e/100),r=k.qty>0?t/k.qty:0;O(S,k.id,{unitPrice:Math.round(100*r)/100})}})}),(0,n.jsx)("td",{className:"border-l border-border bg-gradient-to-r from-muted/40 to-card px-3 py-1.5 text-right align-middle",children:(0,n.jsx)("span",{className:"font-mono text-[13px] font-bold tabular-nums text-foreground",children:(0,g.xG)(X)})}),!I&&(0,n.jsx)("td",{className:"sticky right-0 z-[2] pl-1 pr-2 py-1.5 align-middle bg-card border-l border-border group-hover:bg-muted",children:(0,n.jsxs)("div",{className:"flex items-center justify-end gap-0.5",children:[null==W?void 0:W(S,k.id),(0,n.jsx)(_,{ref:ef,isOptional:null!==(f=k.isOptional)&&void 0!==f&&f,taxable:null===(v=k.taxable)||void 0===v||v,recentChanges:eg,notesOpen:eo,hasNotes:!!(null===(t=k.notes)||void 0===t?void 0:t.trim()),onToggleNotes:()=>ea(e=>!e),customerDescOpen:el,hasCustomerDesc:!!(null===(r=k.customerDescription)||void 0===r?void 0:r.trim()),onToggleCustomerDesc:()=>ei(e=>!e),onDuplicate:()=>G(S,k.id),onDelete:()=>Z(S,k.id),onToggleOptional:()=>{var e;O(S,k.id,{isOptional:!(null!==(e=k.isOptional)&&void 0!==e&&e)}),ev(e=>{let t=new Set(e);return t.add("isOptional"),t})},onToggleTaxable:()=>{var e;O(S,k.id,{taxable:!(null===(e=k.taxable)||void 0===e||e)}),ev(e=>{let t=new Set(e);return t.add("taxable"),t})},onApplyToScope:(e,t)=>{null==R||R(S,k.id,e,t)},onOpenCatalog:L?()=>L(S,k.id):void 0,onOfferChoices:!I&&B?()=>B(S,k.id):void 0,optionCount:q})]})})]})}function es(e){let{currentValue:t,onSelect:r,onClose:s,anchorRef:a}
1=e,[l,i]=(0,o.useState)(!1),[d,c]=(0,o.useState)(null);return((0,o.useEffect)(()=>{if(i(!0),a.current){let e=a.current.getBoundingClientRect();c({top:e.bottom+window.scrollY+4,left:e.left+window.scrollX})}},[a]),(0,o.useEffect)(()=>{if(!l)return;let e=()=>{if(!a.current)return;let e=a.current.getBoundingClientRect();c({top:e.bottom+window.scrollY+4,left:e.left+window.scrollX})};return window.addEventListener("resize",e),window.addEventListener("scroll",e,!0),()=>{window.removeEventListener("resize",e),window.removeEventListener("scroll",e,!0)}},[l,a]),l&&"undefined"!=typeof document&&d)?(0,A.createPortal)((0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"fixed inset-0 z-[60]",onClick:s,"aria-hidden":"true"}),(0,n.jsx)("div",{className:"fixed z-[70] w-36 rounded-lg border border-border bg-card p-1 shadow-[0_8px_24px_rgba(28,21,9,0.12)]",style:{top:d.top,left:d.left},children:$.map(e=>(0,n.jsxs)("button",{type:"button",onClick:()=>r(e.value),className:"flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-[12px] hover:bg-muted ".concat(t===e.value?"font-bold":""),children:[(0,n.jsx)("span",{className:"".concat(Y," ").concat(e.ring),"aria-hidden":"true"}),e.label]},e.value))})]}),document.body):null}let ea=[{value:"inherit",label:"Follow document setting",description:"Use the document-level detail preset",icon:(0,n.jsx)(O.Z,{className:"h-3.5 w-3.5",strokeWidth:2})},{value:"expanded",label:"All line amounts",description:"Show all lines + group total",icon:(0,n.jsx)(O.Z,{className:"h-3.5 w-3.5",strokeWidth:2})},{value:"itemsNoPrice",label:"Lines, no amounts",description:"Show lines but hide amounts",icon:(0,n.jsx)(Z.Z,{className:"h-3.5 w-3.5",strokeWidth:2})},{value:"subtotal",label:"Section totals only",description:"Group + sub-group subtotals; no line items shown",icon:(0,n.jsx)(M.Z,{className:"h-3.5 w-3.5",strokeWidth:2})},{value:"summary",label:"Group total only",description:"Collapse group to a single total line",icon:(0,n.jsx)(M.Z,{className:"h-3.5 w-3.5",strokeWidth:2})},{value:"hidden",label:"Hide from customer",description:"Invisible to customer (still in grand total)",icon:(0,n.jsx)(G.Z,{className:"h-3.5 w-3.5",strokeWidth:2})}];function el(e){let{currentMode:t,onSelect:r,onClose:s,anchorRef:a}=e,[l,i]=(0,o.useState)(!1),[d,c]=(0,o.useState)(null);return((0,o.useEffect)(()=>{if(i(!0),a.current){let e=a.current.getBoundingClientRect();c({top:e.bottom+window.scrollY+4,left:e.left+window.scrollX})}},[a]),(0,o.useEffect)(()=>{if(!l)return;let e=()=>{if(!a.current)return;let e=a.current.getBoundingClientRect();c({top:e.bottom+window.scrollY+4,left:e.left+window.scrollX})};return window.addEventListener("resize",e),window.addEventListener("scroll",e,!0),()=>{window.removeEventListener("resize",e),window.removeEventListener("scroll",e,!0)}},[l,a]),l&&"undefined"!=typeof document&&d)?(0,A.createPortal)((0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"fixed inset-0 z-[60]",onClick:s,"aria-hidden":"true"}),(0,n.jsxs)("div",{className:"fixed z-[70] w-56 rounded-lg border border-border bg-card p-1 shadow-[0_8px_24px_rgba(28,21,9,0.12)]",style:{top:d.top,left:d.left},children:[(0,n.jsx)("div",{className:"px-2 py-1.5 text-[10.5px] font-bold uppercase tracking-[0.08em] text-muted-foreground",children:"Customer visibility"}),ea.map(e=>(0,n.jsxs)("button",{type:"button",onClick:()=>r(e.value),className:"flex w-full items-start gap-2.5 rounded px-2 py-2 text-left text-[12px] hover:bg-muted ".concat(t===e.value?"font-bold text-foreground":"text-muted-foreground"),children:[(0,n.jsx)("span",{className:"mt-0.5 flex-shrink-0 text-muted-foreground",children:e.icon}),(0,n.jsxs)("span",{children:[(0,n.jsx)("span",{className:"block",children:e.label}),(0,n.jsx)("span",{className:"block text-[10.5px] text-muted-foreground font-normal",children:e.description})]})]},e.value))]})]}),document.body):null}function ei(e){let{children:t,align:r="left",className:o=""}=e;return(0,n.jsx)("th",{className:"px-3 py-2 text-".concat(r," text-[12px] font-bold uppercase tracking-[0.08em] text-muted-foreground ").concat(o),children:t})}function ed(e){return e>=25?"#3D6442":e>=15?"#F59E0B":"#A84B3D"}function ec(e){let{marginPct:t,onCommit:r}=e,[s,a]=(0,o.useState)(t.toFixed(1)),[l,i]=(0,o.useState)(!1),d=ed(t);return(0,n.jsxs)("div",{className:"flex h-8 items-center justify-end rounded border border-transparent transition-colors focus-within:border-border focus-within:bg-card hover:border-border",children:[(0,n.jsx)("input",{type:"text",inputMode:"decimal","data-brion-line-item-field":"marginPercent",value:l?s:t.toFixed(1),onFocus:()=>{a(t.toFixed(1)),i(!0)},onChange:e=>a(e.target.value),onBlur:()=>{i(!1);let e=parseFloat(s);Number.isNaN(e)||r(e)},onKeyDown:e=>{"Enter"===e.key?e.target.blur():"Escape"===e.key&&(a(t.toFixed(1)),e.target.blur())},className:"h-full w-[64px] bg-transparent pr-1.5 text-right font-mono text-[13px] font-semibold tabular-nums focus:outline-none",style:{color:d}}),(0,n.jsx)("span",{className:"pr-1 text-[12px]",style:{color:d},children:"%"})]})}function eu(e){let{markupPct:t,hasCost:r,isLocked:s,onCommit:a}
1=e,[l,i]=(0,o.useState)(t.toFixed(1)),[d,c]=(0,o.useState)(!1);return r?s?(0,n.jsxs)("span",{className:"block w-full text-right font-mono text-[12px] tabular-nums text-muted-foreground",children:[t.toFixed(1),"%"]}):(0,n.jsxs)("div",{className:"flex h-8 items-center justify-end rounded border border-transparent transition-colors focus-within:border-border focus-within:bg-card hover:border-border",children:[(0,n.jsx)("input",{type:"text",inputMode:"decimal","data-brion-line-item-field":"markupPercent",value:d?l:t.toFixed(1),onFocus:()=>{i(t.toFixed(1)),c(!0)},onChange:e=>i(e.target.value),onBlur:()=>{c(!1);let e=parseFloat(l);!Number.isNaN(e)&&e>=0?a(e):i(t.toFixed(1))},onKeyDown:e=>{"Enter"===e.key?e.target.blur():"Escape"===e.key&&(i(t.toFixed(1)),e.target.blur())},className:"h-full w-[52px] bg-transparent pr-0.5 text-right font-mono text-[12px] tabular-nums text-muted-foreground focus:outline-none"}),(0,n.jsx)("span",{className:"pr-1 text-[11px] text-muted-foreground",children:"%"})]}):(0,n.jsx)("span",{className:"block w-full text-right font-mono text-[12px] tabular-nums text-muted-foreground",children:"â"})}function em(e){let{value:t,onChange:r,readOnly:o,brionFieldName:s,inputRef:a,onKeyDown:l}=e;return o?(0,n.jsx)("span",{className:"block w-full text-right font-mono text-[13px] tabular-nums text-foreground",children:(0,g.xG)(t)}):(0,n.jsxs)("div",{className:"flex h-8 items-center rounded border border-transparent transition-colors focus-within:border-border focus-within:bg-card hover:border-border",children:[(0,n.jsx)("span",{className:"pl-1.5 text-[12px] text-muted-foreground",children:"$"}),(0,n.jsx)("input",{type:"number",step:"0.01",value:t||"",onChange:e=>r(parseFloat(e.target.value)||0),onKeyDown:l,ref:a,...s?{"data-brion-line-item-field":s}:{},className:"h-full w-full bg-transparent pr-1.5 text-right font-mono text-[13px] tabular-nums text-foreground focus:outline-none [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"})]})}},37088:function(e,t,r){r.d(t,{d:function(){return i}});var n=r(27573),o=r(7653),s=r(2966),a=r(85481);let l=[{key:"material",label:"Materials"},{key:"labor",label:"Labor"},{key:"subcontract",label:"Subcontract"},{key:"equipment",label:"Equipment"}];function i(e){let{markupDefaults:t,onMarkupChange:r,disabled:i,readableSummary:d=!1}=e,[c,u]=(0,o.useState)(!1),m=l.map(e=>"".concat(e.label," ").concat(t[e.key],"%")).join(" \xb7 ");return(0,n.jsxs)("div",{className:"rounded-lg border border-border bg-white",children:[(0,n.jsxs)("button",{type:"button",onClick:()=>u(!c),className:"flex w-full items-center justify-between px-4 py-2.5 text-left transition-colors hover:bg-muted",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)(s.Z,{className:"h-4 w-4 text-muted-foreground transition-transform ".concat(c?"rotate-90":""),strokeWidth:2.25}),(0,n.jsx)(a.Z,{className:"h-3.5 w-3.5 text-muted-foreground",strokeWidth:2}),(0,n.jsx)("span",{className:"text-[13px] font-medium text-foreground",children:"Markup defaults for this estimate"}),!c&&(d?(0,n.jsx)("span",{className:"ml-2 font-mono text-[12px] text-muted-foreground tabular-nums",children:m}):(0,n.jsxs)("span",{className:"ml-2 hidden font-mono text-[12px] text-muted-foreground tabular-nums sm:inline",children:["M ",t.material,"% \xb7 L ",t.labor,"% \xb7 S"," ",t.subcontract,"% \xb7 E ",t.equipment,"%"]}))]}),(0,n.jsx)("span",{className:"text-[11px] font-medium uppercase tracking-wider text-muted-foreground",children:d?c?"Hide advanced":"Advanced":c?"Hide":"Show"})]}),c&&(0,n.jsxs)("div",{className:"border-t border-border px-4 py-4",children:[(0,n.jsx)("div",{className:"grid gap-3 sm:grid-cols-4",children:l.map(e=>(0,n.jsxs)("div",{children:[(0,n.jsx)("label",{className:"mb-1 block text-[10.5px] font-bold uppercase tracking-[0.08em] text-muted-foreground",children:e.label}),(0,n.jsxs)("div",{className:"flex h-9 items-center rounded-md border border-border bg-muted",children:[(0,n.jsx)("input",{type:"number",value:t[e.key],disabled:i,onChange:t=>null==r?void 0:r(e.key,parseFloat(t.target.value)||0),className:"h-full flex-1 bg-transparent px-3 text-right font-mono text-[13px] tabular-nums text-foreground focus:outline-none disabled:opacity-60 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),(0,n.jsx)("span",{className:"px-2.5 text-[12px] text-muted-foreground",children:"%"})]}),(0,n.jsx)("p",{className:"mt-1 text-[10.5px] text-muted-foreground",children:"(org default)"})]},e.key))}),(0,n.jsx)("p",{className:"mt-3 text-[11.5px] leading-relaxed text-muted-foreground",children:"Changing a default updates lines that haven't been individually customized. Lines you edited manually keep their values."})]})]})}},42182:function(e,t,r){r.d(t,{U:function(){return x}});var n=r(27573),o=r(7653),s=r(62991),a=r(38677),l=r(81631),i=r(81311);function d(e){let{onClick:t,active:r,disabled:o,title:s,children:a}=e;return(0,n.jsx)("button",{type:"button",onMouseDown:e=>{e.preventDefault(),o||t()},title:s,disabled:o,className:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return t.filter(Boolean).join(" ")}("inline-flex items-center justify-center w-7 h-7 rounded text-xs font-bold transition-colors",r?"bg-primary text-primary-foreground":"text-foreground hover:bg-muted hover:text-primary",o&&"opacity-40 cursor-not-allowed"),children:a})}function c(e){let{editor:t,disabled:r}=e;return(0,n.jsxs)("div",{className:"flex items-center gap-0.5 px-2 py-1.5 border-b border-border bg-muted flex-wrap",children:[(0,n.jsx)(d,{onClick:()=>t.chain().focus().toggleHeading({level:1}).run(),active:t.isActive("heading",{level:1}),disabled:r,title:"Heading 1",children:"H1"}),(0,n.jsx)(d,{onClick:()=>t.chain().focus().toggleHeading({level:2}).run(),active:t.isActive("heading",{level:2}),disabled:r,title:"Heading 2",children:"H2"}),(0,n.jsx)(d,{onClick:()=>t.chain().focus().toggleHeading({level:3}).run(),active:t.isActive("heading",{level:3}),disabled:r,title:"Heading 3",children:"H3"}),(0,n.jsx)("div",{className:"w-px h-5 bg-border mx-1"}),(0,n.jsx)(d,{onClick:()=>t.chain().focus().toggleBold().run(),active:t.isActive("bold"),disabled:r,title:"Bold",children:(0,n.jsx)("span",{style:{fontWeight:800},children:"B"})}),(0,n.jsx)(d,{onClick:()=>t.chain().focus().toggleItalic().run(),active:t.isActive("italic"),disabled:r,title:"Italic",children:(0,n.jsx)("span",{style:{fontStyle:"italic"},children:"I"})}),(0,n.jsx)("div",{className:"w-px h-5 bg-border mx-1"}),(0,n.jsx)(d,{onClick:()=>t.chain().focus().toggleBulletList().run(),active:t.isActive("bulletList"),disabled:r,title:"Bullet List",children:(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:[(0,n.jsx)("line",{x1:"9",y1:"6",x2:"20",y2:"6"}),(0,n.jsx)("line",{x1:"9",y1:"12",x2:"20",y2:"12"}),(0,n.jsx)("line",{x1:"9",y1:"18",x2:"20",y2:"18"}),(0,n.jsx)("circle",{cx:"4",cy:"6",r:"1.5",fill:"currentColor",stroke:"none"}),(0,n.jsx)("circle",{cx:"4",cy:"12",r:"1.5",fill:"currentColor",stroke:"none"}),(0,n.jsx)("circle",{cx:"4",cy:"18",r:"1.5",fill:"currentColor",stroke:"none"})]})}),(0,n.jsx)(d,{onClick:()=>t.chain().focus().toggleOrderedList().run(),active:t.isActive("orderedList"),disabled:r,title:"Numbered List",children:(0,n.jsxs)("svg",{width:"14",height:"14",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2.5",children:[(0,n.jsx)("line",{x1:"10",y1:"6",x2:"20",y2:"6"}),(0,n.jsx)("line",{x1:"10",y1:"12",x2:"20",y2:"12"}),(0,n.jsx)("line",{x1:"10",y1:"18",x2:"20",y2:"18"}),(0,n.jsx)("text",{x:"2",y:"8",fontSize:"7",fill:"currentColor",stroke:"none",fontWeight:"700",children:"1."}),(0,n.jsx)("text",{x:"2",y:"14",fontSize:"7",fill:"currentColor",stroke:"none",fontWeight:"700",children:"2."}),(0,n.jsx)("text",{x:"2",y:"20",fontSize:"7",fill:"currentColor",stroke:"none",fontWeight:"700",children:"3."})]})})]})}let u=null;function m(e){let{kind:t,current:r,onAdd:s}=e,[a,l]=(0,o.useState)([]);(0,o.useEffect)(()=>{let e=!0;return(u||(u=fetch("/api/crm-estimates/frequent-scope-entries",{credentials:"include"}).then(e=>
1e.ok?e.json():null).catch(()=>null)),u).then(r=>{if(!e||!r)return;let n="include"===t?r.includes:r.excludes;l(Array.isArray(n)?n:[])}),()=>{e=!1}},[t]);let i=r.map(e=>e.toLowerCase().trim()),d=a.filter(e=>!i.includes(e.toLowerCase().trim())).slice(0,6);return 0===d.length?null:(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-1.5 mb-2",children:[(0,n.jsx)("span",{className:"text-[10px] font-semibold text-muted-foreground mr-0.5 shrink-0",children:"Frequently used:"}),d.map(e=>(0,n.jsxs)("button",{type:"button",onClick:()=>s(e),title:e,className:["inline-flex items-center gap-1 max-w-[160px] rounded-full border px-2.5 py-0.5","text-[11px] font-medium truncate transition-colors","include"===t?"border-[#2F7D55]/25 bg-[#EBF5EE] text-[#2F7D55] hover:bg-[#D5EDDD] hover:border-[#2F7D55]/40":"border-[#B4602A]/25 bg-[#FBF0E9] text-[#B4602A] hover:bg-[#F5DDD0] hover:border-[#B4602A]/40"].join(" "),children:[(0,n.jsx)("span",{className:"truncate",children:e}),(0,n.jsx)("span",{className:"shrink-0 font-bold text-[10px] opacity-70",children:"+"})]},e))]})}var p=r(17787);function x(e){var t,r,d;let{value:u,onChange:x,specs:b,onSpecsChange:h,includes:f,onIncludesChange:g,excludes:v,onExcludesChange:y,disabled:j=!1}=e,N=(null!==(t=null==b?void 0:b.length)&&void 0!==t?t:0)>0||(null!==(r=null==f?void 0:f.length)&&void 0!==r?r:0)>0||(null!==(d=null==v?void 0:v.length)&&void 0!==d?d:0)>0,[k,w]=(0,o.useState)(!!u||N),C=(0,s.jE)({extensions:[a.Z.configure({blockquote:!1,
1code:!1,codeBlock:!1,horizontalRule:!1,strike:!1}),l.Z.configure({placeholder:"Describe the work to be doneâ¦"}),i.U.configure({html:!1,tightLists:!0,bulletListMarker:"-",breaks:!1,transformCopiedText:!0,transformPastedText:!0})],content:u||"",editable:!j,onUpdate(e){var t,r;let{editor:n}=e,o=n.storage.markdown,s=(null!==(r=null==o?void 0:null===(t=o.getMarkdown)||void 0===t?void 0:t.call(o))&&void 0!==r?r:n.getText()).replace(/\\\r?\n/g,"\n").replace(/^[ \t]+$/gm,"").replace(/(^- .+)\n\n(?=- )/gm,"$1\n").replace(/\n{3,}/g,"\n\n");if(s.length>5e3){p.A.error("Scope of Work is limited to ".concat(5e3.toLocaleString()," characters. Please shorten."));return}s.length>4500&&p.A.warning("Scope of Work is getting long (".concat(s.length.toLocaleString()," / ").concat(5e3.toLocaleString()," chars)."),{id:"scope-char-warn"}),x(s)}},[j]);(0,o.useEffect)(()=>{var e,t;if(!C)return;let r=C.storage.markdown,n=null!==(t=null==r?void 0:null===(e=r.getMarkdown)||void 0===e?void 0:e.call(r))&&void 0!==t?t:C.getText(),o=null!=u?u:"";n!==o&&C.commands.setContent(o)},[u]),(0,o.useEffect)(()=>{(u||N)&&!k&&w(!0)},[u,N,k]);let S=(()=>{var e,t;if(!C)return 0;let r=C.storage.markdown;return(null!==(t=null==r?void 0:null===(e=r.getMarkdown)||void 0===e?void 0:e.call(r))&&void 0!==t?t:C.getText()).length})(),I=(0,o.useCallback)(()=>{j||w(e=>!e)},[j]),A=null!=b?b:[],E=(0,o.useCallback)(()=>{null==h||h([...null!=b?b:[],{label:"",value:""}])},[b,h]),T=(0,o.useCallback)((e,t,r)=>{let n=(null!=b?b:[]).map((n,o)=>o===e?{...n,[t]:r}:n);null==h||h(n)},[b,h]),P=(0,o.useCallback)(e=>{null==h||h((null!=b?b:[]).filter((t,r)=>r!==e))},[b,h]),D=null!=f?f:[],F=null!=v?v:[],O=(0,o.useCallback)(()=>{null==g||g([...null!=f?f:[],""])},[f,g]),M=(0,o.useCallback)((e,t)=>{null==g||g((null!=f?f:[]).map((r,n)=>n===e?t:r))},[f,g]),Z=(0,o.useCallback)(e=>{null==g||g((null!=f?f:[]).filter((t,r)=>r!==e))},[f,g]),G=(0,o.useCallback)(()=>{null==y||y([...null!=v?v:[],""])},[v,y]),L=(0,o.useCallback)((e,t)=>{null==y||y((null!=v?v:[]).map((r,n)=>n===e?t:r))},[v,y]),R=(0,o.useCallback)(e=>{null==y||y((null!=v?v:[]).filter((t,r)=>r!==e))},[v,y]),B=!!(h||g||y);return(0,n.jsxs)("div",{className:"bg-white rounded-2xl border border-border shadow-sm overflow-hidden","data-brion-scope-of-work-format":"markdown",children:[(0,n.jsxs)("div",{className:"px-5 py-3.5 bg-muted border-b border-border flex items-center justify-between",children:[(0,n.jsx)("h2",{className:"text-sm font-bold text-foreground",children:"Scope of Work"}),(0,n.jsxs)("div",{className:"flex items-center gap-3",children:[k&&S>4500&&(0,n.jsxs)("span",{className:function(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return t.filter(Boolean).join(" ")}("text-[11px] font-semibold",S>=5e3?"text-[#DC2626]":"text-primary"),children:[S.toLocaleString(),"â/â",5e3.toLocaleString()]}),!j&&(0,n.jsx)("button",{type:"button",onClick:I,"data-brion-action":"open-scope-of-work",className:"text-[11px] font-semibold text-primary hover:text-primary/80 transition-colors",children:k?"Collapse":u?"Edit":"Add Scope of Work"})]})]}),!k&&u&&(0,n.jsx)("div",{className:"px-5 py-3 text-sm text-foreground leading-relaxed cursor-pointer hover:bg-muted transition-colors",onClick:j?void 0:I,children:(0,n.jsxs)("span",{className:"line-clamp-2 whitespace-pre-wrap",children:[u.replace(/^#{1,3} /gm,"").replace(/\*\*|__|\*|_/g,"").trim().slice(0,140),u.length>140?"â¦":""]})}),k&&(0,n.jsxs)(n.Fragment,{children:[!j&&C&&(0,n.jsx)(c,{editor:C,disabled:j}),(0,n.jsx)("div",{className:"px-0",children:(0,n.jsx)(s.kg,{editor:C,className:"scope-of-work-editor-content"})}),(0,n.jsx)("textarea",{"data-brion-field":"scopeOfWork","aria-hidden":"true",tabIndex:-1,readOnly:!0,value:null!=u?u:"",onChange:()=>{},style:{position:"absolute",opacity:0,pointerEvents:"none",width:1,height:1}}),B&&(0,n.jsxs)("div",{className:"px-5 pt-4 pb-5 border-t border-border space-y-5","data-brion-field":"scopeStructured",children:[h&&(0,n.jsxs)("div",{children:[(0,n.jsxs)("div",{className:"flex items-center justify-between mb-2",children:[(0,n.jsx)("span",{className:"text-[10px] font-bold uppercase tracking-[0.14em] text-muted-foreground",children:"Spec strip"}),!j&&(0,n.jsx)("button",{type:"button",onClick:E,className:"text-[11px] font-semibold text-primary hover:text-primary/80",children:"+ Add spec"})]}),0===A.length?(0,n.jsx)("p",{className:"text-[12px] text-muted-foreground italic",children:"No specs yet â e.g. Product, Sheen, Coats, Prep level."}):(0,n.jsx)("div",{className:"space-y-2",children:A.map((e,t)=>(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)("input",{type:"text",value:e.label,disabled:j,onChange:e=>T(t,"label",e.target.value),placeholder:"Label (e.g. Coats)",className:"flex-1 min-w-0 rounded-lg border border-border bg-white px-2.5 py-1.5 text-[13px] text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring"}),(0,n.jsx)("input",{type:"text",value:e.value,disabled:j,onChange:e=>T(t,"value",e.target.value),placeholder:"Value (e.g. 2 throughout)",className:"flex-1 min-w-0 rounded-lg border border-border bg-white px-2.5 py-1.5 text-[13px] text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring"}),!j&&(0,n.jsx)("button",{type:"button",onClick:()=>P(t),"aria-label":"Remove spec",className:"shrink-0 text-muted-foreground hover:text-[#DC2626] text-lg leading-none px-1",children:"\xd7"})]},t))})]}),(g||y)&&(0,n.jsxs)("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-5",children:[g&&(0,n.jsxs)("div",{children:[(0,n.jsxs)("div",{className:"flex items-center justify-between mb-2",children:[(0,n.jsx)("span",{className:"text-[10px] font-bold uppercase tracking-[0.14em] text-[#2F7D55]",children:"Includes"}),!j&&(0,n.jsx)("button",{type:"button",onClick:O,className:"text-[11px] font-semibold text-primary hover:text-primary/80",children:"+ Add"})]}),!j&&(0,n.jsx)(m,{kind:"include",current:D,onAdd:e=>g([...D,e])}),0===D.length?(0,n.jsx)("p",{className:"text-[12px] text-muted-foreground italic",children:"Nothing listed yet."}):(0,n.jsx)("div",{className:"space-y-2",children:D.map((e,t)=>(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)("span",{className:"text-[#2F7D55] font-bold text-sm leading-none",children:"â"}),(0,n.jsx)("input",{type:"text",value:e,disabled:j,onChange:e=>M(t,e.target.value),placeholder:"What's included",className:"flex-1 min-w-0 rounded-lg border border-border bg-white px-2.5 py-1.5 text-[13px] text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring"}),!j&&(0,n.jsx)("button",{type:"button",onClick:()=>Z(t),"aria-label":"Remove include",className:"shrink-0 text-muted-foreground hover:text-[#DC2626] text-lg leading-none px-1",children:"\xd7"})]},t))})]}),y&&(0,n.jsxs)("div",{children:[(0,n.jsxs)("div",{className:"flex items-center justify-between mb-2",children:[(0,n.jsx)("span",{className:"text-[10px] font-bold uppercase tracking-[0.14em] text-[#B4602A]",children:"Excludes"}),!j&&(0,n.jsx)("button",{type:"button",onClick:G,className:"text-[11px] font-semibold text-primary hover:text-primary/80",children:"+ Add"})]}),!j&&(0,n.jsx)(m,{kind:"exclude",current:F,onAdd:e=>y([...F,e])}),0===F.length?(0,n.jsx)("p",{className:"text-[12px] text-muted-foreground italic",children:"Nothing listed yet."}):(0,n.jsx)("div",{className:"space-y-2",children:F.map((e,t)=>(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)("span",{className:"text-[#B4602A] font-bold text-sm leading-none",children:"â"}),(0,n.jsx)("input",{type:"text",value:e,disabled:j,onChange:e=>L(t,e.target.value),placeholder:"What's excluded",className:"flex-1 min-w-0 rounded-lg border border-border bg-white px-2.5 py-1.5 text-[13px] text-foreground placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring"}),!j&&(0,n.jsx)("button",{type:"button",onClick:()=>R(t),"aria-label":"Remove exclude",className:"shrink-0 text-muted-foreground hover:text-[#DC2626] text-lg leading-none px-1",children:"\xd7"})]},t))})]})]})]})]}),(0,n.jsx)("style",{children:"\n .scope-of-work-editor-content .ProseMirror {\n min-height: 120px;\n padding: 12px 20px;\n outline: none;\n font-size: 14px;\n line-height: 1.7;\n color: hsl(var(--foreground));\n }\n .scope-of-work-editor-content .ProseMirror h1 {\n font-size: 18px; font-weight: 700; margin: 12px 0 6px; color: hsl(var(--foreground));\n }\n .scope-of-work-editor-content .ProseMirror h2 {\n font-size: 15px; font-weight: 700; margin: 10px 0 5px; color: hsl(var(--foreground));\n }\n .scope-of-work-editor-content .ProseMirror h3 {\n font-size: 13px; font-weight: 700; margin: 8px 0 4px; color: hsl(var(--foreground));\n }\n .scope-of-work-editor-content .ProseMirror p { margin: 4px 0; }\n .scope-of-work-editor-content .ProseMirror ul,\n .scope-of-work-editor-content .ProseMirror ol {\n margin: 4px 0; padding-left: 24px;\n }\n .scope-of-work-editor-content .ProseMirror li { margin: 2px 0; }\n .scope-of-work-editor-content .ProseMirror strong { font-weight: 700; }\n .scope-of-work-editor-content .ProseMirror em { font-style: italic; }\n .scope-of-work-editor-content .ProseMirror p.is-editor-empty:first-child::before {\n content: attr(data-placeholder);\n float: left;\n color: hsl(var(--muted-foreground));\n pointer-events: none;\n height: 0;\n }\n .scope-of-work-editor-content .ProseMirror:focus {\n box-shadow: inset 0 0 0 2px hsl(var(--ring) / 0.25);\n }\n "})]})}},66311:function(e,t,r){r.r(t),r.d(t,{CopyFromEstimatePicker:function(){return rl},EstimateDocumentEditor:function(){return ra}});
1var n=r(27573),o=r(7653),s=r(84683),a=r(17787),l=r(25555),i=r(20054),d=r(90743),c=r(54684),u=r(6991),m=r(36673),p=r(24593),x=r(3349),b=r(59622),h=r(97236),f=r(32917),g=r(25159),v=r(69790),y=r(47686),j=r(38333),N=r(75721),k=r(92482),w=r(70548),C=r(48104),S=r(73166),I=r(72750),A=r(3172),E=r(72829),T=r(96631),P=r(88497),D=r(51856),F=r(75771),O=r(18177),M=r(73794),Z=r(10269),G=r(95731),L=r(78356),R=r(4043);let B=["qty","unitPrice","cost"];var q=r(88146),W=r(50466);function _(e){let{estimateId:t,status:r,viewHref:o,onViewEstimate:s}=e,a=(0,R.$6)({status:r}),l=(0,R.G)(t),i=null!=o?o:"/estimates/".concat(t);return(0,n.jsxs)("div",{className:"rounded-lg border border-violet-200 dark:border-violet-700 bg-violet-50 dark:bg-violet-950/40 px-4 py-3 flex flex-col sm:flex-row sm:items-center gap-3",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2.5 flex-1 min-w-0",children:[(0,n.jsx)("div",{className:"w-7 h-7 rounded-full bg-violet-600 dark:bg-violet-500 text-white flex items-center justify-center flex-shrink-0",children:(0,n.jsx)(y.Z,{className:"w-3.5 h-3.5","aria-hidden":"true"})}),(0,n.jsxs)("p",{className:"text-xs text-violet-800 dark:text-violet-300 leading-relaxed",children:[(0,n.jsx)("span",{className:"font-bold",children:a?"Signed":"Locked"})," â this estimate is locked. Changes are documented with a change order."]})]}),(0,n.jsxs)("div",{className:"flex items-center gap-2 flex-shrink-0",children:[(0,n.jsx)(W.z,{asChild:!0,size:"sm",children:(0,n.jsx)(q.default,{href:l,children:"Create change order"})}),s?(0,n.jsx)(W.z,{variant:"outline",size:"sm",onClick:s,children:"View estimate"}):(0,n.jsx)(W.z,{asChild:!0,variant:"outline",size:"sm",children:(0,n.jsx)(q.default,{href:i,children:"View estimate"})})]})]})}var U=r(2966),z=r(6315),K=r(58410);function V(e){let{customerName:t,customerId:r,propertyLabel:s,projectName:a,projectId:l,estimateNumber:i,estimateId:d,siblings:c,currentEstimateId:u,pulseAfterSave:m,onRenameProject:p}=e,x=c.findIndex(e=>e.id===(null!=u?u:d)),b=x>0?c[x-1]:null,h=-1!==x&&x<c.length-1?c[x+1]:null,f=null!=i?i:d?d.slice(-8).toUpperCase():"Estimate",[g,v]=(0,o.useState)(!1),[y,j]=(0,o.useState)(null!=a?a:""),[N,k]=(0,o.useState)(null),w=(0,o.useRef)(null);(0,o.useEffect)(()=>{g||j(null!=a?a:"")},[a,g]);let[C,S]=(0,o.useState)(!1),I=(0,o.useRef)(void 0);(0,o.useEffect)(()=>{if(m&&m!==I.current){I.current=m,S(!0);let e=setTimeout(()=>S(!1),1500);return()=>clearTimeout(e)}},[m]);let A=(0,o.useCallback)(()=>{p&&l&&(j(null!=a?a:""),k(null),v(!0),setTimeout(()=>{var e;return null===(e=w.current)||void 0===e?void 0:e.focus()},0))},[p,l,a]),E=(0,o.useCallback)(async()=>{let e=y.trim();if(!e||e===a){j(null!=a?a:""),v(!1),k(null);return}if(!p){v(!1);return}let t=await p(e);if(t&&"error"in t&&t.error){var r;k(t.error),null===(r=w.current)||void 0===r||r.focus()}else v(!1),k(null)},[y,a,p]),T=(0,o.useCallback)(()=>{j(null!=a?a:""),v(!1),k(null)},[a]),P=(0,o.useCallback)(async e=>{"Enter"===e.key?(e.preventDefault(),await E()):"Escape"===e.key?(e.preventDefault(),T()):"Tab"===e.key&&(e.preventDefault(),await E())},[E,T]),D=(0,o.useCallback)(async()=>{N||await E()},[E,N]),F=l||a?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(U.Z,{className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground",strokeWidth:2.25}),(0,n.jsx)("span",{className:"group/proj flex items-center gap-1 rounded px-1 -mx-1 transition-all duration-300 ".concat(C?"bg-primary/15":""),style:C?{animation:"breadcrumb-pulse 1.5s ease-out forwards"}:void 0,children:g?(0,n.jsxs)("span",{className:"relative flex flex-col",children:[(0,n.jsx)("input",{ref:w,type:"text",value:y,onChange:e=>{j(e.target.value),k(null)},onKeyDown:P,onBlur:D,className:"w-40 rounded border border-primary bg-white px-1.5 py-0.5 text-[13px] font-medium text-foreground focus:outline-none focus:ring-1 focus:ring-ring","aria-label":"Project name"}),N&&(0,n.jsx)("span",{className:"absolute top-full left-0 mt-0.5 whitespace-nowrap rounded bg-white px-1.5 py-0.5 text-[11px] font-medium text-red-600 shadow-sm ring-1 ring-red-200",children:N})]}):(0,n.jsxs)(n.Fragment,{children:[l?(0,n.jsx)("a",{href:"/projects/".concat(l),className:"truncate font-medium text-foreground hover:text-foreground hover:underline decoration-primary decoration-2 underline-offset-4",children:a}):(0,n.jsx)("span",{className:"truncate font-medium text-foreground",children:a}),p&&l&&(0,n.jsx)("button",{type:"button",onClick:A,title:"Rename project",className:"opacity-0 group-hover/proj:opacity-100 transition-opacity focus:opacity-100 rounded p-0.5 text-muted-foreground hover:text-primary",children:(0,n.jsx)(z.Z,{className:"h-3 w-3",strokeWidth:2})})]})})]}):null;return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("style",{children:"\n @keyframes breadcrumb-pulse {\n 0% { background-color: hsl(var(--primary) / 0.30); }\n 60% { background-color: hsl(var(--primary) / 0.15); }\n 100% { background-color: transparent; }\n }\n "}),(0,n.jsx)("div",{className:"sticky top-0 z-30 border-b border-border bg-background/95 backdrop-blur-sm",children:(0,n.jsxs)("div",{className:"flex items-center justify-between px-6 py-2.5 text-[13px]",children:[(0,n.jsxs)("nav",{className:"flex items-center gap-1.5 min-w-0 overflow-visible","aria-label":"Breadcrumb",children:[r&&t?(0,n.jsx)("a",{href:"/customers/".concat(r),className:"truncate font-medium text-foreground hover:text-foreground hover:underline decoration-primary decoration-2 underline-offset-4",children:t}):t?(0,n.jsx)("span",{className:"truncate font-medium text-foreground",children:t}):null,s&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(U.Z,{className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground",strokeWidth:2.25}),(0,n.jsx)("span",{className:"truncate font-medium text-foreground",children:s})]}),F,(0,n.jsx)(U.Z,{className:"h-3.5 w-3.5 flex-shrink-0 text-muted-foreground",strokeWidth:2.25}),(0,n.jsx)("span",{className:"truncate font-mono text-[12.5px] font-semibold text-foreground",children:f})]}),c.length>1&&(0,n.jsxs)("div",{className:"flex items-center gap-1 flex-shrink-0",children:[(0,n.jsxs)("button",{type:"button",disabled:!b,onClick:()=>b&&(window.location.href="/estimates/".concat(b.id,"/edit")),title:b?"Previous: ".concat(b.estimateNumber):"No previous estimate",className:"flex h-7 items-center gap-1 rounded-md px-2 text-[12px] font-medium text-foreground transition-colors hover:bg-muted hover:text-foreground disabled:cursor-not-allowed disabled:opacity-40",children:[(0,n.jsx)(K.Z,{className:"h-3.5 w-3.5",
1strokeWidth:2}),(0,n.jsx)("span",{className:"hidden sm:inline",children:"Prev"})]}),(0,n.jsxs)("span",{className:"px-2 font-mono text-[11.5px] tabular-nums text-muted-foreground",children:["Estimate ",x+1," of ",c.length," in this project"]}),(0,n.jsxs)("button",{type:"button",disabled:!h,onClick:()=>h&&(window.location.href="/estimates/".concat(h.id,"/edit")),title:h?"Next: ".concat(h.estimateNumber):"No next estimate",className:"flex h-7 items-center gap-1 rounded-md px-2 text-[12px] font-medium text-foreground transition-colors hover:bg-muted hover:text-foreground disabled:cursor-not-allowed disabled:opacity-40",children:[(0,n.jsx)("span",{className:"hidden sm:inline",children:"Next"}),(0,n.jsx)(U.Z,{className:"h-3.5 w-3.5",strokeWidth:2})]})]})]})})]})}var H=r(97066),J=r(74737),Q=r(31751),$=r(45782);let Y={draft:"border-[#D4D4D4] bg-[#F5F5F5] text-[#525252]",sent:"border-[#A8C5E5] bg-[#E8F1FA] text-[#1F4E7A]",viewed:"border-[#A8C5E5] bg-[#E8F1FA] text-[#1F4E7A]",approved:"border-[#9BBF9F] bg-[#E8F1E9] text-[#3D6442]",signed:"border-[#9BBF9F] bg-[#E8F1E9] text-[#3D6442]",rejected:"border-[#D4A0A0] bg-[#F8E8E8] text-[#7A2F2F]",converted:"border-primary/30 bg-primary/10 text-primary"};function X(e){let{title:t,status:r,estimateNumber:o,estimateId:s,totalRevenue:a,currentVersion:l,lastRevisionReason:i,isSaving:d,isLocked:c,isCreateMode:y,autosaveState:k,onAutosaveRetry:w,onSend:C,onPreview:S,onConvertToInvoice:I,onGenerateWO:A,onAddTask:E,onMessage:T,onFiles:P,onMore:D,addTaskDisabled:F,messageDisabled:O,filesDisabled:M,moreDisabled:G,onSave:L,onCancel:R,onCreateRevision:B,onUndo:q,canUndo:W=!1,onMoveProject:_}=e,U="approved"===r||"signed"===r,K=null!=o?o:s?"EST-".concat(s.slice(-6).toUpperCase()):null;return(0,n.jsx)("div",{className:"border-b border-border bg-white px-6 py-4",children:(0,n.jsxs)("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between lg:gap-6",children:[(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsxs)("div",{className:"flex items-baseline gap-3 min-w-0",children:[(0,n.jsxs)("h1",{className:"group flex min-w-0 items-center gap-2 font-montserrat text-[22px] font-bold tracking-tight text-foreground",children:[(0,n.jsx)("span",{className:"truncate",children:t||(y?"New Estimate":"Estimate")}),L&&!c&&(0,n.jsx)("button",{type:"button",onClick:L,className:"opacity-0 transition-opacity group-hover:opacity-100",title:"Save estimate",children:(0,n.jsx)(z.Z,{className:"h-3.5 w-3.5 text-muted-foreground",strokeWidth:2})})]}),(0,n.jsx)("span",{className:"flex-shrink-0 rounded-full border px-2.5 py-0.5 text-[11px] font-bold uppercase tracking-wider ".concat(Y[r]),children:r}),!y&&l&&l>1&&(0,n.jsxs)("span",{className:"flex-shrink-0 inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-[#EDE9FE] text-[#7C3AED] text-[10px] font-bold uppercase tracking-wide",title:i?"Latest revision: ".concat(i):"Revised",children:[(0,n.jsx)(x.Z,{className:"w-3 h-3"}),"v",l]})]}),(0,n.jsxs)("div",{className:"mt-1.5 flex items-baseline gap-3 text-[13px] flex-wrap",children:[K&&(0,n.jsx)("span",{className:"font-mono text-foreground",children:K}),(0,n.jsx)("span",{className:"text-muted-foreground",children:"\xb7"}),(0,n.jsx)("span",{className:"text-muted-foreground",children:"Total"}),(0,n.jsx)("span",{className:"font-mono text-[18px] font-bold tabular-nums text-foreground",children:(0,$.xG)(a)}),k&&"idle"!==k.kind&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"text-muted-foreground",children:"\xb7"}),"pending"===k.kind&&(0,n.jsx)("span",{className:"text-[12px] italic text-muted-foreground",children:"Savingâ¦"}),"success"===k.kind&&(0,n.jsxs)("span",{className:"flex items-center gap-1 text-[12px] text-[#3D6442]",children:[(0,n.jsx)(H.Z,{className:"h-3 w-3 flex-shrink-0",strokeWidth:2}
1),"Saved \xb7 ".concat(function(e){let t=Date.now()-e;return t<1e4?"just now":t<6e4?"".concat(Math.floor(t/1e3),"s ago"):t<36e5?"".concat(Math.floor(t/6e4),"m ago"):"".concat(Math.floor(t/36e5),"h ago")}(k.at))]}),"error"===k.kind&&(0,n.jsxs)("span",{className:"flex items-center gap-1 text-[12px] text-[#7A2F2F]",children:["Couldn't save",w&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"text-muted-foreground",children:"\xb7"}),(0,n.jsx)("button",{type:"button",onClick:w,className:"underline underline-offset-2 hover:text-[#DC2626] transition-colors",children:"Retry"})]})]}),"disabled"===k.kind&&(0,n.jsx)("span",{className:"text-[12px] italic text-muted-foreground",children:k.reason})]})]})]}),(0,n.jsxs)("div",{className:"flex flex-shrink-0 items-center gap-1.5 flex-wrap justify-end",children:[C&&!c&&(0,n.jsx)(ee,{icon:J.Z,label:"Send",onClick:C,disabled:d,brionAction:"submit-form"}),c&&B&&(0,n.jsxs)("button",{type:"button",onClick:B,className:"flex h-9 items-center gap-1.5 rounded-md bg-[#7C3AED] hover:bg-[#6D28D9] px-3.5 text-[13px] font-semibold text-white shadow-sm transition-colors",children:[(0,n.jsx)(x.Z,{className:"h-3.5 w-3.5",strokeWidth:2.25}),"Create Revision"]}),L&&!c&&(0,n.jsx)(et,{icon:u.Z,label:y?"Save draft":"draft"===r?"Save":"Save Changes",onClick:L,disabled:d,brionAction:"submit-form"}),S&&(0,n.jsx)(et,{icon:j.Z,label:"Preview",onClick:S}),I&&(0,n.jsx)(et,{icon:m.Z,label:"Convert to Invoice",onClick:I,disabled:!U,title:U?void 0:"Approve or sign the estimate first to convert it to an invoice."}),A&&(0,n.jsx)(et,{icon:p.Z,label:"Generate Work Order",onClick:A,disabled:!U,title:U?void 0:"Approve or sign the estimate first to generate a work order."}),(E||T||P||D)&&(0,n.jsx)("div",{className:"mx-1 h-5 w-px bg-border"}),E&&(0,n.jsx)(er,{icon:h.Z,label:"Add Task",onClick:E,disabled:F}),T&&(0,n.jsx)(er,{icon:f.Z,label:"Message",onClick:T,disabled:O}),P&&(0,n.jsx)(er,{icon:g.Z,label:"Files",onClick:P,disabled:M}),D&&(0,n.jsx)(er,{icon:v.Z,label:"More",onClick:D,disabled:G}),_&&!y&&(0,n.jsx)(er,{icon:Q.Z,label:"Move to project",onClick:_}),q&&!c&&(0,n.jsxs)("button",{type:"button",onClick:q,disabled:!W,title:"Undo last change (Ctrl-Z)",className:"flex h-9 items-center gap-1.5 rounded-md border border-border bg-white px-3 text-[13px] font-medium text-foreground transition-all hover:border-primary hover:bg-muted disabled:opacity-40 disabled:cursor-not-allowed",children:[(0,n.jsx)(b.Z,{className:"h-3.5 w-3.5 text-muted-foreground",strokeWidth:2}),"Undo"]}),R&&(0,n.jsxs)("button",{type:"button",onClick:R,disabled:d,className:"flex h-9 items-center gap-1.5 rounded-md border border-border bg-white px-3 text-[13px] font-medium text-foreground transition-all hover:border-primary hover:bg-muted disabled:opacity-50",children:[(0,n.jsx)(Z.Z,{className:"h-3.5 w-3.5 text-muted-foreground",strokeWidth:2}),"Cancel"]}),d&&(0,n.jsx)(N.Z,{className:"h-4 w-4 animate-spin text-primary"})]})]})})}function ee(e){let{icon:t,label:r,onClick:o,disabled:s,brionAction:a}=e;return(0,n.jsxs)("button",{type:"button",onClick:o,disabled:s,...a?{"data-brion-action":a}:{},className:"flex h-9 items-center gap-1.5 rounded-md bg-primary px-3.5 text-[13px] font-semibold text-primary-foreground shadow-sm transition-colors hover:bg-primary/90 disabled:opacity-50",children:[(0,n.jsx)(t,{className:"h-3.5 w-3.5",strokeWidth:2.25}),r]})}function et(e){let{icon:t,label:r,onClick:o,disabled:s,title:a,brionAction:l}=e;return(0,n.jsxs)("button",{type:"button",onClick:s?void 0:o,disabled:s,title:a,...l?{"data-brion-action":l}:{},className:"flex h-9 items-center gap-1.5 rounded-md border border-border bg-white px-3 text-[13px] font-medium text-foreground transition-all hover:border-primary hover:bg-muted disabled:opacity-50 disabled:cursor-not-allowed",children:[(0,n.jsx)(t,{className:"h-3.5 w-3.5 text-muted-foreground",strokeWidth:2}),r]})}function er(e){let{icon:t,label:r,onClick:o,disabled:s}=e;return(0,n.jsx)("button",{type:"button",title:s?"".concat(r," (coming soon)"):r,onClick:s?void 0:o,disabled:s,"aria-disabled":s||void 0,className:s?"flex h-9 w-9 cursor-not-allowed items-center justify-center rounded-md text-muted-foreground
1/40":"flex h-9 w-9 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:(0,n.jsx)(t,{className:"h-4 w-4",strokeWidth:1.75})})}var en=r(3458),eo=r(38983),es=r(61883),ea=r(94452),el=r(26146),ei=r(48054);function ed(e){let t=[e.firstName,e.lastName].filter(Boolean).join(" ").trim();return e.email||t||"Unnamed contact"}function ec(e){var t;return[e.firstName,e.lastName].filter(Boolean).join(" ").trim()||(null!==(t=e.email)&&void 0!==t?t:"Unnamed contact")}let eu={estimate:{label:"Emailed to",gapLabel:"â add recipient"},billing:{label:"Bills to",gapLabel:"â add billing contact"},approve:{label:"Approved by",gapLabel:"â add approver"}};function em(e,t){var r,n,o,s,a,l,i,d,c,u,m,p,x,b,h,f;return{id:e.id,customerId:null!==(r=e.customerId)&&void 0!==r?r:t,firstName:e.firstName,lastName:e.lastName,title:null!==(n=e.title)&&void 0!==n?n:null,email:null!==(o=e.email)&&void 0!==o?o:null,phone:null!==(s=e.phone)&&void 0!==s?s:null,mobilePhone:null!==(a=e.mobilePhone)&&void 0!==a?a:null,isPrimary:e.isPrimary,isBilling:e.isBilling,canApprove:null!==(l=e.canApprove)&&void 0!==l&&l,receiveInvoices:null!==(d=null!==(i=e.receiveInvoices)&&void 0!==i?i:e.receivesInvoices)&&void 0!==d&&d,receiveScheduling:null!==(u=null!==(c=e.receiveScheduling)&&void 0!==c?c:e.receivesScheduling)&&void 0!==u&&u,receiveEstimates:null!==(p=null!==(m=e.receiveEstimates)&&void 0!==m?m:e.receivesEstimates)&&void 0!==p&&p,receivesInvoices:e.receivesInvoices,receivesScheduling:e.receivesScheduling,receivesEstimates:e.receivesEstimates,canSign:null!==(x=e.canSign)&&void 0!==x&&x,role:null!==(b=e.role)&&void 0!==b?b:"general",communicationPreference:null!==(h=e.communicationPreference)&&void 0!==h?h:"email",createdAt:null!==(f=e.createdAt)&&void 0!==f?f:new Date().toISOString()}}function ep(e){let{contacts:t,customerId:r,customerType:s,onContactsChanged:a}=e,[l,i]=(0,o.useState)(null);if("commercial"!==s)return null;let d=(function(e,t){var r;let n=null!==(r=e.find(e=>e.isPrimary))&&void 0!==r?r:null;if("commercial"!==t)return n?[{kind:"primary",gap:!1,label:ec(n),contactId:n.id}]:[];let o=[],s=e.filter(e=>{var t;return(null!==(t=e.receivesEstimates)&&void 0!==t?t:e.receiveEstimates)===!0}),a=s.length>0?s:n?[n]:[];o.push(a.length>0?{kind:"estimate",gap:!1,label:ed(a[0]),contactId:a[0].id}:{kind:"estimate",gap:!0,label:"No estimate recipient â add"});let l=e.filter(e=>!0===e.isBilling);o.push(l.length>0?{kind:"billing",gap:!1,label:ed(l[0]),contactId:l[0].id}:{kind:"billing",gap:!0,label:"No billing contact â add"});let i=e.filter(e=>!0===e.canApprove);return o.push(i.length>0?{kind:"approve",gap:!1,label:ec(i[0]),contactId:i[0].id}:{kind:"approve",gap:!0,label:"No approver â add"}),o})(t,s).filter(e=>"primary"!==e.kind);if(0===d.length)return null;let c=e=>{if(e.gap||!e.contactId){i({contact:void 0});return}let n=t.find(t=>t.id===e.contactId);i({contact:n?em(n,r):void 0})};return(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("p",{"data-testid":"contact-chain-strip",className:"mt-0.5 text-[13px] leading-relaxed text-foreground",children:d.map((e,t)=>{let r=eu[e.kind];return(0,n.jsxs)("span",{children:[t>0&&(0,n.jsx)("span",{className:"mx-1.5 text-border","aria-hidden":!0,children:"\xb7"}),(0,n.jsxs)("span",{className:"text-muted-foreground",children:[r.label," "]}),(0,n.jsx)("button",{type:"button","data-testid":"contact-chain-fragment-".concat(e.kind),onClick:()=>c(e),className:"font-semibold underline decoration-1 underline-offset-2 ".concat(e.gap?"text-amber-700 decoration-amber-400 hover:decoration-amber-600":"text-foreground decoration-border hover:decoration-foreground"),children:e.gap?r.gapLabel:e.label})]},e.kind)})}),l&&(0,n.jsx)(ei.p,{open:!0,onClose:()=>{i(null),null==a||a()},customerId:r,contact:l.contact})]})}function ex(e){let{roleLabel:t,contact:r,showName:o,onEdit:s}=e,a=r.phone||r.mobilePhone||null,l=r.email||null;return(0,n.jsxs)("span",{className:"inline-flex flex-wrap items-center gap-x-1.5 gap-y-0.5",children:[t&&(0,n.jsx)("span",{className:"text-[10px] font-bold uppercase tracking-wider text-muted-foreground
1/80",children:t}),o&&(0,n.jsx)("span",{className:"font-medium text-foreground",children:ec(r)}),a?(0,n.jsx)("a",{href:"tel:".concat(a),"data-testid":"contact-identity-phone",className:"text-muted-foreground underline decoration-border underline-offset-2 hover:text-foreground hover:decoration-foreground",children:a}):(0,n.jsx)("button",{type:"button","data-testid":"contact-identity-phone-gap",onClick:s,className:"font-semibold text-amber-700 underline decoration-amber-400 underline-offset-2 hover:decoration-amber-600",children:"+ add phone"}),(0,n.jsx)("span",{className:"text-border","aria-hidden":!0,children:"\xb7"}),l?(0,n.jsx)("a",{href:"mailto:".concat(l),"data-testid":"contact-identity-email",className:"text-muted-foreground underline decoration-border underline-offset-2 hover:text-foreground hover:decoration-foreground",children:l}):(0,n.jsx)("button",{type:"button","data-testid":"contact-identity-email-gap",onClick:s,className:"font-semibold text-amber-700 underline decoration-amber-400 underline-offset-2 hover:decoration-amber-600",children:"+ add email"})]})}function eb(e){var t,r,s,a,l;let{contacts:i,customerId:d,customerType:c,property:u,projectManagerContactId:m,onContactsChanged:p}=e,[x,b]=(0,o.useState)(null),h=e=>{b({contact:em(e,d)})};if("commercial"!==c){let e=null!==(r=null!==(t=i.find(e=>e.isPrimary))&&void 0!==t?t:i[0])&&void 0!==r?r:null;return e?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{"data-testid":"contact-identity-line",className:"mt-0.5 text-[13px]",children:(0,n.jsx)(ex,{contact:e,showName:!1,onEdit:()=>h(e)})}),x&&(0,n.jsx)(ei.p,{open:!0,onClose:()=>{b(null),null==p||p()},customerId:d,contact:x.contact})]}):null}let f=null!==(s=i.find(e=>e.isPrimary))&&void 0!==s?s:null,g=m&&null!==(a=i.find(e=>e.id===m))&&void 0!==a?a:null,v=(null==u?void 0:u.supervisorContactId)&&null!==(l=i.find(e=>e.id===u.supervisorContactId))&&void 0!==l?l:null;return f||g||v?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{"data-testid":"contact-identity-line",className:"mt-0.5 flex flex-col gap-0.5 text-[13px]",children:[f&&(0,n.jsx)(ex,{contact:f,showName:!0,onEdit:()=>h(f)}),g&&(0,n.jsx)(ex,{roleLabel:"PM",contact:g,showName:!0,onEdit:()=>h(g)}),v&&(0,n.jsx)(ex,{roleLabel:"Site",contact:v,showName:!0,onEdit:()=>h(v)})]}),x&&(0,n.jsx)(ei.p,{open:!0,onClose:()=>{b(null),null==p||p()},customerId:d,contact:x.contact})]}):null}let eh={standard:"Standard",priority:"Priority",emergency:"Emergency"},ef="Review & send";function eg(e){let{subtotal:t,taxAmount:r,discountValue:s,total:a,readinessLabel:l}=e,[i,d]=(0,o.useState)(!1),c=(0,o.useRef)(null),u=(0,o.useRef)(null),[m,p]=(0,o.useState)(null);return(0,o.useEffect)(()=>{if(i)return e(),window.addEventListener("resize",e),window.addEventListener("scroll",e,!0),()=>{window.removeEventListener("resize",e),window.removeEventListener("scroll",e,!0)};function e(){if(!c.current)return;let e=c.current.getBoundingClientRect(),t=Math.max(8,e.right-224);p({top:e.bottom+6,left:t})}},[i]),(0,o.useEffect)(()=>{if(i)return document.addEventListener("mousedown",e),document.addEventListener("keydown",t),()=>{document.removeEventListener("mousedown",e),document.removeEventListener("keydown",t)};function e(e){c.current&&!c.current.contains(e.target)&&u.current&&!u.current.contains(e.target)&&d(!1)}function t(e){"Escape"===e.key&&d(!1)}},[i]),(0,n.jsxs)("div",{"data-testid":"jobheader-v2-total-block",className:"w-full text-left sm:w-auto sm:flex-shrink-0 sm:text-right",children:[(0,n.jsx)("div",{className:"font-mono text-[22px] font-bold tabular-nums leading-tight text-foreground sm:text-[26px]",children:(0,$.xG)(a)}),(0,n.jsxs)("button",{ref:c,type:"button",onClick:()=>d(e=>!e),"aria-expanded":i,"aria-label":"Estimate total â expand breakdown","data-testid":"jobheader-v2-total-chip",className:"mt-0.5 inline-flex items-center gap-1 text-[12px] text-muted-foreground underline decoration-border underline-offset-2 transition-colors hover:text-foreground hover:decoration-foreground",children:["View breakdown",(0,n.jsx)(eo.Z,{className:"h-3 w-3 transition-transform ".concat(i?"rotate-180":""),strokeWidth:2.25})]}),(0,n.jsx)("div",{className:"mt-2 text-[11.5px] text-muted-foreground",children:l}),i&&m&&"undefined"!=typeof document&&(0,en.createPortal)((0,n.jsx)("div",{ref:u,role:"dialog","aria-label":"Total breakdown","data-testid":"jobheader-v2-total-breakdown",className:"fixed z-[70] w-56 rounded-lg border border-border bg-popover p-3 text-popover-foreground shadow-lg",style:{to
1p:m.top,left:m.left},children:(0,n.jsxs)("dl",{className:"space-y-1.5 text-[12.5px]",children:[(0,n.jsx)(ev,{label:"Subtotal",value:(0,$.xG)(t)}),r>0&&(0,n.jsx)(ev,{label:"Tax",value:"+".concat((0,$.xG)(r))}),s>0&&(0,n.jsx)(ev,{label:"Discount",value:"-".concat((0,$.xG)(s))}),(0,n.jsx)("div",{className:"my-1 border-t border-border"}),(0,n.jsxs)("div",{className:"flex items-baseline justify-between",children:[(0,n.jsx)("dt",{className:"text-[11px] font-bold uppercase tracking-wider text-muted-foreground",children:"Total"}),(0,n.jsx)("dd",{className:"font-mono text-[14px] font-bold tabular-nums text-primary",children:(0,$.xG)(a)})]})]})}),document.body)]})}function ev(e){let{label:t,value:r}=e;return(0,n.jsxs)("div",{className:"flex items-baseline justify-between",children:[(0,n.jsx)("dt",{className:"text-muted-foreground",children:t}),(0,n.jsx)("dd",{className:"font-mono tabular-nums text-foreground",children:r})]})}function ey(e){let{title:t,customerName:r,addressLabel:o,status:s,estimateNumber:a,isCreateMode:l,isSaving:i,isLocked:d,autosaveState:c,onAutosaveRetry:u,urgency:m,onBack:p,onSend:x,onPreview:b,overflowItems:h,subtotal:f,taxAmount:g,discountValue:y,total:k,contacts:w,customerId:C,customerType:S,property:I,projectManagerContactId:A,onContactsChanged:E,remainingRequiredCount:T}=e,P="commercial"===S,D=T&&T>0?"".concat(ef," â ").concat(T," item").concat(T>1?"s":""," remaining"):ef;return(0,n.jsxs)("div",{"data-testid":"jobheader-v2",className:"sticky top-[42px] z-20 border-b border-border bg-white",children:[(0,n.jsxs)("div",{className:"flex flex-col gap-2.5 border-b border-border px-4 py-2.5 sm:flex-row sm:items-center sm:justify-between sm:px-6",children:[(0,n.jsxs)("div",{"data-testid":"jobheader-v2-meta",className:"flex flex-wrap items-center gap-x-2 gap-y-1 text-[12px]",children:[p&&(0,n.jsx)("button",{type:"button",onClick:p,"aria-label":"Back",className:"-ml-1.5 mr-0.5 flex h-7 w-7 flex-shrink-0 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:(0,n.jsx)(es.Z,{className:"h-4 w-4",strokeWidth:2.25})}),a&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"font-mono text-foreground",children:a}),(0,n.jsx)(ej,{})]}),(0,n.jsx)("span",{className:"inline-flex items-center rounded-full border px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider ".concat(Y[s]),children:s}),c&&"idle"!==c.kind&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(ej,{}),"pending"===c.kind&&(0,n.jsx)("span",{className:"italic text-muted-foreground",children:"Savingâ¦"}),"success"===c.kind&&(0,n.jsx)("span",{"data-testid":"jobheader-v2-autosave-label",className:"text-[#3D6442]",children:"Saved ".concat(function(e){let t=Date.now()-e;return t<1e4?"just now":t<6e4?"".concat(Math.floor(t/1e3),"s ago"):t<36e5?"".concat(Math.floor(t/6e4),"m ago"):"".concat(Math.floor(t/36e5),"h ago")}(c.at))}),"error"===c.kind&&(0,n.jsxs)("span",{className:"flex items-center gap-1 text-[#7A2F2F]",children:["Couldn't save",u&&(0,n.jsx)("button",{type:"button",onClick:u,className:"underline underline-offset-2 hover:text-[#DC2626]",children:"Retry"})]}),"disabled"===c.kind&&(0,n.jsx)("span",{className:"italic text-muted-foreground",children:c.reason})]}),(0,n.jsx)(ej,{}),(0,n.jsx)("span",{className:"text-muted-foreground",children:eh[m]})]}),(0,n.jsxs)("div",{className:"flex flex-shrink-0 items-center justify-end gap-1.5",children:[b&&(0,n.jsxs)("button",{type:"button",onClick:b,className:"flex h-9 items-center gap-1.5 rounded-md border border-border bg-white px-3 text-[13px] font-medium text-foreground transition-all hover:border-primary hover:bg-muted",children:[(0,n.jsx)(j.Z,{className:"h-3.5 w-3.5 text-muted-foreground",strokeWidth:2}),(0,n.jsx)("span",{className:"hidden sm:inline",children:"Preview"})]}),x&&!d&&(0,n.jsxs)("button",{type:"button",onClick:x,disabled:i,"data-brion-action":"submit-form",className:"flex h-9 items-center gap-1.5 rounded-md bg-primary px-3.5 text-[13px] font-semibold text-primary-foreground shadow-sm transition-colors hover:bg-primary/90 disabled:opacity-50",children:[(0,n.jsx)(J.Z,{className:"h-3.5 w-3.5",
1strokeWidth:2.25}),"Send"]}),i&&(0,n.jsx)(N.Z,{className:"h-4 w-4 animate-spin text-primary","aria-hidden":!0}),(0,n.jsx)(el.h,{label:"Estimate actions",items:h,trigger:(0,n.jsx)("button",{type:"button","aria-label":"More estimate actions",className:"flex h-9 w-9 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",children:(0,n.jsx)(v.Z,{className:"h-4 w-4",strokeWidth:1.75})})})]})]}),(0,n.jsxs)("div",{"data-testid":"jobheader-v2-identity-row",className:"flex flex-wrap items-start justify-between gap-x-6 gap-y-3 px-4 py-3.5 sm:px-6",children:[(0,n.jsxs)("div",{className:"min-w-0 flex-1 basis-[340px]",children:[(0,n.jsxs)("h1",{"data-testid":"jobheader-v2-title",className:"line-clamp-2 font-montserrat text-[19px] font-bold leading-snug tracking-tight text-foreground sm:text-[21px]",children:[null!=r?r:t,P&&(0,n.jsx)("span",{className:"ml-2 inline-block align-middle rounded-md bg-muted px-1.5 py-0.5 text-[11px] font-bold uppercase tracking-wider text-muted-foreground",children:"Commercial"})]}),o&&(0,n.jsxs)("div",{"data-testid":"jobheader-v2-property-line",className:"mt-1 flex items-center gap-1 text-[13.5px] text-muted-foreground",children:[(0,n.jsx)(ea.Z,{className:"h-3.5 w-3.5 flex-shrink-0",strokeWidth:2}),(0,n.jsx)("span",{className:"truncate",children:o})]}),w&&w.length>0&&C&&(0,n.jsx)(eb,{contacts:w,customerId:C,customerType:S,property:I,projectManagerContactId:A,onContactsChanged:E}),w&&w.length>0&&C&&(0,n.jsx)(ep,{contacts:w,customerId:C,customerType:S,onContactsChanged:E})]}),(0,n.jsx)(eg,{subtotal:f,taxAmount:g,discountValue:y,total:k,readinessLabel:D})]})]})}function ej(){return(0,n.jsx)("span",{className:"text-muted-foreground","aria-hidden":!0,children:"\xb7"})}var eN=r(81695),ek=r(38894),ew=r(23727),eC=r(670),eS=r(41269);let eI=[{id:"estimate",label:"Estimate",icon:ek.Z},{id:"schedule",label:"Schedule",icon:ew.Z},{id:"messages",label:"Messages",icon:f.Z},{id:"files",label:"Files",icon:eC.Z},{id:"photos",label:"Photos",icon:eS.Z},{id:"history",label:"History",icon:l.Z}];function eA(e){let{projectId:t,activeTab:r="estimate",onTabSelect:o}=e,s=(0,eN.useRouter)();return(0,n.jsx)("div",{className:"border-b border-border bg-white px-6",children:(0,n.jsx)("nav",{className:"flex items-center gap-0.5","aria-label":"Project sections",children:eI.map(e=>{let a=e.icon,l=e.id===r,i="estimate"===e.id,d=!i&&!t;return(0,n.jsxs)("button",{type:"button",onClick:()=>{l||d||(o?o(e.id):!i&&t&&s.push("/projects/".concat(t,"?tab=").concat(e.id),{scroll:!1}))},disabled:d,"aria-selected":l,className:"relative flex h-10 items-center gap-2 px-3.5 text-[13px] font-medium transition-colors disabled:cursor-not-allowed disabled:opacity-40 ".concat(l?"text-foreground":"text-foreground hover:text-foreground"),children:[(0,n.jsx)(a,{className:"h-3.5 w-3.5 ".concat(l?"text-primary":"text-muted-foreground"),strokeWidth:2}),(0,n.jsx)("span",{children:e.label}),null!=e.badge&&(0,n.jsx)("span",{className:"ml-0.5 flex h-4 min-w-[16px] items-center justify-center rounded-full bg-primary px-1 text-[10px] font-bold text-primary-foreground",children:e.badge}),l&&(0,n.jsx)("span",{className:"absolute inset-x-0 -bottom-px h-[2px] bg-primary","aria-hidden":"true"})]},e.id)})})})}var eE=r(61569),eT=r(44005);function eP(e){var t;let{customer:r,onChangeCustomer:o}=e;if(!r)return null;let s=null!==(t=r.initials)&&void 0!==t?t:function(e){let t=e.trim().split(/\s+/);return t.length>=2?(t[0][0]+t[t.length-1][0]).toUpperCase():e.slice(0,2).toUpperCase()}(r.displayName);return(0,n.jsx)("div",{className:"rounded-lg border border-border bg-white",children:(0,n.jsxs)("div",{className:"flex items-center gap-3 px-3 py-1.5",children:[(0,n.jsx)("div",{className:"flex h-7 w-7 flex-shrink-0 items-center justify-center rounded-full bg-primary font-mono text-[10.5px] font-bold text-primary-foreground",children:s}),(0,n.jsxs)("div",{className:"flex flex-1 min-w-0 items-center gap-2 text-[12.5px]",children:[(0,n.jsx)("span",{className:"font-semibold text-foreground truncate",children:r.displayName}),r.address&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"text-muted-foreground",children:"\xb7"}),(0,n.jsxs)("span",{className:"flex items-center gap-1 text-muted-foreground min-w-0",children:[(0,n.jsx)(ea.Z,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground",strokeWidth:2}),(0,n.jsx)("span",{className:"truncate",children:r.address})]})]}),r.primaryContact&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("span",{className:"hidden h-4 w-px bg-border md:block"}),(0,n.jsxs)("span",{className:"hidden items-baseline gap-1.5 md:flex",children:[(0,n.jsx)("span",{className:"font-medium text-foreground truncate",children:r.primaryContact.name}),r.primaryContact.title&&(0,n.jsx)("span",{className:"rounded border border-border bg-muted px-1 py-0 text-[9.5px] font-semibold uppercase tracking-wide text-primary",children:r.primaryContact.title})]}),r.primaryContact.email&&(0,n.jsxs)("span",{className:"hidden items-center gap-1 text-muted-foreground lg:flex",children:[(0,n.jsx)(eE.Z,{className:"h-3 w-3 text-muted-foreground",strokeWidth:2}),(0,n.jsx)("span",{className:"truncate",children:r.primaryContact.email})]}),r.primaryContact.phone&&(0,n.jsxs)("span",{className:"hidden items-center gap-1 font-mono text-muted-foreground lg:flex",children:[(0,n.jsx)(eT.Z,{className:"h-3 w-3 text-muted-foreground",strokeWidth:2}),r.primaryContact.phone]}
1)]})]}),o&&(0,n.jsxs)("button",{type:"button",onClick:o,className:"flex h-7 flex-shrink-0 items-center gap-1 rounded-md border border-border bg-white px-2 text-[11.5px] font-medium text-foreground transition-colors hover:border-primary hover:bg-muted hover:text-foreground",children:["Change",(0,n.jsx)(eo.Z,{className:"h-3 w-3",strokeWidth:2})]})]})})}var eD=r(14195);let eF=[{value:"standard",label:"Standard",surcharge:"base rate"},{value:"priority",label:"Priority",surcharge:"+15%"},{value:"emergency",label:"Emergency",surcharge:"+25%"}];function eO(e){let{urgency:t,validDays:r,onUrgencyChange:s,disabled:a}=e,l=(0,o.useMemo)(()=>{let e=new Date;return e.setDate(e.getDate()+r),e.toLocaleDateString(void 0,{month:"short",day:"numeric",year:"numeric"})},[r]);return(0,n.jsx)("div",{className:"rounded-lg border border-border bg-white px-4 py-3",children:(0,n.jsxs)("div",{className:"grid gap-3 md:grid-cols-[2fr_1fr]",children:[(0,n.jsx)(eM,{label:"Urgency",icon:d.Z,children:(0,n.jsx)("div",{className:"flex h-9 items-center gap-1 rounded-md border border-border bg-muted p-0.5",children:eF.map(e=>(0,n.jsxs)("button",{type:"button",disabled:a,onClick:()=>s(e.value),className:"flex h-full flex-1 flex-col items-center justify-center rounded text-[12px] font-medium leading-tight transition-all disabled:opacity-60 ".concat(t===e.value?"bg-white text-foreground shadow-sm":"text-foreground hover:text-foreground"),children:[(0,n.jsx)("span",{children:e.label}),(0,n.jsx)("span",{className:"text-[9.5px] font-semibold uppercase tracking-wider ".concat(t===e.value?"text-primary":"text-muted-foreground"),children:e.surcharge})]},e.value))})}),(0,n.jsx)(eM,{label:"Expires",icon:eD.Z,children:(0,n.jsx)("div",{className:"flex h-9 items-center rounded-md border border-border bg-muted px-3",children:(0,n.jsx)("span",{className:"font-mono text-[13px] tabular-nums text-foreground",children:l})})})]})})}function eM(e){let{label:t,icon:r,children:o}=e;return(0,n.jsxs)("div",{children:[(0,n.jsxs)("label",{className:"mb-1.5 flex items-center gap-1.5 text-[10.5px] font-bold uppercase tracking-[0.08em] text-muted-foreground",children:[(0,n.jsx)(r,{className:"h-3 w-3",strokeWidth:2}),t]}),o]})}var eZ=r(37088),eG=r(42182),eL=r(41169),eR=r(37145),eB=r(76251),eq=r(31095);let eW={material:"Material",labor:"Labor",subcontract:"Subcontract",equipment:"Equipment",subcontractor:"Subcontractor",other:"Other"},e_={material:"border-[#334155] dark:border-[#94A3B8]",labor:"border-primary",subcontract:"border-[#64748B] dark:border-[#E2E8F0]",subcontractor:"border-[#64748B] dark:border-[#E2E8F0]",equipment:"border-[#475569] dark:border-[#CBD5E1]",other:"border-[#94A3B8] dark:border-[#F1F5F9]"},eU={all:"All lines",labor:"Labor only",material:"Material only",subcontract:"Subcontract only",equipment:"Equipment only"};function ez(e){let{totals:t,paymentSchedule:r,customerNotes:o,internalNotes:s,warrantyText:a,onCustomerNotesChange:l,onInternalNotesChange:i,onWarrantyTextChange:d,onEditPaymentSchedule:c,isLocked:u,onApplyTargetMargin:p}=e,x=Object.entries(t.byCostType);return(0,n.jsxs)("aside",{className:"space-y-4",children:[x.some(e=>{let[,t]=e;return t.count>0})&&(0,n.jsx)(eH,{title:"Cost Breakdown",subtitle:"By cost type",children:(0,n.jsx)("ul",{className:"space-y-2",children:x.map(e=>{var t,r;let[o,s]=e;return(0,n.jsxs)("li",{className:"flex items-center gap-2 ".concat(0===s.count?"opacity-40":""),children:[(0,n.jsx)("span",{className:"h-2 w-2 flex-shrink-0 rounded-full border-2 bg-transparent ".concat(null!==(t=e_[o])&&void 0!==t?t:"border-muted-foreground"),"aria-hidden":!0}),(0,n.jsx)("span",{className:"flex-1 text-[12.5px] font-medium text-foreground",children:null!==(r=eW[o])&&void 0!==r?r:o}),(0,n.jsxs)("span",{className:"font-mono text-[11px] tabular-nums text-muted-foreground",children:[s.count," ",1===s.count?"item":"items"]}),(0,n.jsx)("span",{className:"w-20 text-right font-mono text-[12.5px] tabular-nums text-foreground",children:(0,$.xG)(s.cost)})]},o)})})}),(0,n.jsx)(eK,{totals:t,onApplyTargetMargin:u?void 0:p}),null!=t.urgencyPremium&&t.urgencyPremium>0||null!=t.taxAmount&&t.taxAmount>0||null!=t.discountValue&&t.discountValue>0?(0,n.jsx)(eH,{title:"Estimate Total",children:(0,n.jsxs)("dl",{className:"space-y-1.5 text-[12.5px]",children:[null!=t.rawSubtotal&&(0,n.jsx)(eV,{label:"Subtotal",value:(0,$.xG)(t.rawSubtotal)}),null!=t.urgencyPremium&&t.urgencyPremium>0&&(0,n.jsx)(eV,{label:"Urgency premium",value:"+".concat((0,$.xG)(t.urgencyPremium)),accent:"warn"}),null!=t.taxAmount&&t.taxAmount>0&&(0,n.jsx)(eV,{label:"Tax",value:"+".concat((0,$.xG)(t.taxAmount))}),null!=t.discountValue&&t.discountValue>0&&(0,n.jsx)(eV,{label:"Discount",value:"-".concat((0,$.xG)(t.discountValue)),accent:"discount"}),null!=t.total&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{className:"my-1 border-t border-border"}),(0,n.jsxs)("div",{className:"flex items-baseline justify-between",children:[(0,n.jsx)("dt",{className:"text-[11.5px] font-bold uppercase tracking-wider text-muted-foreground",children:"Total"}),(0,n.jsx)("dd",{className:"font-mono text-[16px] font-bold tabular-nums text-primary","data-brion-form-total":String(t.total),children:(0,$.xG)(t.total)})]})]})]})}):null,r&&(0,n.jsxs)(eH,{title:"Payment Schedule",action:c&&!u?(0,n.jsx)(eJ,{title:"Edit payment schedule",onClick:c}):void 0,children:[(0,n.jsxs)("div",{className:"flex items-center gap-2 text-[12.5px]",children:[(0,n.jsx)(eB.Z,{className:"h-3.5 w-3.5 text-primary",strokeWidth:2.25}),(0,n.jsx)("span",{className:"font-medium text-foreground",children:r.summary})]}),r.complianceState&&(0,n.jsx)("p",{className:"mt-1 flex items-center gap-1.5 text-[11px] text-muted-foreground",children:(0,n.jsxs)("span",{className:r.isCompl
1iant?"rounded-full border border-success/30 bg-success/10 px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wider text-success":"rounded-full border border-border bg-muted px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wider text-muted-foreground",children:[r.isCompliant?"â ":"",r.complianceState]})})]}),(0,n.jsx)(eH,{title:"Customer notes",subtitle:"Appears on the estimate sent to customer",icon:(0,n.jsx)(j.Z,{className:"h-3.5 w-3.5 text-muted-foreground",strokeWidth:2}),children:(0,n.jsx)("textarea",{"data-brion-field":"customerNotes",value:o,onChange:e=>l(e.target.value),rows:3,readOnly:u,placeholder:"Notes visible to the customerâ¦",className:"w-full resize-none rounded border border-border bg-muted px-2.5 py-1.5 text-[12.5px] leading-relaxed text-foreground placeholder:text-muted-foreground/60 focus:border-primary focus:bg-white focus:outline-none"})}),d&&(0,n.jsxs)(eH,{title:"Warranty / Terms",subtitle:"Shown at the bottom of the customer copy",icon:(0,n.jsx)(m.Z,{className:"h-3.5 w-3.5 text-muted-foreground",strokeWidth:2}),children:[(0,n.jsx)("textarea",{"data-brion-field":"warrantyText",value:null!=a?a:"",onChange:e=>d(e.target.value||null),rows:4,readOnly:u,placeholder:"e.g. 1-year workmanship warranty. All work performed to local code. Payment due within 30 days of completionâ¦",className:"w-full resize-none rounded border border-border bg-muted px-2.5 py-1.5 text-[12.5px] leading-relaxed text-foreground placeholder:text-muted-foreground/60 focus:border-primary focus:bg-white focus:outline-none"}),(0,n.jsx)("p",{className:"mt-1 text-[10.5px] text-muted-foreground",children:"Visible to customer. Set a default in Organization settings."})]}),(0,n.jsx)(eH,{title:"Internal notes",subtitle:"Only visible to your team",icon:(0,n.jsx)(y.Z,{className:"h-3.5 w-3.5 text-muted-foreground",strokeWidth:2}),muted:!0,children:(0,n.jsx)("textarea",{"data-brion-field":"internalNotes",value:s,onChange:e=>i(e.target.value),rows:3,readOnly:u,placeholder:"Internal notes for your teamâ¦",className:"w-full resize-none rounded border border-border bg-muted/40 px-2.5 py-1.5 text-[12.5px] leading-relaxed text-muted-foreground placeholder:text-muted-foreground/60 focus:border-primary focus:bg-white focus:text-foreground focus:outline-none"})})]})}function eK(e){var t;let{totals:r,onApplyTargetMargin:s}=e,a=r.margin>=25,l=null!==(t=r.rawSubtotal)&&void 0!==t?t:r.revenue,[i,d]=(0,o.useState)(""),[c,u]=(0,o.useState)("all"),[m,p]=(0,o.useState)(!1);return(0,n.jsxs)("div",{className:"overflow-hidden rounded-lg border border-primary/30 bg-gradient-to-br from-background to-white",children:[(0,n.jsxs)("div",{className:"flex items-center justify-between border-b border-border bg-muted/60 px-4 py-2",children:[(0,n.jsx)("h3",{className:"font-montserrat text-[13px] font-bold text-foreground",children:"Margin Summary"}),s&&(0,n.jsxs)("button",{type:"button",title:"Set target margin",onClick:()=>p(e=>!e),"data-brion-action":"set-target-margin",className:"flex items-center gap-1 rounded px-2 py-0.5 text-[10.5px] font-semibold transition-colors ".concat(m?"bg-primary text-primary-foreground":"text-muted-foreground hover:bg-muted hover:text-foreground"),children:[(0,n.jsx)(eq.Z,{className:"h-3 w-3",strokeWidth:2.5}),"Target"]})]}),(0,n.jsxs)("div",{className:"px-4 py-3",children:[(0,n.jsxs)("dl",{className:"space-y-1.5",children:[(0,n.jsx)(eV,{label:"Revenue",value:(0,$.xG)(l)}),(0,n.jsx)(eV,{label:"Cost",value:(0,$.xG)(r.cost),muted:!0}),(0,n.jsx)("div",{className:"my-1.5 border-t border-border"}),(0,n.jsx)(eV,{label:"Profit",value:(0,$.xG)(r.profit),accent:"profit"})]}),(0,n.jsxs)("div",{className:"mt-3 flex items-center justify-between rounded-md border border-border bg-white px-3 py-2",children:[(0,n.jsx)("span",{className:"text-[10.5px] font-bold uppercase tracking-[0.08em] text-muted-foreground",children:"Margin"}),(0,n.jsxs)("span",{className:"font-mono text-[20px] font-bold tabular-nums ".concat(a?"text-[#3D6442]":"text-[#A84B3D]"),children:[r.margin.toFixed(2),"%"]})]}),m&&s&&(0,n.jsxs)("div",{className:"mt-3 rounded-md border border-border bg-muted p-3 space-y-2",children:[(0,n.jsx)("p",{className:"text-[10.5px] font-semibold uppercase tracking-wider text-muted-foreground",children:"Apply target margin"}),(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsxs)("div",{className:"relative flex-1",children:[(0,n.jsx)("input",{type:"number",min:0,max:99,step:.5,value:i,onChange:e=>d(e.target.value),placeholder:r.margin.toFixed(1),"data-brion-field":"targetMarginPct",inputMode:"decimal",className:"w-full rounded border border-border bg-white px-2.5 py-1.5 pr-7 text-[12.5px] tabular-nums text-foreground focus:border-primary focus:outline-none"}),(0,n.jsx)("span",{className:"pointer-events-none absolute right-2 top-1/2 -translate-y-1/2 text-[11px] text-muted-foreground",children:"%"})]}),(0,n.jsx)("button",{type:"button",onClick:()=>
1{if(!s)return;let e=parseFloat(i);isNaN(e)||e<0||e>99||(s(e,c),p(!1),d(""))},disabled:!i||isNaN(parseFloat(i)),"data-brion-action":"apply-target-margin",className:"rounded bg-primary px-3 py-1.5 text-[11.5px] font-bold text-primary-foreground transition-colors hover:bg-primary/80 disabled:opacity-40",children:"Apply"})]}),(0,n.jsx)("select",{value:c,onChange:e=>u(e.target.value),"data-brion-field":"targetMarginFilter",className:"w-full rounded border border-border bg-white px-2.5 py-1.5 text-[12px] text-foreground focus:border-primary focus:outline-none",children:Object.entries(eU).map(e=>{let[t,r]=e;return(0,n.jsx)("option",{value:t,children:r},t)})}),(0,n.jsx)("p",{className:"text-[10px] leading-relaxed text-muted-foreground",children:"Recomputes unit price on lines with a known cost to hit the target. Lines with no cost entered are skipped."})]})]})]})}function eV(e){let{label:t,value:r,muted:o,accent:s}=e;return(0,n.jsxs)("div",{className:"flex items-baseline justify-between",children:[(0,n.jsx)("dt",{className:"text-[11.5px] font-medium ".concat("text-muted-foreground"),children:t}),(0,n.jsx)("dd",{className:"font-mono text-[13.5px] tabular-nums ".concat("profit"===s?"font-bold text-[#3D6442]":"warn"===s?"font-semibold text-primary":"discount"===s?"font-semibold text-[#DC2626]":o?"text-muted-foreground":"font-semibold text-foreground"),children:r})]})}function eH(e){let{title:t,subtitle:r,icon:o,children:s,action:a,muted:l}=e;return(0,n.jsxs)("div",{className:"rounded-lg border border-border ".concat(l?"bg-muted/60":"bg-white"),children:[(0,n.jsxs)("div",{className:"flex items-center justify-between border-b border-border px-4 py-2",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2 min-w-0",children:[o,(0,n.jsxs)("div",{className:"min-w-0",children:[(0,n.jsx)("h3",{className:"font-montserrat text-[12.5px] font-bold text-foreground",children:t}),r&&(0,n.jsx)("p",{className:"truncate text-[10.5px] text-muted-foreground",children:r})]})]}),a]}),(0,n.jsx)("div",{className:"px-4 py-3",children:s})]})}function eJ(e){let{title:t,onClick:r}=e;return(0,n.jsx)("button",{type:"button",title:t,onClick:r,className:"flex h-6 w-6 items-center justify-center rounded text-muted-foreground hover:bg-muted hover:text-foreground",children:(0,n.jsx)(z.Z,{className:"h-3 w-3",strokeWidth:2})})}var eQ=r(34965),e$=r(15671);function eY(e){let{text:t}=e;return t?(0,n.jsx)("span",{className:"inline-flex px-1.5 py-0.5 rounded-md bg-muted text-muted-foreground text-[9px] font-semibold uppercase tracking-wide leading-none",children:t}):null}function eX(e){let{title:t,count:r,children:s}=e,[a,l]=(0,o.useState)(!0);return 0===r?null:(0,n.jsxs)("div",{children:[(0,n.jsxs)("button",{type:"button",onClick:()=>l(e=>!e),className:"w-full flex items-center justify-between px-3 py-1.5 bg-muted text-[10px] font-bold uppercase tracking-wider text-foreground hover:bg-muted transition-colors",children:[(0,n.jsxs)("span",{children:[t," ",(0,n.jsxs)("span",{className:"font-normal text-muted-foreground",children:["(",r,")"]})]}),a?(0,n.jsx)(eQ.Z,{className:"w-3 h-3"}):(0,n.jsx)(eo.Z,{className:"w-3 h-3"})]}),a&&(0,n.jsx)("div",{className:"divide-y divide-border",children:s})]})}function e0(e){let{orgId:t,onSelect:r,onClose:s,anchorRef:l}=e,[i,d]=(0,o.useState)(""),[c,u]=(0,o.useState)({materials:[],labor:[],assemblies:[]}),[m,p]=(0,o.useState)(!1),[x,b]=(0,o.useState)(!1),[h,f]=(0,o.useState)(null),g=(0,o.useRef)(null),v=(0,o.useRef)(null),y=(0,o.useRef)(null);(0,o.useEffect)(()=>{var e;null===(e=g.current)||void 0===e||e.focus()},[]),(0,o.useEffect)(()=>{let e=e=>{"Escape"===e.key&&s()};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[s]),(0,o.useEffect)(()=>{let e=e=>{var t;!v.current||v.current.contains(e.target)||(null==l?void 0:null===(t=l.current)||void 0===t?void 0:t.contains(e.target))||s()};return document.addEventListener("pointerdown",e),()=>document.removeEventListener("pointerdown",e)},[s,l]);let j=(0,o.useCallback)(e=>{let t=e.trim();if(!t){u({materials:[],labor:[],assemblies:[]}),b(!1),p(!1),f(null);return}p(!0),f(null);let r=encodeURIComponent(t),n=async e=>{try{let t=await fetch(e,{credentials:"include"});if(!t.ok)return{ok:!1,status:t.status};let r=await t.json();return{ok:!0,data:r}}catch(e){return{ok:!1,status:0}}};Promise.all([n("/api/materials?search=".concat(r,"&active=true&onlyActiveTrades=true")),e$.xf?n("/api/production-rates?search=".concat(r,"&active=true&onlyActiveTrades=true")):Promise.resolve({ok:!0,data:{productionRates:[]}}),e$.xf?n("/api/assemblies?search=".concat(r,"&active=true")):Promise.resolve({ok:!0,data:{assemblies:[]}})]).then(e=>{let[t,r,n]=e;if(!t.ok||!r.ok||!n.ok){let e=t.ok?r.ok?n.ok?0:n.status:r.status:t.status;u({materials:[],labor:[],assemblies:[]}),f("Catalog search failed â ".concat(e||"network error")),b(!0);return}let o=t.data,s=r.data,a=n.data;u({materials:o.materials||o.data||[],labor:s.productionRates||s.data||[],assemblies:a.assemblies||a.data||[]}),b(!0)}).catch(e=>{console.error("Catalog search failed:",e),u({materials:[],labor:[],assemblies:[]}),f("Catalog search failed â network error"),b(!0)}).finally(()=>{p(!1)})},[]),N=e=>{r({source:"material",id:e.id,description:e.name,unit:e.unit||"each",unitPrice:e.defaultCostCents>0?e.defaultCostCents/100:0,lineItemType:"material",materialItemId:e.id}),s()},k=async e=>{var t,n;let o=null!==(t=e.minutesPerUnit)&&void 0!==t?t:0,l=0;if(o>0&&e.trade)try{let t=await fetch("/api/trade-rates/".concat(encodeURIComponent(e.trade)),{credentials:"include"});if(t.ok){let r=await t.json(),s=null===(n=r.tradeRate)||void 0===n?void 0:n.sellRateCents;s&&s>0?l=Math.round(o/60*(s/100)*100)/100:a.A.warning('No sell rate configured for trade "'.concat(e.trade,'". Set it in Settings â Pricing â Trade Rates.'))}else 404===t.status&&a.A.warning('No trade rate found for "'.concat(e.trade,'". Configure it in Settings â Pricing â Trade Rates.'))}catch(e){a.A.warning("Could not fetch trade rate. The line item will be added at $0.00 â edit before sending.")}else o>0&&!e.trade&&a.A.warning("This labor item has no trade assigned. Set a trade rate to get an accurate price.");r({source:"labor",id:e.id,description:e.taskName,unit:e.unit||"hr",unitPrice:l,lineItemType:"labor",productionRateId:e.id}),s()},w=e=>{r({source:"assembly",id:e.id,description:e.name,unit:"job",unitPrice:e.basePrice||0,lineItemType:"other"}),s()},C=c.materials.length+c.labor.length+c.assemblies.length;return(0,n.jsxs)("div",{ref:v,className:"z-50 w-full sm:w-96 bg-white rounded-2xl border border-border shadow-xl overflow-hidden flex flex-col",style:{maxHeight:"calc(100vh - 120px)",fontFamily:"'Montserrat', system-ui, sans-serif"},children:[(0,n.jsxs)("div",{className:"flex items-center gap-2 px-3 py-2.5 border-b border-border bg-muted",children:[(0,n.jsx)(E.Z,{className:"w-4 h-4 text-primary flex-shrink-0"}),(0,n.jsx)("span",{className:"text-xs font-bold text-foreground flex-1 uppercase tracking-wider",children:"Catalog Search"}),(0,n.jsx)("button",{type:"button",onClick:s,className:"p-1 rounded-md text-muted-foreground hover:text-foreground hover:bg-muted transition-colors",children:(0,n.jsx)(Z.Z,{className:"w-3.5 h-3.5"})})]}),(0,n.jsx)("div",{className:"px-3 py-2 border-b border-border",children:(0,n.jsxs)("div",{className:"relative",children:[(0,n.jsx)(G.Z,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-muted-foreground pointer-events-none"}),(0,n.jsx)("input",{ref:g,type:"text",value:i,onChange:e=>{let t=e.target.value;d(t),y.current&&clearTimeout(y.current),y.current=setTimeout(()=>j(t),250)},placeholder:"Search materials, labor, assemblies...",className:"w-full rounded-lg border border-border bg-white pl-8 pr-3 py-2 text-sm text-foreground placeholder:text-muted-foreground
1/60 focus:outline-none focus:ring-2 focus:ring-ring/40 focus:border-primary transition-all"})]})}),(0,n.jsxs)("div",{className:"flex-1 overflow-y-auto",children:[m&&(0,n.jsx)("div",{className:"px-3 py-6 text-center text-xs text-muted-foreground",children:"Searching..."}),!m&&h&&(0,n.jsx)("div",{className:"px-3 py-6 text-center text-xs text-destructive",children:h}),!m&&!h&&x&&0===C&&(0,n.jsxs)("div",{className:"px-3 py-6 text-center text-xs text-muted-foreground",children:["No results for â",i,"â"]}),!m&&!h&&!x&&(0,n.jsx)("div",{className:"px-3 py-6 text-center text-xs text-muted-foreground",children:"Type to search the catalog"}),!m&&C>0&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(eX,{title:"Materials",count:c.materials.length,children:c.materials.map(e=>(0,n.jsxs)("button",{type:"button",onClick:()=>N(e),className:"w-full text-left px-3 py-2.5 hover:bg-muted transition-colors flex items-center justify-between gap-2 group",children:[(0,n.jsxs)("div",{className:"flex flex-col gap-0.5 min-w-0",children:[(0,n.jsx)("span",{className:"text-sm text-foreground font-medium leading-snug truncate",children:e.name}),(0,n.jsxs)("div",{className:"flex items-center gap-1 flex-wrap",children:[e.trade&&(0,n.jsx)(eY,{text:e.trade}),e.category&&(0,n.jsx)(eY,{text:e.category})]})]}),(0,n.jsx)("span",{className:"text-xs font-semibold text-primary flex-shrink-0 whitespace-nowrap",children:e.defaultCostCents>0?"".concat((e.defaultCostCents/100).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2})," / ").concat(e.unit||"each"):"per ".concat(e.unit||"each")})]},e.id))}),e$.xf&&(0,n.jsx)(eX,{title:"Labor",count:c.labor.length,children:c.labor.map(e=>(0,n.jsxs)("button",{type:"button",onClick:()=>k(e),className:"w-full text-left px-3 py-2.5 hover:bg-muted transition-colors flex items-center justify-between gap-2 group",children:[(0,n.jsxs)("div",{className:"flex flex-col gap-0.5 min-w-0",children:[(0,n.jsx)("span",{className:"text-sm text-foreground font-medium leading-snug truncate",children:e.taskName}),(0,n.jsxs)("div",{className:"flex items-center gap-1 flex-wrap",children:[e.trade&&(0,n.jsx)(eY,{text:e.trade}),e.category&&(0,n.jsx)(eY,{text:e.category})]})]}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground flex-shrink-0 whitespace-nowrap",children:e.minutesPerUnit?"".concat(e.minutesPerUnit," min / ").concat(e.unit||"unit"):"per ".concat(e.unit||"unit")})]},e.id))}),e$.xf&&(0,n.jsx)(eX,{title:"Assemblies",count:c.assemblies.length,children:c.assemblies.map(e=>(0,n.jsxs)("button",{type:"button",onClick:()=>w(e),className:"w-full text-left px-3 py-2.5 hover:bg-muted transition-colors flex items-center justify-between gap-2 group",children:[(0,n.jsxs)("div",{className:"flex flex-col gap-0.5 min-w-0",children:[(0,n.jsx)("span",{className:"text-sm text-foreground font-medium leading-snug truncate",children:e.name}),(0,n.jsxs)("div",{className:"flex items-center gap-1 flex-wrap",children:[e.trade&&(0,n.jsx)(eY,{text:e.trade}),e.category&&(0,n.jsx)(eY,{text:e.category}),e.description&&(0,n.jsx)("span",{className:"text-[9px] text-muted-foreground truncate max-w-[140px]",children:e.description})]})]}),(0,n.jsx)("span",{className:"text-xs font-semibold text-primary flex-shrink-0 whitespace-nowrap",children:e.basePrice&&e.basePrice>0?e.basePrice.toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:2}):"price TBD"})]},e.id))})]})]})]})}var e1=r(37040),e5=r(52893),e2=r(29324),e3=r(39134),e4=r(5364);async function e6(e){try{var t,r;let n=await fetch("/api/trade-rates/".concat(encodeURIComponent(e)),{credentials:"include"});if(!n.ok)return null;let o=await n.json();return null!==(r=null===(t=o.tradeRate)||void 0===t?void 0:t.sellRateCents)&&void 0!==r?r:null}catch(e){return null}}async function e9(e,t,r){var n,o,s,a;let l=await fetch("/api/assemblies/".concat(e.id),{credentials:"include"});if(!l.ok)return null;let i=null!==(o=null===(n=(await l.json()).assembly)||void 0===n?void 0:n.lineItems)&&void 0!==o?o:[],d=null!==(s=e.trade)&&void 0!==s?s:null,c=null;d&&(r.has(d)||r.set(d,await e6(d)),c=null!==(a=r.get(d))&&void 0!==a?a:null);let u=i.map((e,t)=>{var r;return{description:e.description,quantity:null!==(r=e.quantity)&&void 0!==r?r:1,unit:e.unit||"each",unitPrice:function(e,t){var r,n;if(null!=e.costCents)return e.costCents/100;let o=null!==(r=e.quantity)&&void 0!==r?r:1;return(null!==(n=e.minutesPerUnit)&&void 0!==n?n:0)>0&&null!=t&&t>0?Math.round(e.minutesPerUnit/60*o*(t/100)*100)/100:0}(e,c),category:e.lineItemType,sortOrder:t}});return 0===u.length&&u.push({description:e.name,quantity:1,unit:"ea",unitPrice:0,sortOrder:0}),{name:e.name,sortOrder:t,items:u}}function e8(e){var t,r,s,a,l,i;let{assembly:d,selected:c,onToggle:u}=e,[m,p]=(0,o.useState)(!1),x=null!==(s=null!==(r=d.lineItemCount)&&void 0!==r?r:null===(t=d.lineItems)||void 0===t?void 0:t.length)&&void 0!==s?s:0;return(0,n.jsxs)("div",{className:"rounded-lg border transition-colors ".concat(c?"border-primary bg-muted":"border-border bg-white"),children:[(0,n.jsxs)("div",{className:"flex items-start gap-3 p-4",children:[(0,n.jsx)("button",{type:"button",onClick:()=>u(d.id),className:"mt-0.5 shrink-0 text-primary hover:opacity-75 transition-opacity","aria-label":c?"Deselect assembly":"Select assembly",children:c?(0,n.jsx)(h.Z,{className:"h-5 w-5"}):(0,n.jsx)(e5.Z,{className:"h-5 w-5 text-muted-foreground"})}),(0,n.jsx)("div",{className:"mt-0.5 shrink-0 rounded-md bg-muted border border-border p-1.5",children:(0,n.jsx)(E.Z,{className:"h-4 w-4 text-primary"})}),(0,n.jsxs)("div",{className:"min-w-0 flex-1",children:[(0,n.jsx)("p",{className:"font-semibold text-foreground text-sm font-['Montserrat']",children:d.name}),d.description&&(0,n.jsx)("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-2 font-['Inter']",children:d.description}),(0,n.jsxs)("div",{className:"flex items-center gap-3 mt-1.5",children:[d.category&&(0,n.jsx)("span",{className:"inline-flex items-center rounded-full bg-muted px-2 py-0.5 text-[10px] font-medium text-muted-foreground font-['Inter']",children:d.category}),(0,n.jsxs)("span",{className:"text-xs text-muted-foreground font-['Inter']",children:[x," ",1===x?"item":"items"]})]})]}),(null!==(a=d.lineItems)&&void 0!==a?a:[]).length>0&&(0,n.jsx)("button",{type:"button",onClick:()=>p(e=>!e),className:"shrink-0 text-muted-foreground hover:text-foreground transition-colors p-1","aria-label":m?"Collapse line items":"Expand line items",children:m?(0,n.jsx)(eQ.Z,{className:"h-4 w-4"}):(0,n.jsx)(eo.Z,{className:"h-4 w-4"})})]}),m&&(null!==(l=d.lineItems)&&void 0!==l?l:[]).length>0&&(0,n.jsxs)("div",{className:"border-t border-border px-4 pb-3 pt-2",children:[(0,n.jsx)("p",{className:"text-[10px] font-semibold uppercase tracking-wide text-muted-foreground mb-2 font-['Montserrat']",children:"Line items"}),(0,n.jsx)("div",{className:"space-y-1",children:(null!==(i=d.lineItems)&&void 0!==i?i:[]).map((e,t)=>{var r;return(0,n.jsxs)("div",{className:"flex items-center justify-between text-xs text-foreground font-['Inter']",children:[(0,n.jsx)("span",{className:"flex-1 min-w-0 truncate",children:e.description}),(0,n.jsxs)("span",{className:"ml-3 shrink-0 text-muted-foreground",children:[e.quantity," ",e.unit]})]},null!==(r=e.id)&&void 0!==r?r:t)})})]})]})}function e7(e){var t;let{open:r,onClose:s,onInsert:a}
1=e,[l,i]=(0,o.useState)(""),[d,c]=(0,o.useState)("all"),[u,m]=(0,o.useState)(new Set),[p,x]=(0,o.useState)(!1),{data:b,isLoading:h,isError:f}=(0,e4.lx)(),g=null!==(t=null==b?void 0:b.assemblies)&&void 0!==t?t:[],v=(0,o.useMemo)(()=>Array.from(new Set(g.map(e=>e.category).filter(e=>!!e))).sort(),[g]),y=(0,o.useMemo)(()=>{let e=l.trim().toLowerCase();return g.filter(t=>{var r;return!!(("all"===d||t.category===d)&&(!e||t.name.toLowerCase().includes(e)||(null!==(r=t.description)&&void 0!==r?r:"").toLowerCase().includes(e)))})},[g,l,d]);function j(e){m(t=>{let r=new Set(t);return r.has(e)?r.delete(e):r.add(e),r})}async function k(){let e=y.filter(e=>u.has(e.id));if(0!==e.length){x(!0);try{let t=new Map,r=[];for(let n=0;n<e.length;n++){let o=await e9(e[n],n,t);o&&r.push(o)}if(0===r.length)return;a(r),m(new Set),i(""),c("all"),s()}finally{x(!1)}}}function w(){m(new Set),i(""),c("all"),s()}let C=u.size;return(0,n.jsx)(e2.Vq,{open:r,onOpenChange:e=>{e||w()},children:(0,n.jsxs)(e2.cZ,{className:"max-w-2xl w-full max-h-[85vh] flex flex-col p-0 gap-0 bg-background border-border rounded-xl overflow-hidden",style:{fontFamily:"Inter, sans-serif"},children:[(0,n.jsxs)(e2.fK,{className:"px-6 pt-6 pb-4 border-b border-border shrink-0",children:[(0,n.jsx)(e2.$N,{className:"text-xl font-bold text-foreground",style:{fontFamily:"Montserrat, sans-serif"},children:"Insert from Pricebook"}),(0,n.jsx)("p",{className:"text-sm text-muted-foreground mt-1",children:"Select one or more assemblies to insert as line groups into the estimate."})]}),(0,n.jsxs)("div",{className:"px-6 py-4 border-b border-border shrink-0 space-y-3",children:[(0,n.jsxs)("div",{className:"relative",children:[(0,n.jsx)(G.Z,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),(0,n.jsx)(e3.I,{placeholder:"Search assembliesâ¦",value:l,onChange:e=>i(e.target.value),className:"pl-9 bg-white border-border text-foreground placeholder:text-muted-foreground focus-visible:ring-ring focus-visible:border-primary"})]}),v.length>0&&(0,n.jsxs)("div",{className:"flex flex-wrap gap-2",children:[(0,n.jsx)("button",{type:"button",onClick:()=>c("all"),className:"rounded-full px-3 py-1 text-xs font-medium transition-colors ".concat("all"===d?"bg-primary text-primary-foreground":"bg-white border border-border text-muted-foreground hover:border-primary hover:text-primary"),style:{fontFamily:"Montserrat, sans-serif"},children:"All"}),v.map(e=>(0,n.jsx)("button",{type:"button",onClick:()=>c(e),className:"rounded-full px-3 py-1 text-xs font-medium transition-colors ".concat(d===e?"bg-primary text-primary-foreground":"bg-white border border-border text-muted-foreground hover:border-primary hover:text-primary"),style:{fontFamily:"Montserrat, sans-serif"},children:e},e))]})]}),(0,n.jsxs)("div",{className:"flex-1 overflow-y-auto px-6 py-4 min-h-0",children:[h&&(0,n.jsxs)("div",{className:"flex items-center justify-center py-16 text-muted-foreground",children:[(0,n.jsx)(N.Z,{className:"h-6 w-6 animate-spin mr-2"}),(0,n.jsx)("span",{className:"text-sm",children:"Loading pricebookâ¦"})]}),f&&(0,n.jsxs)("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[(0,n.jsx)("p",{className:"text-sm font-medium text-[#E05A2B]",children:"Failed to load assemblies."}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground mt-1",children:"Check your connection and try again."})]}),!h&&!f&&0===y.length&&(0,n.jsxs)("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[(0,n.jsx)(E.Z,{className:"h-10 w-10 text-muted-foreground mb-3"}),0===g.length?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("p",{className:"text-sm font-semibold text-foreground",style:{fontFamily:"Montserrat, sans-serif"},children:"No assemblies yet"}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground mt-1",children:"Add assemblies to your pricebook to use them here."})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("p",{className:"text-sm font-semibold text-foreground",style:{fontFamily:"Montserrat, sans-serif"},children:"No results"}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground mt-1",children:"Try a different search or category."})]})]}),!h&&!f&&y.length>0&&(0,n.jsx)("div",{className:"space-y-3",children:y.map(e=>(0,n.jsx)(e8,{assembly:e,selected:u.has(e.id),onToggle:j},e.id))})]}),(0,n.jsxs)("div",{className:"px-6 py-4 border-t border-border shrink-0 flex items-center justify-between bg-white",children:[(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:0===C?"No assemblies selected":"".concat(C," ").concat(1===C?"assembly":"assemblies"," selected")}),(0,n.jsxs)("div",{className:"flex gap-3",children:[(0,n.jsx)(W.z,{type:"button",variant:"outline",onClick:w,className:"border-border text-muted-foreground hover:bg-muted hover:text-foreground",children:"Cancel"}),(0,n.jsx)(W.z,{type:"button",onClick:k,disabled:0===C||p,className:"bg-primary hover:bg-primary/90 text-primary-foreground font-semibold disabled:opacity-40",style:{fontFamily:"Montserrat, sans-serif"},children:p?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(N.Z,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Insertingâ¦"]}):"Insert ".concat(C>0?"(".concat(C,")"):"")})]})]})]})})}var te=r(758),tt=r(59682),tr=r(36120),tn=r(44323);let to=["image/png","image/jpeg","image/jpg","image/webp","image/heic","image/heif"];function ts(e){var t,r,n;return{id:e.id,workOrderId:null,s3Key:e.photoUrl,thumbnailKey:e.photoUrl,previewKey:e.photoUrl,placeholderDataUrl:null,imageWidth:null,imageHeight:null,phase:null,photoType:null!==(t=e.type)&&void 0!==t?t:null,tagStatus:"auto_complete",capturedAt:null!==(r=e.createdAt)&&void 0!==r?r:null,gpsLat:null,gpsLng:null,createdAt:null!==(n=e.createdAt)&&void 0!==n?n:new Date().toISOString(),isIssue:!1}}function ta(e){let{organizationId:t,estimateId:r,onChange:s,readOnly:a=!1}=e,[l,i]=(0,o.useState)([]),[d,c]=(0,o.useState)(!1),[u,m]=(0,o.useState)(!1),[p,x]=(0,o.useState)(""),[b,h]=(0,o.useState)(!1),[f,g]=(0,o.useState)(new Set),[v,y]=(0,o.useState)(null),j=(0,o.useRef)(null),N=l.map(ts),k=(0,o.useCallback)(async()=>
1{if(r){c(!0);try{var e;let t=await fetch("/api/crew-mobile-estimator/estimates/".concat(r,"/photos"),{credentials:"include"});if(!t.ok)throw Error("Failed to load photos (".concat(t.status,")"));let n=await t.json();i(null!==(e=n.photos)&&void 0!==e?e:[])}catch(e){}finally{c(!1)}}},[r]);(0,o.useEffect)(()=>{r?k():i([])},[r,k]);let w=(0,o.useCallback)(async e=>{if(r){if(x(""),!to.includes(e.type)){x("Only PNG, JPG, WebP, and HEIC images are supported.");return}if(e.size>15728640){x("File is too large â maximum size is 15 MB.");return}m(!0);try{let o=new FormData;o.append("photo",e);let a=await fetch("/api/crew-mobile-estimator/estimates/".concat(r,"/photos"),{method:"POST",body:o,credentials:"include"});if(!a.ok){var t,n;let e=await a.json().catch(()=>({})),r=null!==(n=null!==(t="object"==typeof e.error&&e.error?e.error.message:"string"==typeof e.error?e.error:void 0)&&void 0!==t?t:e.message)&&void 0!==n?n:"Upload failed (".concat(a.status,")");throw Error(r)}await k(),null==s||s()}catch(e){x(e instanceof Error?e.message:"Upload failed")}finally{m(!1)}}},[r,k,s]),C=(0,o.useCallback)(async e=>{if(e&&0!==e.length)for(let t=0;t<e.length;t++){let r=e[t];r&&await w(r)}},[w]),S=(0,o.useCallback)(async e=>{if(r){g(t=>new Set(t).add(e));try{let t=await fetch("/api/crew-mobile-estimator/estimates/".concat(r,"/photos/").concat(e),{method:"DELETE",credentials:"include"});if(!t.ok)throw Error("Delete failed (".concat(t.status,")"));i(t=>t.filter(t=>t.id!==e)),null==s||s()}catch(e){}finally{g(t=>{let r=new Set(t);return r.delete(e),r})}}},[r,s]);return r?(0,n.jsxs)("div",{className:"border border-border rounded-2xl bg-white overflow-hidden",children:[(0,n.jsxs)("div",{className:"px-5 py-3.5 bg-muted border-b border-border",children:[(0,n.jsx)("h2",{className:"text-sm font-bold text-foreground",children:"Project Photos"}),(0,n.jsx)("p",{className:"text-xs text-[#78350F] mt-0.5",children:"These photos appear on the customer's estimate as a visual gallery."})]}),(0,n.jsxs)("div",{className:"p-5 space-y-4",children:[!a&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)("div",{role:"button",tabIndex:0,onDragOver:e=>{e.preventDefault(),h(!0)},onDragLeave:()=>h(!1),onDrop:e=>{e.preventDefault(),h(!1),C(e.dataTransfer.files)},onClick:()=>{var e;return!u&&(null===(e=j.current)||void 0===e?void 0:e.click())},onKeyDown:e=>{var t;return"Enter"===e.key&&!u&&(null===(t=j.current)||void 0===t?void 0:t.click())},"aria-label":"Upload project photos",className:["border-2 border-dashed rounded-xl p-6 text-center cursor-pointer transition-colors",u?"border-primary/40 bg-primary/5 curs
1or-not-allowed":b?"border-primary bg-primary/5":"border-border hover:border-primary/60 hover:bg-primary/5"].join(" "),children:u?(0,n.jsxs)("div",{className:"flex flex-col items-center gap-2",children:[(0,n.jsx)("div",{className:"w-7 h-7 border-2 border-border border-t-primary rounded-full animate-spin",role:"status","aria-label":"Uploading"}),(0,n.jsx)("p",{className:"text-sm text-[#78350F] font-medium",children:"Uploadingâ¦"})]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(tr.Z,{className:"w-6 h-6 mx-auto text-[#C9B99A] mb-2"}),(0,n.jsx)("p",{className:"text-sm font-medium text-foreground",children:"Drop photos here or click to browse"}),(0,n.jsx)("p",{className:"text-xs text-muted-foreground mt-1",children:"PNG, JPG, WebP, HEIC \xb7 up to 15 MB each \xb7 multiple allowed"})]})}),(0,n.jsx)("input",{ref:j,type:"file",accept:"image/png,image/jpeg,image/webp,image/heic,image/heif,.heic,.heif",multiple:!0,onChange:e=>{C(e.target.files),e.target.value=""},className:"hidden","aria-label":"Select photo files"})]}),p&&(0,n.jsxs)("div",{className:"flex items-start gap-2 rounded-lg bg-red-50 border border-red-200 px-3 py-2",children:[(0,n.jsx)("span",{className:"text-red-500 text-xs mt-0.5 flex-shrink-0",children:"â "}),(0,n.jsx)("p",{className:"text-xs text-red-700",children:p}),(0,n.jsx)("button",{onClick:()=>x(""),className:"ml-auto text-red-400 hover:text-red-600 flex-shrink-0","aria-label":"Dismiss error",children:(0,n.jsx)(Z.Z,{className:"w-3.5 h-3.5"})})]}),d&&(0,n.jsx)("div",{className:"grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 gap-2",children:[1,2,3,4,5].map(e=>(0,n.jsx)("div",{className:"aspect-square rounded-lg bg-muted animate-pulse"},e))}),!d&&l.length>0&&(0,n.jsx)("div",{className:"grid grid-cols-3 sm:grid-cols-4 md:grid-cols-5 gap-2",children:l.map((e,t)=>{var r;let o=f.has(e.id);return(0,n.jsxs)("div",{className:["relative group rounded-lg overflow-hidden border border-border bg-muted/30",o?"opacity-50":""].join(" "),children:[(0,n.jsx)("button",{type:"button",onClick:()=>y(t),"aria-label":e.caption?"View photo: ".concat(e.caption):"View photo",className:"block w-full focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-1",disabled:o,children:(0,n.jsx)("img",{src:e.photoUrl,alt:null!==(r=e.caption)&&void 0!==r?r:"Project photo",loading:"lazy",className:"w-full aspect-square object-cover"})}),!a&&(0,n.jsx)("button",{type:"button",onClick:t=>{t.stopPropagation(),o||S(e.id)},disabled:o,"aria-label":"Delete photo",className:"absolute top-1 right-1 w-5 h-5 rounded-full bg-white/90 text-gray-600 hover:bg-red-100 hover:text-red-600 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center shadow-sm disabled:cursor-not-allowed",children:(0,n.jsx)(Z.Z,{className:"w-3 h-3"})}),e.caption&&(0,n.jsx)("div",{className:"absolute bottom-0 left-0 right-0 px-1.5 py-1 bg-black/60 opacity-0 group-hover:opacity-100 transition-opacity pointer-events-none",children:(0,n.jsx)("p",{className:"text-[10px] text-white truncate leading-tight",title:e.caption,children:e.caption})})]},e.id)})}),!d&&0===l.length&&!u&&(0,n.jsx)("p",{className:"text-xs text-muted-foreground text-center py-2",children:"No photos yet â upload site or job photos above."})]}),null!==v&&N.length>0&&(0,n.jsx)(tn.j,{photos:N,initialIndex:v,onClose:()=>y(null),cdnBase:void 0,onIndexChange:e=>y(e)})]}):(0,n.jsxs)("div",{className:"border border-border rounded-2xl bg-white overflow-hidden",children:[(0,n.jsxs)("div",{className:"px-5 py-3.5 bg-muted border-b border-border",children:[(0,n.jsx)("h2",{className:"text-sm font-bold text-foreground",children:"Project Photos"}),(0,n.jsx)("p",{className:"text-xs text-[#78350F] mt-0.5",children:"Photos are shown to the customer on their estimate."})]}),(0,n.jsxs)("div",{className:"px-5 py-8 text-center",children:[(0,n.jsx)(eS.Z,{className:"w-8 h-8 mx-auto text-[#C9B99A] mb-2"}),(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:"Save the estimate first to attach photos."})]})]})}function tl(e){let{organizationId:t,estimateId:r,hideWhenEmpty:s=!1,forceExpanded:a=!1,onCountChange:l}=e,[i,d]=(0,o.useState)(null),[c,u]=(0,o.useState)(!1),m=(0,o.useCallback)(async()=>
1{if(!r){d(0),null==l||l(0);return}try{var e,t;let n=await fetch("/api/crew-mobile-estimator/estimates/".concat(r,"/photos"),{credentials:"include"});if(!n.ok)return;let o=await n.json(),s=null!==(t=null===(e=o.photos)||void 0===e?void 0:e.length)&&void 0!==t?t:0;d(s),null==l||l(s)}catch(e){u(!0)}},[r,l]);(0,o.useEffect)(()=>{m()},[m]);let p=c||a;return r?(null!=i?i:0)!==0||p?(0,n.jsx)(ta,{organizationId:t,estimateId:r,onChange:()=>{m()}}):s?null:(0,n.jsxs)("button",{type:"button",onClick:()=>u(!0),className:"w-full flex items-center justify-between gap-2 border border-border rounded-2xl bg-white px-5 py-3.5 text-left hover:border-primary/50 transition-colors min-h-[44px]",children:[(0,n.jsxs)("span",{className:"flex items-center gap-2 text-sm text-foreground",children:[(0,n.jsx)(eS.Z,{className:"w-4 h-4 text-muted-foreground flex-shrink-0",strokeWidth:2}),"Project photos \xb7 ",null!=i?i:0," attached â Add photos"]}),(0,n.jsx)(U.Z,{className:"w-4 h-4 text-muted-foreground flex-shrink-0",strokeWidth:2})]}):s&&!p?null:(0,n.jsx)("div",{className:"border border-border rounded-2xl bg-white overflow-hidden",children:(0,n.jsxs)("div",{className:"px-5 py-3.5 flex items-center gap-2 text-muted-foreground",children:[(0,n.jsx)(eS.Z,{className:"w-4 h-4 flex-shrink-0",strokeWidth:2}),(0,n.jsx)("span",{className:"text-sm",children:"Project photos â save the estimate first to attach photos."})]})})}var ti=r(20361),td=r(28285),tc=r(60537);function tu(e){let{estimateId:t,hideWhenEmpty:r=!1,forceExpanded:s=!1,onHasContentChange:a}=e,{lines:l,lineLoading:i}=function(e,t){let[r,n]=(0,o.useState)([]),[s,a]=(0,o.useState)(!0);return(0,o.useEffect)(()=>{if(!e){a(!1);return}let t=!1;return a(!0),fetch("/api/crm-estimates/".concat(e),{credentials:"include"}).then(e=>e.ok?e.json():Promise.reject(e.status)).then(e=>{var r,o,s,a;if(t)return;let l=null!==(o=null===(r=e.estimate)||void 0===r?void 0:r.lineGroups)&&void 0!==o?o:[],i=[];for(let e of l)for(let t of null!==(s=e.items)&&void 0!==s?s:[])i.push({id:t.id,description:null!==(a=t.description)&&void 0!==a?a:""});n(i)}).catch(()=>{t||n([])}).finally(()=>{t||a(!1)}),()=>{t=!0}},[e,t]),{lines:r,lineLoading:s}}(t,s),{grouped:d,estimateStatus:c,loading:u,error:m,refresh:p,createOption:x,updateOption:b,deleteOption:h,hasAnyOptions:f}=(0,tc.j)(null!=t?t:"");(0,o.useEffect)(()=>{if(!t){null==a||a(!1);return}u||null==a||a(f)},[t,u,f,a]);let g=s||f;return r&&!g?null:t?(0,n.jsx)("div",{id:"estimate-options-section",className:"bg-card rounded-2xl border border-border shadow-sm overflow-hidden",children:(0,n.jsx)("div",{className:"p-5",children:(0,n.jsx)(td.B,{estimateId:t,lines:l,grouped:d,loading:u||i,error:m,estimateStatus:c,onCreate:x,onUpdate:b,onDelete:h,onRefresh:p})})}):(0,n.jsxs)("div",{className:"bg-card rounded-2xl border border-border shadow-sm overflow-hidden",children:[(0,n.jsxs)("div",{className:"px-5 py-3.5 bg-muted border-b border-border flex items-center gap-2",children:[(0,n.jsx)(ti.Z,{className:"h-4 w-4 text-primary",strokeWidth:1.75}),(0,n.jsx)("h2",{className:"text-sm font-bold text-foreground",children:"Options"})]}),(0,n.jsxs)("div",{className:"p-5 text-center",children:[(0,n.jsx)("p",{className:"text-[13px] text-foreground",children:"Offer Good/Better/Best â customers pick, total updates."}),(0,n.jsx)("p",{className:"mt-1 text-[12px] text-muted-foreground",children:"Save the estimate first, then add options here."})]})]})}var tm=r(39866),tp=r(24726);let tx=[{key:"options",label:"Options"},{key:"scope",label:"Scope"},{key:"photos",label:"Photos"},{key:"terms",label:"Terms"},{key:"markup",label:"Markup"},{key:"urgency",label:"Urgency"}],tb="estimateSimpleMode.expanded",th="estimateSimpleMode.expandAllCount",tf="estimateSimpleMode.fullLayout";function tg(e){return"string"==typeof e&&tx.some(t=>t.key===e)}function tv(e){try{window.localStorage.setItem(tb,JSON.stringify(Array.from(e)))}catch(e){}}function ty(e){let{sections:t,onToggle:r,onExpandAll:o}=e;return(0,n.jsxs)("div",{"data-testid":"simple-mode-chips",className:"flex flex-wrap items-center gap-2 rounded-xl border border-border bg-muted/60 px-3 py-2",children:[(0,n.jsx)("span",{className:"pr-0.5 text-[10px] font-semibold uppercase tracking-wider text-muted-foreground",children:"More"}),t.map(e=>(0,n.jsxs)("button",{type:"button","data-testid":"simple-mode-chip-".concat(e.key),"aria-pressed":e.expanded,"aria-label":e.hasContent?"".concat(e.label," (has content)"):e.label,onClick:()=>r(e.key),className:"inline-flex min-h-[44px] items-center gap-1.5 rounded-full border px-3 py-2 text-[12px] font-semibold transition-colors ".concat(e.expanded?"border-primary bg-primary/10 text-primary":"border-border bg-card text-foreground hover:border-primary/50"),children:[e.hasContent&&(0,n.jsx)("span",{"aria-hidden":!0,
1className:"h-1.5 w-1.5 flex-shrink-0 rounded-full bg-primary"}),e.label,(0,n.jsx)(eo.Z,{className:"h-3 w-3 flex-shrink-0 text-muted-foreground transition-transform ".concat(e.expanded?"rotate-180":""),strokeWidth:2.25})]},e.key)),(0,n.jsx)("button",{type:"button","data-testid":"simple-mode-expand-all",onClick:o,className:"ml-auto min-h-[44px] px-2 text-[11px] font-semibold text-primary hover:underline",children:"Expand all"})]})}var tj=r(73552),tN=r(77329),tk=r(29147),tw=r(6257);let tC={high:{fill:"bg-emerald-500",flag:"bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-950/30 dark:text-emerald-300 dark:border-emerald-800",label:"High"},medium:{fill:"bg-amber-500",flag:"bg-amber-50 text-amber-700 border-amber-200 dark:bg-amber-950/30 dark:text-amber-300 dark:border-amber-800",label:"Medium"},low:{fill:"bg-red-500",flag:"bg-red-50 text-red-700 border-red-200 dark:bg-red-950/30 dark:text-red-300 dark:border-red-800",label:"Low"},unknown:{fill:"bg-muted-foreground/40",flag:"bg-muted text-muted-foreground border-border",label:"Checkingâ¦"}};function tS(e){return e<1?e.toFixed(3):e.toFixed(1)}function tI(e){let{taskLabel:t,unit:r,catalogMinutesPerUnit:s,learnedMinutesPerUnit:a,variancePct:l,sampleSize:i,confidence:d,onApplyToEstimate:c,onApplyAsOrgDefault:u}=e,[m,p]=(0,o.useState)(!1),[x,b]=(0,o.useState)(!1),[h,f]=(0,o.useState)(!1),[g,v]=(0,o.useState)(!1),[y,j]=(0,o.useState)("idle"),N=(0,o.useRef)(null),k=(0,o.useRef)(null),w=(0,o.useRef)(null);(0,o.useEffect)(()=>()=>{N.current&&clearTimeout(N.current)},[]),(0,o.useEffect)(()=>{var e;m&&(null===(e=k.current)||void 0===e||e.focus())},[m]);let C=l<0,S=tC[(0,tw.A)(Math.round(100*d))],I=C?"Your actual is faster: ".concat(tS(a)," min/").concat(r," across ").concat(i," jobs â lower this rate?"):"Your actual: ".concat(tS(a)," min/").concat(r," across ").concat(i," jobs â apply?"),A=async()=>{j("applying");try{await u(),j("done"),v(!0),p(!1)}catch(e){j("confirming")}};return x?h?(0,n.jsxs)("div",{className:"mt-1.5 inline-flex items-center gap-2 text-[11px] text-muted-foreground",children:["Hint dismissed for this session",(0,n.jsx)("button",{type:"button",onClick:()=>{N.current&&clearTimeout(N.current),b(!1),f(!1)},className:"rounded px-1 py-0.5 font-bold text-[#D4920B] underline",children:"Undo"})]}):null:g&&!m?(0,n.jsx)("span",{className:"mt-1.5 inline-flex items-center gap-1.5 rounded-full border border-emerald-200 bg-emerald-50 px-2.5 py-0.5 text-[11.5px] font-semibold text-emerald-700 dark:border-emerald-800 dark:bg-emerald-950/30 dark:text-emerald-300",children:"done"===y?"â Applied as org default â future estimates use this rate":"â Applied to this estimate"}):(0,n.jsxs)("div",{className:"mt-1.5",children:[(0,n.jsxs)("div",{className:"inline-flex max-w-full items-center gap-0.5",children:[(0,n.jsxs)("button",{ref:w,type:"button","aria-expanded":m,"aria-controls":void 0,onClick:()=>p(e=>!e),className:"flex max-w-full items-center gap-1.5 rounded-md py-1 pl-0.5 pr-1.5 text-left hover:bg-[#D4920B]/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[(0,n.jsx)("span",{"aria-hidden":"true",className:"flex h-[17px] w-[17px] shrink-0 items-center justify-center rounded-[5px] bg-[#D4920B]/10 text-[#D4920B]",children:(0,n.jsx)(tN.Z,{className:"h-2.5 w-2.5",strokeWidth:2.5})}),(0,n.jsx)("span",{className:"text-[11.5px] font-semibold text-[#D4920B] underline decoration-dotted decoration-[#D4920B]/50 underline-offset-2",children:I})]}),(0,n.jsx)("button",{type:"button","aria-label":"Dismiss rate hint for this line",onClick:()=>{b(!0),f(!0),N.current=setTimeout(()=>f(!1),4e3)},className:"grid h-[22px] w-[22px] shrink-0 place-items-center rounded-md text-muted-foreground hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:(0,n.jsx)(Z.Z,{className:"h-3 w-3"})})]}),m&&(0,n.jsxs)("div",{role:"region","aria-label":"Learned rate comparison â ".concat(t),className:"mt-3 rounded-xl border border-[#D4920B]/35 bg-[#D4920B]/10 p-4",children:[(0,n.jsxs)("div",{className:"mb-3 flex items-start justify-between gap-2.5",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("b",{className:"text-xs font-extrabold text-foreground",children:"Brion noticed a learned rate for this task"}),(0,n.jsx)("span",{className:"mt-0.5 block text-[11px] font-medium text-muted-foreground",children:"Based on completed jobs logging time against this catalog task"})]}),(0,n.jsx)("button",{type:"button","aria-label":"Collapse",onClick:()=>{var e;p(!1),null===(e=w.current)||void 0===e||e.focus()},className:"grid h-[30px] w-[30px] shrink-0 place-items-center rounded-lg border border-border bg-card text-muted-foreground hover:border-[#D4920B]/40 hover:text-[#D4920B] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:"â"})]}),(0,n.jsxs)("div",{className:"mb-3.5 grid grid-cols-[1fr_1fr_auto] items-stretch gap-3.5",children:[(0,n.jsxs)("div",{className:"rounded-lg border border-border bg-card p-2.5",children:[(0,n.jsx)("div",{className:"text-[10px] font-extrabold uppercase tracking-wide text-muted-foreground",children:"Catalog rate"}),(0,n.jsxs)("div",{className:"mt-0.5 text-base font-bold tabular-nums text-foreground",children:[tS(s)," min/",r]}),(0,n.jsx)("div",{className:"mt-0.5 text-[11px] text-muted-foreground",children:"budgeted, current estimate"})]}),(0,n.jsxs)("div",{className:"rounded-lg border border-[#D4920B]/35 bg-card p-2.5",children:[(0,n.jsx)("div",{className:"text-[10px] font-extrabold uppercase tracking-wide text-muted-foreground",children:"Your actual"}),(0,n.jsxs)("div",{className:"mt-0.5 text-base font-bold tabular-nums text-[#D4920B]",children:[tS(a)," min/",r]}),(0,n.jsx)("div",{className:"mt-0.5 text-[11px] text-muted-foreground",children:"field-logged average"})]}),(0,n.jsxs)("div",{className:"flex min-w-[88px] flex-col items-center justify-center gap-0.5",children:[(0,n.jsxs)("span",{className:(0,tk.cn)("text-lg font-extrabold tabular-nums",C?"text-emerald-600":"text-amber-600"),children:[C?"":"+",Math.round(l),"%"]}),(0,n.jsx)("span",{className:"text-[10px] font-bold uppercase tracking-wide text-muted-foreground",children:"variance"})]})]}),(0,n.jsxs)("div",{className:"mb-3.5 flex items-center gap-2.5 text-xs",children:[(0,n.jsx)("span",{className:"shrink-0 text-[10.5px] font-extrabold uppercase tracking-wide text-muted-foreground",children:"Confidence"}),(0,n.jsx)("div",{className:"h-1.5 max-w-[220px] flex-1 overflow-hidden rounded-full bg-muted",children:(0,n.jsx)("div",{className:(0,tk.cn)("h-full rounded-full",S.fill),style:{width:"".concat(Math.round(100*d),"%")}})}),(0,n.jsx)("span",{className:(0,tk.cn)("shrink-0 whitespace-nowrap rounded-full border px-2.5 py-0.5 text-[10.5px] font-extrabold",S.flag),children:S.label}),(0,n.jsxs)("span",{className:"text-[11px] text-muted-foreground",children:["n=",i," jobs"]})]}),(0,n.jsxs)("div",{className:"grid grid-cols-1 gap-2.5 sm:grid-cols-3",children:[(0,n.jsxs)("button",{ref:k,type:"button",onClick:()=>{var e;c(),v(!0),p(!1),null===(e=w.current)||void 0===e||e.focus()},className:"flex min-h-[44px] flex-col items-center justify-center gap-0.5 rounded-lg border border-primary bg-primary px-3 py-2.5 text-center text-[12.5px] font-bold text-primary-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[C?"Lower this estimate":"Apply to this estimate",(0,n.jsx)("span",{className:"text-[10px] font-medium text-primary-foreground
1/80",children:"Updates only this line, this document"})]}),"confirming"===y?(0,n.jsxs)("button",{type:"button",onClick:A,disabled:"confirming"!==y,className:"flex min-h-[44px] flex-col items-center justify-center gap-0.5 rounded-lg border border-amber-300 bg-amber-50 px-3 py-2.5 text-center text-[12.5px] font-bold text-amber-800 dark:border-amber-800 dark:bg-amber-950/30 dark:text-amber-300 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:["Confirm â apply for all future estimates",(0,n.jsx)("span",{className:"text-[10px] font-medium opacity-85",children:"This cannot be undone from here"})]}):(0,n.jsxs)("button",{type:"button",disabled:"applying"===y,onClick:()=>j("confirming"),className:"flex min-h-[44px] flex-col items-center justify-center gap-0.5 rounded-lg border border-[#D4920B]/40 bg-card px-3 py-2.5 text-center text-[12.5px] font-bold text-[#D4920B] hover:bg-[#D4920B]/10 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:["applying"===y?"Applyingâ¦":"Apply as org default",(0,n.jsx)("span",{className:"text-[10px] font-medium text-[#D4920B]/85",children:"Updates pricing for all future estimates using this task"})]}),(0,n.jsxs)("button",{type:"button",onClick:()=>{var e;p(!1),null===(e=w.current)||void 0===e||e.focus()},className:"flex min-h-[44px] flex-col items-center justify-center gap-0.5 rounded-lg border border-border bg-card px-3 py-2.5 text-center text-[12.5px] font-bold text-foreground hover:border-muted-foreground/40",children:["Not now",(0,n.jsx)("span",{className:"text-[10px] font-medium text-muted-foreground",children:"Keep the current rate"})]})]})]})]})}var tA=r(32710),tE=r(50221),tT=r(80481),tP=r(51062),tD=r(80815),tF=r(11039),tO=r(27126),tM=r(96825),tZ=r(10997),tG=r(98609);function tL(){return Math.random().toString(36).slice(2)}let tR=[{key:"PAINT_50_50",label:"50% Deposit + 50% Final (Painting standard)",milestones:[{sequence:0,label:"Deposit",amountKind:"PERCENT",percent:.5,fixedAmountCents:null,triggerKind:"ON_ESTIMATE_SIGN",expectedDueDate:null},{sequence:1,label:"Final",amountKind:"PERCENT",percent:.5,fixedAmountCents:null,triggerKind:"MANUAL",expectedDueDate:null}]},{key:"PAINT_30_40_30",label:"30% / 40% / 30% (Whole-house repaint)",milestones:[{sequence:0,label:"Deposit",amountKind:"PERCENT",percent:.3,fixedAmountCents:null,triggerKind:"ON_ESTIMATE_SIGN",expectedDueDate:null},{sequence:1,label:"Mid-job",amountKind:"PERCENT",percent:.4,fixedAmountCents:null,triggerKind:"MANUAL",expectedDueDate:null},{sequence:2,label:"Final",amountKind:"PERCENT",percent:.3,fixedAmountCents:null,triggerKind:"MANUAL",expectedDueDate:null}]},{key:"CARPENTRY_30_30_30_10",label:"30% / 30% / 30% / 10% (Carpentry / remodels)",milestones:[{sequence:0,label:"Deposit",amountKind:"PERCENT",percent:.3,fixedAmountCents:null,triggerKind:"ON_ESTIMATE_SIGN",expectedDueDate:null},{sequence:1,label:"Framing",amountKind:"PERCENT",percent:.3,fixedAmountCents:null,triggerKind:"MANUAL",expectedDueDate:null},{sequence:2,label:"Trim",amountKind:"PERCENT",percent:.3,fixedAmountCents:null,triggerKind:"MANUAL",expectedDueDate:null},{sequence:3,label:"Final / Punch",amountKind:"PERCENT",percent:.1,fixedAmountCents:null,triggerKind:"MANUAL",expectedDueDate:null}]},{key:"CLEAN_ON_COMPLETION",label:"Pay on completion (Cleaning standard)",milestones:[{sequence:0,label:"Final",amountKind:"PERCENT",percent:1,fixedAmountCents:null,triggerKind:"MANUAL",expectedDueDate:null}]}];function tB(e){return e?"painting"===e?"PAINT_50_50":"cleaning"===e?"CLEAN_ON_COMPLETION":"carpentry"===e||"small_remodels"===e||"general_repairs"===e?"CARPENTRY_30_30_30_10":"CUSTOM":"CUSTOM"}function tq(e){let t=tR.find(t=>t.key===e);return t?t.milestones.map(e=>({...e,id:tL()})):[{id:tL(),sequence:0,label:"Deposit",amountKind:"PERCENT",percent:.5,fixedAmountCents:null,triggerKind:"ON_ESTIMATE_SIGN",expectedDueDate:null},{id:tL(),sequence:1,label:"Final",amountKind:"PERCENT",percent:.5,fixedAmountCents:null,triggerKind:"MANUAL",expectedDueDate:null}]}function tW(e){let{totalAmountCents:t,customerState:r,trade:a,milestones:l,onChange:d,collapsed:c=!0,onCollapseChange:u}=e,[m,p]=(0,o.useState)(tB(a));(0,o.useEffect)(()=>
1{if(0===l.length&&a){let e=tB(a);p(e),d(tq(e))}},[]);let x=function(e,t,r){let n=[];if(e.some(e=>"PERCENT"===e.amountKind)){let t=e.reduce((e,t)=>{var r;return e+("PERCENT"===t.amountKind?(0,s.Qw)(null!==(r=t.percent)&&void 0!==r?r:0):0)},0);Math.abs(t-1)>.001&&n.push({type:"error",message:"Milestone percentages sum to ".concat(Math.round(100*t),"% â must equal 100%."),code:"TOTAL_NOT_100"})}let o=e.find(e=>0===e.sequence);if(!o||t<=0)return n;let a=0;"PERCENT"===o.amountKind&&null!=o.percent?a=Math.round(t*o.percent):"FIXED_CENTS"===o.amountKind&&null!=o.fixedAmountCents&&(a=o.fixedAmountCents);let l=a/t;switch(null==r?void 0:r.toUpperCase()){case"CA":case"NV":{let e=Math.min(Math.round(.1*t),1e5);a>e&&n.push({type:"error",message:"".concat(r," law (CSLB \xa77159.5) limits deposits to 10% or $1,000, whichever is less. Max: $").concat((e/100).toFixed(2)," (").concat(Math.round(e/t*100),"%)."),code:"CA_NV_HARD_BLOCK"});break}case"MD":l>1/3&&n.push({type:"warning",message:"Maryland limits deposits to 1/3 of the contract ($".concat((t/3/100).toFixed(2),"). You can override this with written customer authorization."),code:"MD_SOFT_WARN"});break;default:l>.33&&n.push({type:"info",message:"Deposit is ".concat(Math.round(100*l),"%. Industry standard is 30%. No legal cap in this state, but high deposits can deter customers."),code:"INDUSTRY_HINT"})}return n}(l,t,r),b=x.some(e=>"error"===e.type),h=0===l.length?"No payment schedule":l.map(e=>"PERCENT"===e.amountKind&&null!=e.percent?"".concat((0,s.DW)(e.percent),"% ").concat(e.label):"FIXED_CENTS"===e.amountKind&&null!=e.fixedAmountCents?"$".concat((e.fixedAmountCents/100).toFixed(2)," ").concat(e.label):e.label).join(" + "),f=!b&&0===x.length,g=(0,o.useCallback)((e,t)=>{d(l.map(r=>r.id===e?{...r,...t}:r))},[l,d]),v=(0,o.useCallback)(()=>{let e=l.length;d([...l,{id:tL(),sequence:e,label:0===e?"Deposit":"Milestone",amountKind:"PERCENT",percent:0,fixedAmountCents:null,triggerKind:0===e?"ON_ESTIMATE_SIGN":"MANUAL",expectedDueDate:null}])},[l,d]),y=(0,o.useCallback)(e=>{d(l.filter(t=>t.id!==e).map((e,t)=>({...e,sequence:t})))},[l,d]),j=(0,o.useCallback)(e=>{p(e),d(tq(e))},[d]);return(0,n.jsxs)("div",{className:"rounded-lg border border-border overflow-hidden",children:[(0,n.jsxs)("button",{type:"button",onClick:()=>null==u?void 0:u(!c),className:"w-full flex items-center justify-between px-4 py-3 bg-card hover:bg-muted transition-colors text-left",children:[(0,n.jsxs)("div",{className:"flex items-center gap-3 min-w-0",children:[(0,n.jsx)("span",{className:"text-sm font-semibold text-foreground",children:"Payment Schedule"}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground truncate hidden sm:inline",children:h}),f&&l.length>0&&(0,n.jsx)(H.Z,{className:"w-3.5 h-3.5 text-green-600 shrink-0"}),b&&(0,n.jsx)(i.Z,{className:"w-3.5 h-3.5 text-red-500 shrink-0"})]}),c?(0,n.jsx)(eo.Z,{className:"w-4 h-4 text-muted-foreground shrink-0"}):(0,n.jsx)(eQ.Z,{className:"w-4 h-4 text-muted-foreground shrink-0"})]}),!c&&(0,n.jsxs)("div",{className:"px-4 pb-4 pt-3 space-y-4 bg-white",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)("span",{className:"text-xs font-medium text-muted-foreground shrink-0",children:"Apply template:"}),(0,n.jsxs)(tG.Ph,{value:m,onValueChange:e=>j(e),children:[(0,n.jsx)(tG.i4,{className:"h-8 text-xs flex-1 max-w-[340px]",children:(0,n.jsx)(tG.ki,{})}),(0,n.jsxs)(tG.Bw,{children:[tR.map(e=>(0,n.jsx)(tG.Ql,{value:e.key,className:"text-xs",children:e.label},e.key)),(0,n.jsx)(tG.Ql,{value:"CUSTOM",className:"text-xs",children:"Custom"})]})]})]}),x.map(e=>(0,n.jsxs)("div",{className:"flex items-start gap-2 p-3 rounded-md text-xs ".concat("error"===e.type?"bg-red-50 border border-red-200 text-red-700":"warning"===e.type?"bg-amber-50 border border-amber-200 text-amber-700":"bg-blue-50 border border-blue-100 text-blue-700"),children:["error"===e.type?(0,n.jsx)(i.Z,{className:"w-3.5 h-3.5 shrink-0 mt-0.5"}):(0,n.jsx)(tO.Z,{className:"w-3.5 h-3.5 shrink-0 mt-0.5"}),(0,n.jsx)("span",{children:e.message})]},e.code)),(0,n.jsx)("div",{className:"space-y-2",children:l.map((e,r)=>(0,n.jsxs)("div",{className:"flex items-center gap-2 p-2 rounded-md border border-border bg-card",children:[(0,n.jsx)(tM.Z,{className:"w-4 h-4 text-muted-foreground shrink-0 cursor-grab"}),(0,n.jsx)("span",{className:"text-[10px] font-bold text-muted-foreground w-4 text-center",children:r+1}),(0,n.jsx)("input",{type:"text",value:e.label,onChange:t=>g(e.id,{label:t.target.value}),placeholder:"Label",className:"flex-1 min-w-0 text-sm border border-transparent hover:border-border focus:border-primary rounded px-2 py-1 bg-transparent focus:bg-white focus:outline-none transition-colors"}),(0,n.jsxs)("div",{className:"flex rounded overflow-hidden border border-border text-xs",children:[(0,n.jsx)("button",{type:"button",onClick:()=>g(e.id,{amountKind:"PERCENT",fixedAmountCents:null}),className:"px-2 py-1 ".concat("PERCENT"===e.amountKind?"bg-primary text-primary-foreground":"text-muted-foreground hover:bg-muted"),children:"%"}),(0,n.jsx)("button",{type:"button",onClick:()=>g(e.id,{amountKind:"FIXED_CENTS",percent:null}),className:"px-2 py-1 ".concat("FIXED_CENTS"===e.amountKind?"bg-primary text-primary-foreground":"text-muted-foreground hover:bg-muted"),children:"$"})]}),"PERCENT"===e.amountKind?(0,n.jsxs)("div",{className:"relative w-20",children:[(0,n.jsx)("input",{type:"number",min:"0",max:"100",step:"1",value:null!=e.percent?(0,s.DW)(e.percent):"",onCh
1ange:t=>{let r=parseInt(t.target.value,10);g(e.id,{percent:isNaN(r)?null:r/100})},placeholder:"0",className:"w-full text-sm border border-border rounded px-2 py-1 pr-5 focus:outline-none focus:border-primary"}),(0,n.jsx)("span",{className:"absolute right-1.5 top-1/2 -translate-y-1/2 text-xs text-muted-foreground",children:"%"})]}):(0,n.jsxs)("div",{className:"relative w-24",children:[(0,n.jsx)("span",{className:"absolute left-2 top-1/2 -translate-y-1/2 text-xs text-muted-foreground",children:"$"}),(0,n.jsx)("input",{type:"number",min:"0",step:"0.01",value:null!=e.fixedAmountCents?(e.fixedAmountCents/100).toFixed(2):"",onChange:t=>{let r=parseFloat(t.target.value);g(e.id,{fixedAmountCents:isNaN(r)?null:Math.round(100*r)})},placeholder:"0.00",className:"w-full text-sm border border-border rounded px-2 py-1 pl-5 focus:outline-none focus:border-primary"})]}),(0,n.jsx)("span",{className:"text-xs text-muted-foreground w-16 text-right tabular-nums shrink-0",children:"PERCENT"===e.amountKind&&null!=e.percent?"$".concat((t*(0,s.Qw)(e.percent)/100).toFixed(0)):null!=e.fixedAmountCents?"$".concat((e.fixedAmountCents/100).toFixed(2)):"â"}),(0,n.jsx)("button",{type:"button",onClick:()=>y(e.id),className:"text-muted-foreground hover:text-red-500 transition-colors shrink-0","aria-label":"Remove milestone",children:(0,n.jsx)(tZ.Z,{className:"w-3.5 h-3.5"})})]},e.id))}),(0,n.jsxs)(W.z,{type:"button",variant:"outline",size:"sm",onClick:v,className:"gap-1.5 text-xs",children:[(0,n.jsx)(A.Z,{className:"w-3.5 h-3.5"}),"Add milestone"]})]})]})}var t_=r(70775),tU=r(70845),tz=r(57641),tK=r(39769),tV=r(18519);function tH(e){let{open:t,onOpenChange:r,title:s,description:a,defaultName:l="",trades:i,onSave:d}=e,[c,u]=(0,o.useState)(l),[m,p]=(0,o.useState)("");return(0,o.useEffect)(()=>{t&&(u(l),p(""))},[t,l]),(0,n.jsx)(e2.Vq,{open:t,onOpenChange:r,children:(0,n.jsxs)(e2.cZ,{className:"max-w-md",children:[(0,n.jsxs)(e2.fK,{children:[(0,n.jsx)(e2.$N,{children:s}),a&&(0,n.jsx)(e2.Be,{children:a})]}),(0,n.jsxs)("form",{onSubmit:function(e){e.preventDefault();let t=c.trim();t&&(d(t,m),r(!1))},className:"space-y-4 mt-2",children:[(0,n.jsxs)("div",{className:"space-y-1.5",children:[(0,n.jsxs)("label",{htmlFor:"save-as-name",className:"block text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:["Name ",(0,n.jsx)("span",{className:"text-[#DC2626]",children:"*"})]}),(0,n.jsx)(e3.I,{id:"save-as-name",value:c,onChange:e=>u(e.target.value),placeholder:"e.g. Interior 2-coat painting",autoFocus:!0,className:"h-10"})]}),i&&i.length>0&&(0,n.jsxs)("div",{className:"space-y-1.5",children:[(0,n.jsxs)("label",{htmlFor:"save-as-trade",className:"block text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:["Trade ",(0,n.jsx)("span",{className:"text-[10px] font-normal normal-case text-muted-foreground",children:"(optional)"})]}),(0,n.jsxs)("select",{id:"save-as-trade",value:m,onChange:e=>p(e.target.value),className:"w-full rounded-xl border border-border bg-white px-3.5 py-2.5 text-sm text-foreground appearance-none focus:outline-none focus:ring-2 focus:ring-ring/40 focus:border-primary",children:[(0,n.jsx)("option",{value:"",children:"All trades"}),i.map(e=>(0,n.jsx)("option",{value:e.slug,children:e.name},e.slug))]})]}),(0,n.jsxs)("div",{className:"flex justify-end gap-2 pt-1",children:[(0,n.jsx)(W.z,{type:"button",variant:"outline",onClick:()=>r(!1),children:"Cancel"}),(0,n.jsx)(W.z,{type:"submit",disabled:!c.trim(),className:"bg-primary hover:bg-primary/90 text-primary-foreground border-0",children:"Save"})]})]})]})})}function tJ(e){let{open:t,onOpenChange:r,estimateId:s,hasExistingScope:l,onApplied:i}=e,[d,c]=(0,o.useState)([]),[u,m]=(0,o.useState)(!1),[p,x]=(0,o.useState)(""),[b,h]=(0,o.useState)(null),[f,g]=(0,o.useState)(null);(0,o.useEffect)(()=>{if(!t)return;let e=!1;return m(!0),x(""),h(null),fetch("/api/crm-estimates/scope-templates?sort=recent",{credentials:"include"}).then(e=>e.ok?e.json():Promise.reject(e.status)).then(t=>{var r;e||c(null!==(r=null==t?void 0:t.templates)&&void 0!==r?r:[])}).catch(()=>{e||c([])}).finally(()=>{e||m(!1)}),()=>{e=!0}},[t]);let v=(0,o.useMemo)(()=>{let e=new Set,t=[];
1for(let r of d)r.trade&&!e.has(r.trade)&&(e.add(r.trade),t.push(r.trade));return t},[d]),y=(0,o.useMemo)(()=>{let e=p.trim().toLowerCase();return d.filter(t=>{var r,n;return(!b||t.trade===b)&&(!e||(t.label+" "+(null!==(r=t.trade)&&void 0!==r?r:"")+" "+(null!==(n=t.previewText)&&void 0!==n?n:"")).toLowerCase().includes(e))})},[d,p,b]);async function j(e,t){g(e);try{var n,o,l,d,c;let u="/api/crm-estimates/".concat(s,"/apply-scope-template/").concat(e).concat(t?"?overwrite=true":""),m=await fetch(u,{method:"POST",credentials:"include"}),p=await m.json().catch(()=>({}));if(!m.ok){a.A.error(null!==(n=p.error)&&void 0!==n?n:"Failed to apply scope template.");return}i({scopeOfWork:null!==(o=p.scopeOfWork)&&void 0!==o?o:null,scopeSpecs:null!==(l=p.scopeSpecs)&&void 0!==l?l:[],scopeIncludes:null!==(d=p.scopeIncludes)&&void 0!==d?d:[],scopeExcludes:null!==(c=p.scopeExcludes)&&void 0!==c?c:[]}),a.A.success("Scope template applied."),r(!1)}catch(e){a.A.error("Could not apply scope template â network error.")}finally{g(null)}}return(0,n.jsx)(e2.Vq,{open:t,onOpenChange:r,children:(0,n.jsxs)(e2.cZ,{className:"max-w-2xl",children:[(0,n.jsxs)(e2.fK,{children:[(0,n.jsx)(e2.$N,{children:"Apply scope template"}),(0,n.jsx)(e2.Be,{children:"Pick a saved scope template to copy its narrative, inclusions, exclusions, and spec strip into this estimate. Ordered by most recently used."})]}),(0,n.jsxs)("div",{className:"relative",children:[(0,n.jsx)(G.Z,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),(0,n.jsx)(e3.I,{value:p,onChange:e=>x(e.target.value),placeholder:"Search by label or tradeâ¦",className:"pl-9",autoFocus:!0})]}),v.length>0&&(0,n.jsxs)("div",{className:"flex flex-wrap gap-1.5",children:[(0,n.jsx)("button",{type:"button",onClick:()=>h(null),className:"px-2.5 py-1 rounded-full text-xs font-semibold transition-colors "+(null===b?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground hover:bg-muted/80"),children:"All"}),v.map(e=>(0,n.jsx)("button",{type:"button",onClick:()=>h(e===b?null:e),className:"px-2.5 py-1 rounded-full text-xs font-semibold capitalize transition-colors "+(b===e?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground hover:bg-muted/80"),children:e},e))]}),(0,n.jsx)("div",{className:"max-h-[50vh] overflow-y-auto border rounded-md divide-y",children:u?(0,n.jsxs)("div",{className:"flex items-center justify-center py-10 text-muted-foreground text-sm",children:[(0,n.jsx)(N.Z,{className:"h-4 w-4 animate-spin mr-2"}),"Loading templatesâ¦"]}):0===y.length?(0,n.jsxs)("div",{className:"flex flex-col items-center justify-center py-10 text-muted-foreground text-sm gap-2",children:[(0,n.jsx)(w.Z,{className:"h-6 w-6 opacity-50"}),0===d.length?'No scope templates saved yet. Write a scope and click "Save as template".':"No matches for that search."]}):y.map(e=>{let t=f===e.id;return(0,n.jsxs)("button",{type:"button",disabled:null!==f,onClick:()=>(function(e){if(l){(0,a.A)("This estimate already has scope content.",{duration:8e3,action:{label:"Overwrite",onClick:()=>void j(e.id,!0)},cancel:{label:"Cancel",onClick:()=>{}}});return}j(e.id,!1)})(e),className:"w-full text-left px-4 py-3 hover:bg-accent transition-colors flex items-start gap-3 disabled:opacity-60",children:[(0,n.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,n.jsx)("span",{className:"text-sm font-semibold text-foreground truncate",children:e.label}),e.trade&&(0,n.jsx)("span",{className:"inline-block px-2 py-0.5 rounded-full bg-muted text-[10px] font-semibold uppercase tracking-wide text-muted-foreground capitalize",children:e.trade})]}),e.previewText&&(0,n.jsxs)("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-2 whitespace-pre-wrap",children:[e.previewText.slice(0,140),e.previewText.length>140?"â¦":""]}),(0,n.jsxs)("div",{className:"flex gap-3 mt-1",children:[e.includeCount>0&&(0,n.jsxs)("span",{className:"text-[11px] text-[#2F7D55]",children:[e.includeCount," included"]}),e.excludeCount>0&&(0,n.jsxs)("span",{className:"text-[11px] text-[#B4602A]",children:[e.excludeCount," excluded"]}),e.specCount>0&&(0,n.jsxs)("span",{className:"text-[11px] text-muted-foreground",children:[e.specCount," specs"]})]})]}),t&&(0,n.jsx)(N.Z,{className:"h-4 w-4 animate-spin text-muted-foreground shrink-0 mt-0.5"})]},e.id)})})]})})}function tQ(e){let{open:t,onOpenChange:r,estimateId:l,onInserted:i}=e,[d,c]=(0,o.useState)([]),[u,m]=(0,o.useState)(!1),[p,x]=(0,o.useState)(""),[b,h]=(0,o.useState)(null),[f,g]=(0,o.useState)(null);(0,o.useEffect)(()=>
1{if(!t)return;let e=!1;return m(!0),x(""),h(null),fetch("/api/crm-estimates/saved-line-groups?sort=recent",{credentials:"include"}).then(e=>e.ok?e.json():Promise.reject(e.status)).then(t=>{var r;e||c(null!==(r=null==t?void 0:t.savedGroups)&&void 0!==r?r:[])}).catch(()=>{e||c([])}).finally(()=>{e||m(!1)}),()=>{e=!0}},[t]);let v=(0,o.useMemo)(()=>{let e=new Set,t=[];for(let r of d)r.trade&&!e.has(r.trade)&&(e.add(r.trade),t.push(r.trade));return t},[d]),y=(0,o.useMemo)(()=>{let e=p.trim().toLowerCase();return d.filter(t=>{var r;return(!b||t.trade===b)&&(!e||(t.name+" "+(null!==(r=t.trade)&&void 0!==r?r:"")).toLowerCase().includes(e))})},[d,p,b]);async function j(e){g(e.id);try{let n=await fetch("/api/crm-estimates/".concat(l,"/insert-saved-group/").concat(e.id),{method:"POST",credentials:"include"});if(!n.ok){var t;let e=await n.json().catch(()=>({}));a.A.error(null!==(t=e.error)&&void 0!==t?t:"Failed to insert group.");return}a.A.success('"'.concat(e.name,'" inserted.')),i(),r(!1)}catch(e){a.A.error("Could not insert group â network error.")}finally{g(null)}}return(0,n.jsx)(e2.Vq,{open:t,onOpenChange:r,children:(0,n.jsxs)(e2.cZ,{className:"max-w-2xl",children:[(0,n.jsxs)(e2.fK,{children:[(0,n.jsx)(e2.$N,{children:"Insert saved group"}),(0,n.jsx)(e2.Be,{children:"Pick a saved line group to append its items into this estimate. Ordered by most recently used."})]}),(0,n.jsxs)("div",{className:"relative",children:[(0,n.jsx)(G.Z,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),(0,n.jsx)(e3.I,{value:p,onChange:e=>x(e.target.value),placeholder:"Search by name or tradeâ¦",className:"pl-9",autoFocus:!0})]}),v.length>0&&(0,n.jsxs)("div",{className:"flex flex-wrap gap-1.5",children:[(0,n.jsx)("button",{type:"button",onClick:()=>h(null),className:"px-2.5 py-1 rounded-full text-xs font-semibold transition-colors "+(null===b?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground hover:bg-muted/80"),children:"All"}),v.map(e=>(0,n.jsx)("button",{type:"button",onClick:()=>h(e===b?null:e),className:"px-2.5 py-1 rounded-full text-xs font-semibold capitalize transition-colors "+(b===e?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground hover:bg-muted/80"),children:e},e))]}),(0,n.jsx)("div",{className:"max-h-[50vh] overflow-y-auto border rounded-md divide-y",children:u?(0,n.jsxs)("div",{className:"flex items-center justify-center py-10 text-muted-foreground text-sm",children:[(0,n.jsx)(N.Z,{className:"h-4 w-4 animate-spin mr-2"}),"Loading saved groupsâ¦"]}):0===y.length?(0,n.jsxs)("div",{className:"flex flex-col items-center justify-center py-10 text-muted-foreground text-sm gap-2",children:[(0,n.jsx)(T.Z,{className:"h-6 w-6 opacity-50"}),0===d.length?"No saved groups yet. Use the save icon on any group header to save it.":"No matches for that search."]}):y.map(e=>{var t;let r=f===e.id;return(0,n.jsxs)("button",{type:"button",disabled:null!==f,onClick:()=>void j(e),className:"w-full text-left px-4 py-3 hover:bg-accent transition-colors flex items-center gap-3 disabled:opacity-60",children:[(0,n.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,n.jsx)("span",{className:"text-sm font-semibold text-foreground truncate",children:e.name}),e.trade&&(0,n.jsx)("span",{className:"inline-block px-2 py-0.5 rounded-full bg-muted text-[10px] font-semibold uppercase tracking-wide text-muted-foreground capitalize",children:e.trade})]}),(0,n.jsxs)("p",{className:"text-xs text-muted-foreground mt-0.5",children:[e.itemCount," ",1===e.itemCount?"item":"items",e.totalCents>0&&(0,n.jsx)("span",{className:"ml-2 font-medium text-foreground",children:(t=e.totalCents,(0,s.xG)(t/100))})]})]}),r&&(0,n.jsx)(N.Z,{className:"h-4 w-4 animate-spin text-muted-foreground shrink-0"})]},e.id)})})]})})}var t$=r(87354),tY=r(51094),tX=r(40735);let t0={"Payment Terms":"payment-terms",paymentTerms:"payment-terms",contractType:"contract-type",validUntil:"valid-days",validDays:"valid-days",taxRate:"tax-rate",scopeOfWork:"scope-of-work-editor"},t1=["high","advisory","polish"],t5={high:{label:"Important",Icon:i.Z,badge:"bg-destructive/10 text-destructive dark:bg-destructive/20 dark:text-red-400",border:"border-l-2 border-destructive/40 dark:border-destructive/50"},advisory:{label:"Advisory",Icon:tO.Z,badge:"bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-300",border:"border-l-2 border-amber-300 dark:border-amber-600/50"},polish:{label:"Suggestion",Icon:k.Z,badge:"bg-blue-50 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300",border:"border-l-2 border-blue-200 dark:border-blue-700/50"}};function t2(e){let{finding:t,onDismiss:r}=e,s=t5[t.severity],{Icon:a}=s,[l,i]=(0,o.useState)(!1),d=t.field?t0[t.field]:void 0;return(0,n.jsxs)("div",{className:(0,tk.cn)("flex gap-3 rounded-lg px-3 py-2.5","bg-white dark:bg-neutral-900",s.border),children:[(0,n.jsx)(a,{size:15,className:(0,tk.cn)("mt-0.5 shrink-0","high"===t.severity?"text-destructive dark:text-red-400":"advisory"===t.severity?"text-amber-600 dar
1k:text-amber-400":"text-blue-500 dark:text-blue-400"),"aria-hidden":"true"}),(0,n.jsxs)("div",{className:"flex-1 min-w-0 space-y-1",children:[(0,n.jsxs)("div",{className:"flex items-center gap-1.5 flex-wrap",children:[(0,n.jsx)("span",{className:(0,tk.cn)("inline-flex items-center rounded px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wide",s.badge),children:s.label}),t.field&&(0,n.jsx)("span",{className:"text-[11px] text-muted-foreground font-mono",children:t.field})]}),(0,n.jsx)("p",{className:"text-sm text-foreground leading-snug",children:t.message}),t.quote&&(0,n.jsxs)("blockquote",{className:"mt-1 border-l-2 border-muted pl-2 text-[12px] text-muted-foreground italic leading-snug",children:["â",t.quote,"â"]}),t.suggestion&&(0,n.jsxs)("p",{className:"mt-1 text-[12px] text-muted-foreground leading-snug",children:[(0,n.jsx)("span",{className:"font-semibold text-foreground/70",children:"Suggestion: "}),t.suggestion]}),(t.suggestion||d)&&(0,n.jsxs)("div",{className:"mt-1.5 flex flex-wrap items-center gap-3",children:[t.suggestion&&(0,n.jsxs)("button",{type:"button",onClick:()=>{var e;
1t.suggestion&&(null===(e=navigator.clipboard)||void 0===e||e.writeText(t.suggestion).then(()=>{i(!0),setTimeout(()=>i(!1),1500)}).catch(()=>{}))},className:"inline-flex items-center gap-1 text-[11px] font-semibold text-primary hover:underline",children:[l?(0,n.jsx)(t$.Z,{size:12}):(0,n.jsx)(D.Z,{size:12}),l?"Copied":"Copy suggestion"]}),d&&(0,n.jsxs)("button",{type:"button",onClick:()=>{if(!d)return;let e=document.getElementById(d);e&&(e.scrollIntoView({behavior:"smooth",block:"center"}),e.classList.add("ring-2","ring-ring","rounded"),setTimeout(()=>e.classList.remove("ring-2","ring-ring","rounded"),1600))},className:"inline-flex items-center gap-1 text-[11px] font-semibold text-primary hover:underline",children:[(0,n.jsx)(tY.Z,{size:12}),"Go to field"]})]})]}),(0,n.jsx)("button",{type:"button",onClick:()=>r(t.id),"aria-label":"Dismiss finding",className:"ml-1 shrink-0 self-start rounded p-0.5 text-muted-foreground opacity-60 hover:opacity-100 hover:text-foreground transition-opacity focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:(0,n.jsx)(Z.Z,{size:13,"aria-hidden":"true"})})]})}function t3(e){let{open:t,onOpenChange:r,findings:s,summary:a}=e,[l,i]=(0,o.useState)(new Set),d=o.useRef(!1);o.useEffect(()=>{t&&!d.current&&i(new Set),d.current=t},[t]);let c=e=>{i(t=>{let r=new Set(Array.from(t));return r.add(e),r})},u=s.filter(e=>!l.has(e.id)),m=u.filter(e=>"high"===e.severity).length,p=u.filter(e=>"advisory"===e.severity).length,x=u.filter(e=>"polish"===e.severity).length,b=[];m>0&&b.push("".concat(m," important")),p>0&&b.push("".concat(p," ").concat("advisory")),x>0&&b.push("".concat(x," suggestion").concat(1!==x?"s":""));let h=0===u.length?"All findings dismissed":b.join(", ");return t?(0,n.jsxs)("aside",{"aria-label":"Review findings",className:(0,tk.cn)("fixed z-40 flex flex-col bg-white dark:bg-neutral-900 shadow-2xl border border-border dark:border-neutral-700","md:top-0 md:right-0 md:h-full md:w-96 md:border-y-0 md:border-r-0","inset-x-0 bottom-0 max-h-[60vh] rounded-t-2xl md:rounded-none md:inset-x-auto"),children:[(0,n.jsxs)("header",{className:"flex items-center justify-between border-b border-border dark:border-neutral-700 px-4 py-3",children:[(0,n.jsx)("h2",{className:"text-sm font-bold text-foreground",children:"Review findings"}),(0,n.jsx)("button",{type:"button",onClick:()=>r(!1),"aria-label":"Close review findings",className:"rounded p-1 text-muted-foreground hover:text-foreground hover:bg-muted transition-colors",children:(0,n.jsx)(Z.Z,{size:16,"aria-hidden":"true"})})]}),(0,n.jsxs)("div",{className:"flex flex-col min-h-0 flex-1",children:[(0,n.jsx)(tX.n,{variant:0===u.length?"success":m>0?"danger":p>0?"warning":"info",message:0===u.length?"All findings dismissed":h,count:u.length>0?u.length:void 0,className:"rounded-none border-x-0 border-t-0"}),(0,n.jsx)("div",{className:"px-4 pt-3 pb-1",children:(0,n.jsxs)("p",{className:"text-[12px] text-muted-foreground leading-snug",children:["These are ",(0,n.jsx)("span",{className:"font-semibold text-foreground/80",children:"review suggestions only"})," â the tool does not change your estimate. Review each item and make any edits you consider appropriate."]})}),(0,n.jsx)("div",{className:"flex-1 overflow-y-auto px-4 pb-4 pt-2 space-y-4",children:0===u.length?(0,n.jsx)("div",{className:"py-8 text-center",children:(0,n.jsx)("p",{className:"text-sm text-muted-foreground",children:"No remaining findings."})}):t1.map(e=>{let t=u.filter(t=>t.severity===e);if(0===t.length)return null;let r=t5[e];return(0,n.jsxs)("div",{className:"space-y-2",children:[(0,n.jsxs)("h3",{className:"text-[11px] font-bold uppercase tracking-widest text-muted-foreground",children:[r.label,t.length>1?" (".concat(t.length,")"):""]}),t.map(e=>(0,n.jsx)(t2,{finding:e,onDismiss:c},e.id))]},e)})})]})]}):null}function t4(){return Math.random().toString(36).slice(2,9)}function t6(){for(var e=arguments.length,t=Array(e),r=0;r<e;r++)t[r]=arguments[r];return t.filter(Boolean).join(" ")}function t9(e,t,r){return{totalAmountCents:t,currency:"USD",trade:r||null,milestones:e.map(e=>{var t,r,n;return{sequence:e.sequence,label:e.label,amountKind:e.amountKind,percent:null!==(t=e.percent)&&void 0!==t?t:null,fixedAmountCents:null!==(r=e.fixedAmountCents)&&void 0!==r?r:null,triggerKind:e.triggerKind,expectedDueDate:null!==(n=e.expectedDueDate)&&void 0!==n?n:null}})}}function t8(){return{id:t4(),description:"",qty:1,unit:"each",unitPrice:0,cost:0,isOptional:!1,notes:"",taxable:!0,aiGenerated:!1,lineItemType:"labor",materialItemId:void 0,productionRateId:void 0}}function t7(e){var t,r;return!(null===(t=e.description)||void 0===t?void 0:t.trim())&&(1===e.qty||0===e.qty)&&(!e.cost||0===e.cost)&&(!e.unitPrice||0===e.unitPrice)&&!(null===(r=e.notes)||void 0===r?void 0:r.trim())&&(!e.lineItemType||"labor"===e.lineItemType)}let re={due_on_receipt:"Due on Receipt",net_15:"Net 15",net_30:"Net 30",net_45:"Net 45",net_60:"Net 60"},rt={lump_sum:"Lump Sum",time_and_materials:"Time & Materials",unit_price:"Unit Price",cost_plus:"Cost Plus",gmp:"GMP (Guaranteed Max Price)"},rr=[{value:"standard",label:"Standard",description:"Base rate",icon:l.Z,multiplier:1},{value:"priority",label:"Priority",description:"+15%",icon:i.Z,multiplier:1.15}
1,{value:"emergency",label:"Emergency",description:"+25%",icon:d.Z,multiplier:1.25}],rn=["labor","material","equipment","subcontractor","other"];function ro(e){let{children:t,required:r,htmlFor:o}=e;return(0,n.jsxs)("label",{htmlFor:o,className:"block text-[10px] font-semibold uppercase tracking-wider text-muted-foreground mb-1.5",children:[t,r&&(0,n.jsx)("span",{className:"text-destructive ml-0.5",children:"*"})]})}function rs(e){let{value:t,onChange:r,options:o,id:s,className:a}=e;return(0,n.jsx)("select",{id:s,value:t,onChange:r,className:t6("w-full rounded-xl border border-border bg-background px-3.5 py-2.5 text-sm text-foreground appearance-none transition-all duration-200","focus:outline-none focus:ring-2 focus:ring-primary/40 focus:border-primary","bg-[url('data:image/svg+xml;charset=US-ASCII,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2216%22%20height%3D%2216%22%20viewBox%3D%220%200%2024%2024%22%20fill%3D%22none%22%20stroke%3D%22%2364748B%22%20stroke-width%3D%222%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Cpath%20d%3D%22m6%209%206%206%206-6%22%2F%3E%3C%2Fsvg%3E')] bg-[length:16px] bg-[right_12px_center] bg-no-repeat pr-10",a),children:o.map(e=>(0,n.jsx)("option",{value:e.value,children:e.label},e.value))})}let ra=(0,o.forwardRef)(function(e,t){var r,l,i,d,Z,G,q,W,U,z,K,H,J,Q,Y,ee,et,er,en,eo,es,ea,el,ei,ed,ec,eu,em,ep,ex,eb,eh,ef,eg,ev,ej,ek,ew,eC,eS,eI,eE,eT,eD,eF,eM,eB,eq,eW,e_,eU,eK,eV,eH,eJ,eQ,eY,eX,e5,e3,e4,e6,e9,e8,tr,tn,to,ts,ti,td,tc,tN,tk,tw,tC,tS,tO,tM,tZ,tG,tL,tR,tB,tq,t$,tY,tX,t0,t1,t5,t2,ra,ri,rd,rc,ru,rm,rp,rx,rb,rh,rf,rg,rv,ry,rj,rN,rk,rw,rC,rS,rI,rA;let{orgId:rE,estimateId:rT,initialStatus:rP,initialData:rD,branding:rF,mode:rO="edit",viewedAt:rM,lockedAt:rZ,currentVersion:rG,lastRevisionReason:rL,onSave:rR,onAutosave:rB,onSend:rq,onCancel:rW,onCreate:r_,onCreateDraft:rU,onUpdateDraft:rz,onSendDraft:rK,onCreateRevision:rV,onCopyFrom:rH,customerName:rJ,customerId:rQ,propertyLabel:r$,propertyId:rY,projectName:rX,projectId:r0,projectManagerContactId:r1,estimateNumber:r5,pulseAfterSaveExternal:r2,reviewMode:r3=!1}=e,r4="create"===rO,r6=(0,eN.useRouter)(),{user:r9}=(0,tE.a)(),r8=!!(null==r9?void 0:null===(r=r9.featureFlags)||void 0===r?void 0:r.customerAccountV2Enabled),[r7,ne]=(0,o.useState)(!1),[nt,nr]=(0,o.useState)(null),nn=(0,o.useRef)(!1),[no,ns]=(0,o.useState)(!1),na=null!==(ej=null!=rT?rT:nt)&&void 0!==ej?ej:void 0,nl=!!na,ni=r4&&!!rU&&!!rz,nd=(0,o.useRef)([]),[nc,nu]=(0,o.useState)(!1),nm=(0,o.useRef)(null),[np,nx]=(0,o.useState)("estimate"),[nb,nh]=(0,o.useState)(null),[nf,ng]=(0,o.useState)(!1),[nv,ny]=(0,o.useState)(""),[nj,nN]=(0,o.useState)(!1),[nk,nw]=(0,o.useState)(!1),[nC,nS]=(0,o.useState)(!1),[nI,nA]=(0,o.useState)(!1),[nE,nT]=(0,o.useState)(!1),[nP,nD]=(0,o.useState)(!1),[nF,nO]=(0,o.useState)(!1),[nM,nZ]=(0,o.useState)([]),[nG,nL]=(0,o.useState)({high:0,advisory:0,polish:0}),[nR,nB]=(0,o.useState)(!1),[nq,nW]=(0,o.useState)(null),[n_,nU]=(0,o.useState)(""),[nz,nK]=(0,o.useState)(!1),[nV,nH]=(0,o.useState)(!1),[nJ,nQ]=(0,o.useState)(null),[n$,nY]=(0,o.useState)(!1),[nX,n0]=(0,o.useState)(!1),[n1,n5]=(0,o.useState)(null),[n2,n3]=(0,o.useState)(!1),[n4,n6]=(0,o.useState)(!1),[n9,n8]=(0,o.useState)(!1),[n7,oe]=(0,o.useState)(!1),[ot,or]=(0,o.useState)(null),[on,oo]=(0,o.useState)(""),[os,oa]=(0,o.useState)(null),[ol,oi]=(0,o.useState)(null),[od,oc]=(0,o.useState)(null),[ou,om]=(0,o.useState)([]),[op,ox]=(0,o.useState)(!0),[ob,oh]=(0,o.useState)(void 0),[of,og]=(0,o.useState)(null),[ov,oy]=(0,o.useState)(!1),[oj,oN]=(0,o.useState)(null!==(ek=rD.contactId)&&void 0!==ek?ek:null),[ok,ow]=(0,o.useState)(null!==(ew=rD.propertyId)&&void 0!==ew?ew:null),[oC,oS]=(0,o.useState)({contactId:null!==(eC=rD.contactId)&&void 0!==eC?eC:null,serviceContactName:null!==(eS=rD.serviceContactName)&&void 0!==eS?eS:null,serviceContactPhone:null!==(eI=rD.serviceContactPhone)&&void 0!==eI?eI:null}),oI=(0,o.useCallback)(e=>{oS(e),null!==e.contactId&&oN(e.contactId)},[]),oA=(0,o.useCallback)(e=>{ow(e),o1(t=>({...t,propertyId:e}))},[]),[oE,oT]=(0,o.useState)(null),[oP,oD]=(0,o.useState)(r8&&null!==(eT=null!==(eE=null===(l=rD.customer)||void 0===l?void 0:l.id)&&void 0!==eE?eE:rQ)&&void 0!==eT?eT:null),{contacts:oF,properties:oO,loading:oM,refetch:oZ}=(0,tP.tL)(r8?oP:null),[oG,oL]=(0,o.useState)(null);(0,o.useEffect)(()=>
1{if(!r8||!oP){oL(null);return}let e=!1;return fetch("/api/customers/".concat(oP),{credentials:"include"}).then(e=>e.ok?e.json():null).then(t=>{var r,n;e||oL(null!==(n=null==t?void 0:null===(r=t.customer)||void 0===r?void 0:r.customerType)&&void 0!==n?n:null)}).catch(()=>{}),()=>{e=!0}},[r8,oP]);let[oR,oB]=(0,o.useState)({material:35,labor:0,subcontract:15,equipment:15}),oq=!r4&&(0,R.Dk)({lockedAt:rZ,status:rP}),oW=!r4&&!!rM&&!oq,[o_,oU]=(0,o.useState)(()=>{try{let e=localStorage.getItem("estimating-columns-".concat(rE));if(e)return new Set(JSON.parse(e))}catch(e){}return new Set}),oz=(0,o.useCallback)(e=>{oU(e);try{localStorage.setItem("estimating-columns-".concat(rE),JSON.stringify(Array.from(e)))}catch(e){}},[rE]),[oK,oV]=(0,o.useState)([]);(0,o.useEffect)(()=>{r0&&rT&&fetch("/api/crm-estimates?projectId=".concat(r0,"&limit=50"),{credentials:"include"}).then(async e=>{var t;e.ok&&oV((null!==(t=(await e.json()).estimates)&&void 0!==t?t:[]).map(e=>({id:e.id,estimateNumber:e.estimateNumber,title:e.title})))}).catch(()=>{})},[r0,rT]);let oH=(0,o.useCallback)(async()=>{if(!rV)return;let e=nv.trim();if(e){nN(!0);try{await rV(e),ng(!1),ny("")}finally{nN(!1)}}},[rV,nv]);(0,o.useEffect)(()=>{let e=!1;return fetch("/api/organizations/me/trades",{credentials:"include"}).then(e=>e.ok?e.json():null).then(t=>{e||((null==t?void 0:t.trades)&&t.trades.length>0?nQ(t.trades.map(e=>({slug:e.slug,name:e.name}))):nQ(tD.r.map(e=>({slug:e.slug,name:e.label}))))}).catch(()=>{e||nQ(tD.r.map(e=>({slug:e.slug,name:e.label})))}),()=>{e=!0}},[]),(0,o.useEffect)(()=>{let e=!1;return fetch("/api/org-labs",{credentials:"include"}).then(e=>e.ok?e.json():null).then(t=>{var r;e||nY((null==t?void 0:null===(r=t.labs)||void 0===r?void 0:r.assembliesUi)===!0)}).catch(()=>{}),()=>{e=!0}},[]);let oJ=(0,o.useCallback)(e=>{let t={id:e.id,name:e.name,company:e.company,phone:e.phone,email:e.email,address:e.address,lastServiceAddress:e.lastServiceAddress};o1(e=>({...e,customer:t,isNewCustomer:!1})),oN(null),ow(null),oS({contactId:null,serviceContactName:null,serviceContactPhone:null}),og(null),oT(null),r8&&oD(e.id),oy(!0),fetch("/api/customers/".concat(e.id),{credentials:"include"}).then(e=>e.ok?e.json():null).then(e=>{var t,r,n,o,s,a,l,i,d;let c=null!==(t=null==e?void 0:e.customer)&&void 0!==t?t:null;if(og(c),c){let e=null!==(r=c.contacts)&&void 0!==r?r:[],t=null!==(n=c.properties)&&void 0!==n?n:[];1===e.length&&1===t.length?(oN(e[0].id),ow(t[0].id)):(oN(null!==(l=null!==(a=c.primaryContactId)&&void 0!==a?a:null===(o=e[0])||void 0===o?void 0:o.id)&&void 0!==l?l:null),ow(null!==(d=null!==(i=c.primaryPropertyId)&&void 0!==i?i:null===(s=t[0])||void 0===s?void 0:s.id)&&void 0!==d?d:null))}}).catch(()=>{}).finally(()=>oy(!1))},[]),{recipients:oQ,loading:o$}=(0,tP.SP)(r8&&null!=oP?oP:null,r8&&null!=rT?rT:null),[oY,oX]=(0,o.useState)(!r8||!rT);(0,o.useEffect)(()=>{if(!r8||o$)return;let e=oQ.find(e=>"BILLING"===e.role);e&&oT(e.contactId),oX(!0)},[r8,oQ,o$]),(0,o.useEffect)(()=>{r8&&0!==oF.length&&oY&&(oQ.some(e=>"BILLING"===e.role)||oT(e=>e||(0,tP.nH)(oF)))},[r8,oF,oQ,oY]),(0,o.useEffect)(()=>{r8&&0!==oF.length&&ok&&oN(e=>e||(0,tP.lU)(oF,ok,oO))},[r8,ok,oF,oO]);let[o0,o1]=(0,o.useState)({customer:null!==(eD=rD.customer)&&void 0!==eD?eD:null,isNewCustomer:null!==(eF=rD.isNewCustomer)&&void 0!==eF&&eF,newCustomerForm:null!==(eM=rD.newCustomerForm)&&void 0!==eM?eM:{},jobType:null!==(eB=rD.jobType)&&void 0!==eB?eB:"",jobDescription:null!==(eq=rD.jobDescription)&&void 0!==eq?eq:"",urgency:null!==(eW=rD.urgency)&&void 0!==eW?eW:"standard",scopeText:null!==(e_=rD.scopeText)&&void 0!==e_?e_:"",scopeOfWork:null!==(eU=rD.scopeOfWork)&&void 0!==eU?eU:null,scopeSpecs:null!==(eK=rD.scopeSpecs)&&void 0!==eK?eK:[],scopeIncludes:null!==(eV=rD.scopeIncludes)&&void 0!==eV?eV:[],scopeExcludes:null!==(eH=rD.scopeExcludes)&&void 0!==eH?eH:[],lineGroups:rD.lineGroups&&rD.lineGroups.length>0?rD.lineGroups:[{id:t4(),name:"General",collapsed:!1,displayMode:"inherit",items:[t8()]}],paymentTerms:null!==(eJ=rD.paymentTerms)&&void 0!==eJ?eJ:"net_30",contractType:null!==(eQ=rD.contractType)&&void 0!==eQ?eQ:"lump_sum",validDays:null!==(eY=rD.validDays)&&void 0!==eY?eY:30,taxRate:null!==(eX=rD.taxRate)&&void 0!==eX?eX:0,discountAmount:null!==(e5=rD.discountAmount)&&void 0!==e5?e5:0,discountType:null!==(e3=rD.discountType)&&void 0!==e3?e3:"fixed",depositRequired:null!==(e4=rD.depositRequired)&&void 0!==e4&&e4,depositAmount:null!==(e6=rD.depositAmount)&&void 0!==e6?e6:0,depositType:null!==(e9=rD.depositType)&&void 0!==e9?e9:"fixed",customerNotes:null!==(e8=rD.customerNotes)&&void 0!==e8?e8:"",internalNotes:null!==(tr=rD.internalNotes)&&void 0!==tr?tr:"",warrantyText:null!==(tn=rD.warrantyText)&&void 0!==tn?tn:null,financingAvailable:null!==(to=rD.financingAvailable)&&void 0!==to&&to,showQuantity:null===(ts=rD.showQuantity)||void 0===ts||ts,showUnit:null===(ti=rD.showUnit)||void 0===ti||ti,showPrice:null===(td=rD.showPrice)||void 0===td||td,showAmount:null===(tc=rD.showAmount)||void 0===tc||tc,showOrderStatus:null!==(tN=rD.showOrderStatus)&&void 0!==tN&&tN,detailLevel:null!==(tk=rD.detailLevel)&&void 0!==tk?tk:rD.id?null:"grouped_subtotals",contactId:null!==(tw=rD.contactId)&&void 0!==tw?tw:null,propertyId:null!==(tC=rD.propertyId)&&void 0!==tC?tC:null,serviceContactName:null!==(tS=rD.serviceContactName)&&void 0!==tS?tS:null,
1serviceContactPhone:null!==(tO=rD.serviceContactPhone)&&void 0!==tO?tO:null,serviceAddress:null!==(tG=null!==(tZ=null!==(tM=rD.serviceAddress)&&void 0!==tM?tM:null===(i=rD.customer)||void 0===i?void 0:i.lastServiceAddress)&&void 0!==tZ?tZ:null===(d=rD.customer)||void 0===d?void 0:d.address)&&void 0!==tG?tG:""});(0,o.useEffect)(()=>{nm.current=o0},[o0]),(0,o.useEffect)(()=>{let e=rD.primitives;e&&"object"==typeof e&&!Array.isArray(e)?oc(e):oc(null)},[rD.primitives]);let o5=null!==(tL=null===(Z=o0.customer)||void 0===Z?void 0:Z.id)&&void 0!==tL?tL:null,o2=(0,o.useCallback)(()=>{if(!nm.current)return;let e=nd.current;e.length>=10&&e.shift(),e.push(JSON.parse(JSON.stringify(nm.current))),nu(!0)},[]),o3=(0,o.useCallback)(()=>{let e=nd.current.pop();e&&(o1(e),nu(nd.current.length>0))},[]);(0,o.useEffect)(()=>{let e=e=>{if((e.ctrlKey||e.metaKey)&&"z"===e.key){let t=document.activeElement,r=null==t?void 0:t.tagName.toLowerCase();"input"!==r&&"textarea"!==r&&"select"!==r&&0!==nd.current.length&&(e.preventDefault(),o3())}};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[o3]);let o4=(0,o.useCallback)((e,t)=>{o2(),o1(r=>({...r,lineGroups:r.lineGroups.map(r=>r.id===e?{...r,...t}:r)}))},[o2]),o6=(0,o.useCallback)((e,t,r)=>{o2(),o1(n=>({...n,lineGroups:n.lineGroups.map(n=>n.id===e?{...n,items:n.items.map(e=>e.id===t?function(e,t){let r={...e,...t};return B.some(e=>e in t)&&null!=e.lineTotalCents&&(r.lineTotalCents=null),r}(e,r):e)}:n)}))},[o2]),o9=(0,o.useCallback)(e=>{o2(),o1(t=>({...t,lineGroups:t.lineGroups.map(t=>{if(t.id!==e)return t;let r=t.items[t.items.length-1];
1return r&&t7(r)?t:{...t,items:[...t.items,t8()]}})}))},[o2]),o8=(0,o.useCallback)((e,t)=>{o2(),o1(r=>({...r,lineGroups:r.lineGroups.map(r=>r.id===e?{...r,items:r.items.filter(e=>e.id!==t)}:r)}))},[o2]),o7=(0,o.useCallback)(()=>{o2(),o1(e=>({...e,lineGroups:[...e.lineGroups,{id:t4(),name:"New Section",collapsed:!1,displayMode:"inherit",parentGroupId:null,items:[t8()]}]}))},[o2]),se=(0,o.useCallback)(e=>{let t=!1;o1(r=>{let n=t4(),o=[...r.lineGroups.map(e=>{var t;return{id:e.id,parentGroupId:null!==(t=e.parentGroupId)&&void 0!==t?t:null}}),{id:n,parentGroupId:e}];return(0,eR.Zy)(n,e,o).ok?{...r,lineGroups:[...r.lineGroups,{id:n,name:"New Sub-section",collapsed:!1,displayMode:"inherit",parentGroupId:e,items:[t8()]}]}:(t=!0,r)}),t?a.A.error("Max nesting depth is ".concat(eR.BG+1," levels.")):o2()},[o2]),st=(0,o.useCallback)((e,t)=>{let r=null;o1(n=>{let o=n.lineGroups.map(r=>{var n;return{id:r.id,parentGroupId:r.id===e?t:null!==(n=r.parentGroupId)&&void 0!==n?n:null}}),s=(0,eR.Zy)(e,t,n.lineGroups.map(e=>{var t;return{id:e.id,parentGroupId:null!==(t=e.parentGroupId)&&void 0!==t?t:null}}));if(!s.ok)return r=s.reason,n;let a=new Map(o.map(e=>[e.id,e.parentGroupId])),l=e=>{let t=0,r=a.get(e),n=0;for(;null!=r&&n<eR.BG+2;)t++,r=a.get(r),n++;return t};for(let e of o)if(l(e.id)>eR.BG){var i,d;return r='Move would push "'.concat(null!==(d=null===(i=n.lineGroups.find(t=>t.id===e.id))||void 0===i?void 0:i.name)&&void 0!==d?d:"a sub-group",'" past the ').concat(eR.BG+1,"-level limit."),n}return{...n,lineGroups:n.lineGroups.map(r=>r.id===e?{...r,parentGroupId:t}:r)}}),r?a.A.error(r):o2()},[o2]),sr=(0,o.useCallback)(e=>{o2(),o1(t=>{let r=new Set([e]),n=!0;for(;n;)for(let e of(n=!1,t.lineGroups)){var o;let t=null!==(o=e.parentGroupId)&&void 0!==o?o:null;t&&r.has(t)&&!r.has(e.id)&&(r.add(e.id),n=!0)}return{...t,lineGroups:t.lineGroups.filter(e=>!r.has(e.id))}})},[o2]),sn=(0,o.useCallback)(e=>{o2(),o1(t=>{let r={...t,...e};return void 0!==e.detailLevel&&(r.lineGroups=t.lineGroups.map(e=>({...e,displayMode:"inherit"}))),r})},[o2]),so=(0,o.useCallback)((e,t,r)=>{o2(),o1(n=>({...n,lineGroups:n.lineGroups.map(n=>{if(n.id!==e)return n;let o=[...n.items],[s]=o.splice(t,1);return o.splice(r,0,s),{...n,items:o}})}))},[o2]),ss=(0,o.useCallback)((e,t,r,n)=>{o2(),o1(o=>{let s=o.lineGroups.find(t=>t.id===e);if(!s)return o;let a=s.items[t];return a?{...o,lineGroups:o.lineGroups.map(o=>{if(o.id===e)return{...o,items:o.items.filter((e,r)=>r!==t)};if(o.id===r){let e=[...o.items];return e.splice(n,0,a),{...o,items:e}}return o})}:o})},[o2]),sa=(0,o.useCallback)((e,t)=>{o2(),o1(r=>{let n=[...r.lineGroups],[o]=n.splice(e,1);return n.splice(t,0,o),{...r,lineGroups:n}})},[o2]),sl=(0,o.useCallback)((e,t,r,n)=>{o2(),o1(o=>{let s=o.lineGroups.find(t=>t.id===e),a=null==s?void 0:s.items.find(e=>e.id===t);if(!a)return o;let l="isOptional"===r?a.isOptional:a.taxable;return{...o,lineGroups:o.lineGroups.map(t=>"group"===n&&t.id!==e?t:{...t,items:t.items.map(e=>({...e,[r]:l}))})}})},[o2]),si=(0,o.useCallback)(async()=>{if(!na){a.A.error("Save the estimate first, then generate the scope.");return}nT(!0);try{var e,t,r;let n=await fetch("/api/crm-estimates/".concat(na,"/generate-scope"),{method:"POST",credentials:"include"}),o=await n.json();if(!o.ok){a.A.error(null!==(t=({insufficient_line_items:"Add more detail to your line items first, then I can draft the scope.",llm_error:"Couldn't draft the scope right now â try again.",not_found:"Estimate not found."})[null!==(e=o.reason)&&void 0!==e?e:""])&&void 0!==t?t:"Couldn't draft the scope right now â try again.");return}let s=null!==(r=o.scopeOfWork)&&void 0!==r?r:"",l=!!(o0.scopeOfWork&&o0.scopeOfWork.trim().length>0),i=()=>{o1(e=>({...e,scopeOfWork:s||null})),a.A.success("Scope drafted â review and edit before sending.")};l?(0,a.A)("Replace current scope of work?",{action:{label:"Replace",onClick:i},cancel:{label:"Keep current",onClick:()=>{}},duration:8e3}):i()}catch(e){a.A.error("Couldn't draft the scope right now â try again.")}finally{nT(!1)}},[na,o0.scopeOfWork]),sd=(0,o.useCallback)(async()=>{if(!na){a.A.error("Save the estimate first, then review it.");return}nD(!0);try{let t=await fetch("/api/crm-estimates/".concat(na,"/review-estimate"),{method:"POST",credentials:"include"}),r=await t.json();if(!r.ok){var e;a.A.error(null!==(e=({not_found:"Estimate not found."})[r.reason])&&void 0!==e?e:"Couldn't review right now â try again.");return}if(0===r.findings.length){a.A.success("Looks good â no issues found.");return}nZ(r.findings),nL(r.summary),nO(!0)}catch(e){a.A.error("Couldn't review right now â try again.")}finally{nD(!1)}},[na]),sc=(0,o.useCallback)((e,t)=>{o2(),o1(r=>({...r,lineGroups:r.lineGroups.map(r=>{if(r.id!==e)return r;let n=r.items.findIndex(e=>e.id===t);if(-1===n)return r;let o=r.items[n],s={...o,id:t4(),description:o.description?o.description+" (copy)":"",notes:""},a=[...r.items];return a.splice(n+1,0,s),{...r,items:a}})}))},[o2]),su=(0,o.useCallback)((e,t,r)=>{let n={id:t4(),name:e,collapsed:!1,displayMode:"expanded",items:t.map(e=>{var t;return{id:t4(),description:e.description,qty:e.quantity,unit:e.unit||"each",lineItemType:e.lineItemType||"labor",cost:e.priceCents/100,unitPrice:e.priceCents/100,isOptional:!1,notes:"",taxable:!0,aiGenerated:!1,productionRateId:null!==(t=e.productionRateId)&&void 0!==t?t:void 0}})};0===n.items.length&&(n.items=[t8()]),o1(e=>({...e,lineGroups:[...e.lineGroups,n]})),n0(!1),n5(null),nh(null)},[]),sm=(0,o.useCallback)(e=>{var t;n3(!1),or(e.id),oo(null!==(t=e.customerName)&&void 0!==t?t:e.name),oe(!0)},[]),sp=(0,o.useCallback)(async e=>{try{var t,r,n;let o=await fetch("/api/assemblies/".concat(e),{credentials:"include"});if(!o.ok)throw Error("Failed to load assembly details");let s=(await o.json()).assembly;if(s.primitiveType){n5(e),n0(!0);return}let a=null,l=null!==(t=s.trade)&&void 0!==t?t:null;if(l)try{let e=await fetch("/api/trade-rates/".concat(encodeURIComponent(l)),{credentials:"include"});if(e.ok){let t=await e.json();a=null!==(n=null===(r=t.tradeRate)||void 0===r?void 0:r.sellRateCents)&&void 0!==n?n:null}else 404===e.status&&console.error('[expandAssemblyAsGroup] No TradeRate found for trade="'.concat(l,'" â labor items will be $0'))}catch(e){console.error("[expandAssemblyAsGroup] Failed to fetch trade rate â labor items will be $0")}let i={id:t4(),name:s.name,collapsed:!1,displayMode:"expanded",items:(s.lineItems||[]).map(e=>{var t,r;let n=null!==(t=e.quantity)&&void 0!==t?t:1,o=0;return null!=e.costCents?o=e.costCents/100:(null!==(r=e.minutesPerUnit)&&void 0!==r?r:0)>0&&null!=a&&a>0&&(o=Math.round(e.minutesPerUnit/60*n*(a/100)*100)/100),{id:t4(),description:e.description,qty:n,unit:e.unit||"each",lineItemType:e.lineItemType||"labor",materialItemId:e.materialItemId||void 0,productionRateId:e.productionRateId||void 0,cost:o,unitPrice:o,isOptional:e.isOptional||!1,notes:e.notes||"",taxable:!0,aiGenerated:!1}})};0===i.items.length&&(i.items=[t8()]),o1(e=>({...e,lineGroups:[...e.lineGroups,i]}))}catch(e){console.error("Failed to load assembly details")}nh(null)}
1,[]),sx=(0,o.useCallback)(e=>{n3(!1),sp(e.id)},[sp]),sb=(0,o.useCallback)(e=>{let t=e.map(e=>({id:t4(),name:e.name,collapsed:!1,displayMode:"expanded",items:e.items.map(e=>({id:t4(),description:e.description,qty:e.quantity,unit:e.unit||"each",unitPrice:e.unitPrice,cost:0,isOptional:!1,notes:"",taxable:!0,aiGenerated:!1,lineItemType:"material"}))}));o1(e=>({...e,lineGroups:[...e.lineGroups,...t]}))},[]),sh=(0,o.useCallback)(e=>{var t;if(!e$.xf)return;let r=null==od?void 0:od[e];if(!r)return;let n=o0.lineGroups.find(t=>t.id===e),o=null!==(t=null==n?void 0:n.name)&&void 0!==t?t:"Assembly";(0,a.A)("This will replace all lines in this section, including any manual edits.",{duration:8e3,action:{label:"Edit parameters",onClick:()=>{oa(e),oi(r.primitiveInputs),or(r.sourceAssemblyId),oo(o),oe(!0)}},cancel:{label:"Cancel",onClick:()=>{}}})},[od,o0.lineGroups]),sf=(0,o.useCallback)((e,t)=>{if(oq)return null;let r=o0.lineGroups.find(t=>t.id===e);return r?(0,n.jsx)("button",{type:"button",title:"Save group as reusable",onClick:t=>{t.stopPropagation(),nW(e),nU(r.name),nB(!0)},className:"inline-flex items-center justify-center w-6 h-6 rounded text-muted-foreground hover:text-primary hover:bg-muted transition-colors",children:(0,n.jsx)(c.Z,{size:13})}):null},[oq,o0.lineGroups]),sg=(0,o.useCallback)((e,t,r)=>{if("assembly"===r.source&&r.id){sp(r.id);return}let n="material"===r.source,o=r.unitPrice,s=n?(0,$.Eb)(o,oR.material):r.unitPrice;o6(e,t,{description:r.description,unit:r.unit||"each",unitPrice:s,...n?{cost:o}:{},lineItemType:r.lineItemType,materialItemId:r.materialItemId,productionRateId:r.productionRateId,materialFamilyId:r.materialFamilyId,materialVariantId:r.materialVariantId,materialVariantPriceCentsSnapshot:r.materialVariantPriceCentsSnapshot}),nh(null)},[o6,sp,oR.material]),sv=(0,o.useCallback)((e,t)=>{if("assembly"===t.source&&t.id){sp(t.id);return}let r="material"===t.source,n=t.unitPrice,o=r?(0,$.Eb)(n,oR.material):t.unitPrice,s={...t8(),description:t.description,unit:t.unit||"each",unitPrice:o,cost:r?n:0,lineItemType:t.lineItemType,materialItemId:t.materialItemId,productionRateId:t.productionRateId,materialFamilyId:t.materialFamilyId,materialVariantId:t.materialVariantId,materialVariantPriceCentsSnapshot:t.materialVariantPriceCentsSnapshot};o1(t=>({...t,lineGroups:t.lineGroups.map(t=>t.id===e?{...t,items:[...t.items,s]}:t)})),nh(null)},[sp,oR.material]),sy=(0,o.useMemo)(()=>{var e;let t=(null===(e=rr.find(e=>e.value===o0.urgency))||void 0===e?void 0:e.multiplier)||1,r=0,n=0,o={labor:{count:0,revenue:0},material:{count:0,revenue:0},equipment:{count:0,revenue:0},subcontractor:{count:0,revenue:0},other:{count:0,revenue:0}};for(let e of o0.lineGroups)for(let t of e.items)if(!t.isOptional){let e=null!=t.lineTotalCents?t.lineTotalCents/100:t.qty*t.unitPrice;r+=e,n+=t.qty*t.cost;let s=t.lineItemType||"labor";o[s].count+=1,o[s].revenue+=e}let s=rn.filter(e=>o[e].count>0).map(e=>({type:e,count:o[e].count,revenue:o[e].revenue})),a=r,l=a*t,i=o0.taxRate/100*l,d="fixed"===o0.discountType?o0.discountAmount:o0.discountAmount/100*l,c=l+i-d,u=o0.depositRequired?"fixed"===o0.depositType?o0.depositAmount:o0.depositAmount/100*c:0,m=a-n;return{rawSubtotal:a,adjustedSubtotal:l,urgencyPremium:l-a,taxAmount:i,discountValue:d,total:c,depositValue:u,balanceDue:c-u,cost:n,profit:m,margin:a>0?m/a*100:0,breakdown:s}},[o0]),sj=(0,o.useCallback)(()=>{var e,t,r,n;return{...o0,contactId:null!==(n=null!==(r=oC.contactId)&&void 0!==r?r:oj)&&void 0!==n?n:null,propertyId:null!=ok?ok:null,serviceContactName:(null===(e=oC.serviceContactName)||void 0===e?void 0:e.trim())||null,serviceContactPhone:(null===(t=oC.serviceContactPhone)||void 0===t?void 0:t.trim())||null}},[o0,oC,oj,ok]),sN=(0,o.useCallback)((e,t)=>{r8&&oE&&fetch("/api/customers/".concat(t,"/estimates/").concat(e,"/recipients"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({contactId:oE,role:"BILLING"})}).catch(()=>{})},[r8,oE]),sk=(0,o.useCallback)(async()=>{var e,t;if(r4&&!o5){a.A.error("Select a customer before saving");return}ne(!0);try{if(r4){if(na&&rz)await rz(na,sj()),o5&&sN(na,o5);else if(ni&&o5&&!nn.current){nn.current=!0,ns(!1);try{let e=await rU(sj());e?(nr(e),sN(e,o5)):(ns(!0),nn.current=!1)}catch(e){throw ns(!0),nn.current=!1,e}}else r_&&await r_(sj(),!1)}else rR&&(await rR(sj()),rT&&(null===(e=o0.customer)||void 0===e?void 0:e.id)&&sN(rT,o0.customer.id))}catch(r){let e=(0,R.AW)(r);e?a.A.error(e.message,e.href?{action:{label:null!==(t=e.label)&&void 0!==t?t:"Create change order",onClick:()=>{window.location.href=e.href}}}:void 0):a.A.error(r instanceof Error?r.message:"Save failed")}finally{ne(!1)}},[sj,r4,na,rz,rU,ni,o5,r_,rR,sN,rT,null===(G=o0.customer)||void 0===G?void 0:G.id]),sw=(0,o.useRef)(null);(0,o.useEffect)(()=>{null===sw.current&&(sw.current=JSON.stringify(sj()))}),(0,o.useImperativeHandle)(t,()=>({submit:async()=>{ne(!0);try{if(r4){if(na&&rz)await rz(na,sj());else if(ni&&o5&&!nn.current){nn.current=!0;let e=await rU(sj());e?nr(e):nn.current=!1}else r_&&await r_(sj(),!1)}else rR&&await rR(sj());return{ok:!0}}catch(e){return{ok:!1,error:e instanceof Error?e.message:"Save failed"}}finally{ne(!1)}},getCurrentValues:()=>sj(),isDirty:()=>null!==sw.current&&sw.current!==JSON.stringify(sj()),selectCustomer:e=>
1{oJ({id:e.id,name:e.name,company:e.company,phone:e.phone,email:e.email,address:e.address,lastServiceAddress:e.lastServiceAddress})},addLineItem:e=>{o1(t=>{var r;let n={id:t4(),description:e.description,qty:"number"==typeof e.quantity?e.quantity:1,unit:null!==(r=e.unit)&&void 0!==r?r:"each",unitPrice:"number"==typeof e.unitPrice?e.unitPrice:0,cost:"number"==typeof e.unitPrice&&"number"==typeof e.quantity?e.unitPrice*e.quantity:0,isOptional:!1,notes:"",taxable:!0,aiGenerated:!0,lineItemType:"labor"};if(0===t.lineGroups.length)return{...t,lineGroups:[{id:t4(),name:"Brion Items",collapsed:!1,displayMode:"expanded",items:[n]}]};let[o,...s]=t.lineGroups;return{...t,lineGroups:[{...o,items:[...o.items,n]},...s]}})},setField:(e,t)=>{o1(r=>({...r,[e]:t}))},setLineGroups:e=>{e&&0!==e.length&&o1(t=>({...t,lineGroups:e.map(e=>{var t;return{id:e.id,name:e.name,collapsed:e.collapsed,displayMode:e.displayMode,parentGroupId:null!==(t=e.parentGroupId)&&void 0!==t?t:null,items:e.items.map(e=>({id:e.id,description:e.description,qty:e.qty,unit:e.unit,unitPrice:e.unitPrice,cost:e.cost,isOptional:e.isOptional,notes:e.notes,taxable:e.taxable,aiGenerated:e.aiGenerated,lineItemType:e.lineItemType}))}})}))}}),[sj,oJ,r4,r_,rR,na,rz,rU,ni,o5]);let sC=nl&&!oq&&!r7,sS=function(e){let{hasPersisted:t,isLocked:r,isSaving:n,hasCustomer:o,draftCreateFailed:s,isCreatingDraft:a}=e;return t?r?"Saved \xb7 locked":n?"Savingâ¦":"Saved":o?s?"Couldn't start draft \xb7 keep editing":a?"Saving draftâ¦":"Draft â not saved yet":"Pick a customer to start the draft"}({hasPersisted:nl,isLocked:oq,isSaving:r7,hasCustomer:!!o0.customer,draftCreateFailed:no,isCreatingDraft:nn.current}),sI=(0,o.useMemo)(()=>JSON.stringify({lineGroups:o0.lineGroups,jobType:o0.jobType,jobDescription:o0.jobDescription,urgency:o0.urgency,validDays:o0.validDays,taxRate:o0.taxRate,discountAmount:o0.discountAmount,discountType:o0.discountType,depositRequired:o0.depositRequired,depositAmount:o0.depositAmount,depositType:o0.depositType,customerNotes:o0.customerNotes,internalNotes:o0.internalNotes,paymentTerms:o0.paymentTerms,contractType:o0.contractType,financingAvailable:o0.financingAvailable,scopeOfWork:o0.scopeOfWork,scopeSpecs:o0.scopeSpecs,scopeIncludes:o0.scopeIncludes,scopeExcludes:o0.scopeExcludes,showQuantity:o0.showQuantity,showUnit:o0.showUnit,showPrice:o0.showPrice,showAmount:o0.showAmount,showOrderStatus:o0.showOrderStatus,detailLevel:o0.detailLevel,contactId:oj,propertyId:ok}),[o0.lineGroups,o0.jobType,o0.jobDescription,o0.urgency,o0.validDays,o0.taxRate,o0.discountAmount,o0.discountType,o0.depositRequired,o0.depositAmount,o0.depositType,o0.customerNotes,o0.internalNotes,o0.paymentTerms,o0.contractType,o0.financingAvailable,o0.scopeOfWork,o0.scopeSpecs,o0.scopeIncludes,o0.scopeExcludes,o0.showQuantity,o0.showUnit,o0.showPrice,o0.showAmount,o0.showOrderStatus,o0.detailLevel,oj,ok]),sA=(0,o.useCallback)(async()=>{if(r4){na&&rz?await rz(na,sj()):r_&&await r_(sj(),!1);return}let e=null!=rB?rB:rR;e&&await e(sj())},[sj,r4,na,rz,r_,rB,rR]),{state:sE,retry:sT}=(0,L.G)({enabled:sC,payload:sI,onSave:sA,debounceMs:1500,disabledReason:sS}),sP=(0,o.useRef)(null);(0,o.useEffect)(()=>{if("error"!==sE.kind){sP.current=null;return}sP.current!==sE.message&&(sP.current=sE.message,a.A.error(sE.message||"Couldn't save your changes",{description:"Your last edit may not be saved â tap Retry in the header."}))},[sE]),(0,o.useEffect)(()=>{ni&&o5&&!na&&(nn.current||(nn.current=!0,ns(!1),(async()=>{try{let e=await rU(sj());e?nr(e):(ns(!0),nn.current=!1)}catch(e){a.A.error(e instanceof Error?e.message:"Could not start draft"),ns(!0),nn.current=!1}})()))},[ni,o5,na]),(0,o.useEffect)(()=>{let e=e=>{if(oq)return;let t=null!==sw.current&&sw.current!==JSON.stringify(sj());(r4&&!nl&&(t||o0.customer)||"pending"===sE.kind||"error"===sE.kind)&&(e.preventDefault(),e.returnValue="")};return window.addEventListener("beforeunload",e),()=>window.removeEventListener("beforeunload",e)},[r4,oq,nl,sj,sE.kind,o0.customer]);let sD=(0,o.useCallback)(async()=>{ne(!0);try{r4?na&&rK?await rK(na,sj()):r_&&await r_(sj(),!0):rq&&await rq(sj())}catch(e){a.A.error(e instanceof Error?e.message:"Send failed")}finally{ne(!1)}},[sj,r4,na,rK,r_,rq]),sF=(0,o.useMemo)(()=>{let e={labor:{count:0,cost:0},material:{count:0,cost:0},equipment:{count:0,cost:0},subcontractor:{count:0,cost:0},other:{count:0,cost:0}};for(let t of o0.lineGroups)for(let r of t.items)if(!r.isOptional){let t=r.lineItemType||"labor";e[t]&&(e[t].count+=1,e[t].cost+=r.qty*r.cost)}return{revenue:sy.rawSubtotal,cost:sy.cost,profit:sy.profit,margin:sy.margin,byCostType:e,rawSubtotal:sy.rawSubtotal,adjustedSubtotal:sy.adjustedSubtotal,urgencyPremium:sy.urgencyPremium,taxAmount:sy.taxAmount,discountValue:sy.discountValue,total:sy.total,depositValue:sy.depositValue,balanceDue:sy.balanceDue}},[o0.lineGroups,sy]),sO=(0,o.useMemo)(()=>
1{if(0===ou.length)return null;let e=ou.length,t=ou[0],r=ou[e-1],n=e=>"PERCENT"===e.amountKind&&null!=e.percent?(0,s.DW)(e.percent):"FIXED_CENTS"===e.amountKind&&null!=e.fixedAmountCents&&sy.total>0?Math.round(e.fixedAmountCents/100/sy.total*100):0;return{summary:2===e?"".concat(n(t),"% deposit + ").concat(n(r),"% on completion"):1===e?"".concat(n(t),"% on completion"):"".concat(e," milestones"),complianceState:void 0,isCompliant:void 0}},[ou,sy.total]),sM=(0,o.useRef)(!1),sZ=(0,o.useRef)("");(0,o.useEffect)(()=>{!sM.current&&na&&(sM.current=!0,fetch("/api/payment-schedules/".concat(na),{credentials:"include"}).then(e=>e.ok?e.json():null).then(e=>{var t;let r=null==e?void 0:null===(t=e.schedule)||void 0===t?void 0:t.milestones;if(!Array.isArray(r)||0===r.length)return;let n=r.map((e,t)=>{var r,n,o;return{id:"loaded-".concat(null!==(r=e.sequence)&&void 0!==r?r:t),sequence:Number(null!==(n=e.sequence)&&void 0!==n?n:t),label:String(null!==(o=e.label)&&void 0!==o?o:""),amountKind:"FIXED_CENTS"===e.amountKind?"FIXED_CENTS":"PERCENT",percent:null==e.percent?null:Number(e.percent),fixedAmountCents:null==e.fixedAmountCents?null:Number(e.fixedAmountCents),triggerKind:"ON_ESTIMATE_SIGN"===e.triggerKind?"ON_ESTIMATE_SIGN":"MANUAL",expectedDueDate:null==e.expectedDueDate?null:String(e.expectedDueDate)}});sZ.current=JSON.stringify(t9(n,Math.round(100*sy.total),o0.jobType||null)),om(n)}).catch(()=>{}))},[na]),(0,o.useEffect)(()=>{if(!na||0===ou.length)return;let e=JSON.stringify(t9(ou,Math.round(100*sy.total),o0.jobType||null));if(e===sZ.current)return;let t=setTimeout(()=>{fetch("/api/payment-schedules/".concat(na),{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:e}).then(t=>{t.ok?sZ.current=e:t.json().then(e=>console.warn("[payment-schedule] save rejected",e)).catch(()=>{})}).catch(()=>{})},1200);return()=>clearTimeout(t)},[ou,na,sy.total,o0.jobType]);let sG=(0,o.useMemo)(()=>{var e,t,r;if(!o0.customer)return null;let n=oj?null==of?void 0:null===(e=of.contacts)||void 0===e?void 0:e.find(e=>e.id===oj):void 0,o=n?{name:[n.firstName,n.lastName].filter(Boolean).join(" "),title:n.isPrimary?"Primary contact":void 0,email:null!==(t=n.email)&&void 0!==t?t:void 0,phone:null!==(r=n.phone)&&void 0!==r?r:void 0}:o0.customer.email||o0.customer.phone?{name:o0.customer.name,title:o0.customer.company?"Primary contact":void 0,email:o0.customer.email,phone:o0.customer.phone}:void 0;return{id:o0.customer.id,displayName:o0.customer.name,address:o0.customer.address,primaryContact:o}},[o0.customer,oj,of]),sL=(0,o.useMemo)(()=>{var e,t;return null!==(t=null===(e=(null!=nJ?nJ:tD.r.map(e=>({slug:e.slug,name:e.label}))).find(e=>e.slug===o0.jobType))||void 0===e?void 0:e.name)&&void 0!==t?t:o0.jobType},[o0.jobType,nJ]),sR=(0,o.useMemo)(()=>e$.TC?o0.lineGroups.flatMap(e=>e.items.map(e=>e.productionRateId).filter(e=>!!e)):[],[o0.lineGroups]),{hints:sB}=(0,tj.rz)(sR),sq=(0,o.useCallback)((e,t)=>{var r;if(!e$.TC||oq)return null;let o=null===(r=o0.lineGroups.find(t=>t.id===e))||void 0===r?void 0:r.items.find(e=>e.id===t);if(!(null==o?void 0:o.productionRateId))return null;let s=sB.get(o.productionRateId);return s?(0,n.jsx)(tI,{taskLabel:o.description||s.rate.taskName,unit:s.rate.unit,catalogMinutesPerUnit:s.catalog,learnedMinutesPerUnit:s.learned,variancePct:s.variancePct,sampleSize:s.sampleSize,confidence:s.confidence,onApplyToEstimate:()=>{let r=s.learned/s.catalog;o6(e,t,{unitPrice:Math.round(o.unitPrice*r*100)/100})},onApplyAsOrgDefault:async()=>{await (0,tA.Y)(s.rate,s.learned)}}):null},[o0.lineGroups,sB,oq,o6]),sW=null!==(tB=null!=r$?r$:ok?null!==(tR=null==of?void 0:null===(W=of.properties)||void 0===W?void 0:null===(q=W.find(e=>e.id===ok))||void 0===q?void 0:q.label)&&void 0!==tR?tR:null==of?void 0:null===(z=of.properties)||void 0===z?void 0:null===(U=z.find(e=>e.id===ok))||void 0===U?void 0:U.address:void 0)&&void 0!==tB?tB:void 0,s_=(()=>{let e=(null!=sL?sL:"").trim();return e&&"estimate"!==e.toLowerCase()?/estimate$/i.test(e)?e:"".concat(e," Estimate"):r4?"New Estimate":"Estimate"})(),sU=na&&!r4?async()=>{if(!r7){ne(!0);try{var e;let t=await fetch("/api/crm-estimates/".concat(na,"/convert"),{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({skipBillPrep:!0})});if(400===t.status){let e=await t.json().catch(()=>({}
1)),r="string"==typeof(null==e?void 0:e.error)?e.error:"Estimate must be approved or signed before converting.";a.A.error(r);return}if(!t.ok){let e=await t.json().catch(()=>({}));a.A.error("string"==typeof(null==e?void 0:e.error)?e.error:"Convert failed (".concat(t.status,")"));return}let r=await t.json(),n=null==r?void 0:null===(e=r.invoice)||void 0===e?void 0:e.id;a.A.success("Invoice created!"),n?window.location.href="/invoices/".concat(n):window.location.href="/invoices"}catch(e){a.A.error(e instanceof Error?e.message:"Convert to invoice failed")}finally{ne(!1)}}}:void 0,sz=na&&!r4?async()=>{if(!r7){ne(!0);try{var e;let t=await fetch("/api/work-orders/from-estimate/".concat(na),{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({})});if(!t.ok){let e=await t.json().catch(()=>({}));a.A.error("string"==typeof(null==e?void 0:e.error)?e.error:"Generate work order failed (".concat(t.status,")"));return}let r=await t.json(),n=null==r?void 0:null===(e=r.workOrder)||void 0===e?void 0:e.id;a.A.success("Work order created!"),n?window.location.href="/work-orders/".concat(n):window.location.href="/work-orders"}catch(e){a.A.error(e instanceof Error?e.message:"Generate work order failed")}finally{ne(!1)}}}:void 0,sK="approved"===rP||"signed"===rP,sV=function(){let[e,t]=(0,o.useState)(()=>(function(){try{let e=window.localStorage.getItem(tb);if(!e)return new Set;let t=JSON.parse(e);if(!Array.isArray(t))return new Set;return new Set(t.filter(tg))}catch(e){return new Set}})()),[r,n]=(0,o.useState)(()=>"true"===window.localStorage.getItem(tf)),s=(0,o.useCallback)(e=>{t(t=>{let r=new Set(t);return r.has(e)?r.delete(e):r.add(e),tv(r),r})},[]),a=(0,o.useCallback)(()=>{let e=new Set(tx.map(e=>e.key));t(e),tv(e);try{{let e=function(){let e=window.localStorage.getItem(th),t=e?parseInt(e,10):0;return Number.isFinite(t)?t:0}()+1;window.localStorage.setItem(th,String(e)),e>=2&&(window.localStorage.setItem(tf,"true"),n(!0))}}catch(e){}},[]),l=(0,o.useCallback)(function(t){let n=arguments.length>1&&void 0!==arguments[1]&&arguments[1];return r||n||e.has(t)},[r,e]);return{fullLayout:r,expandedKeys:e,isExpanded:l,toggleSection:s,expandAll:a}}(),[sH,sJ]=(0,o.useState)(!1),[sQ,s$]=(0,o.useState)(!1),sY=!!(o0.scopeOfWork||(null!==(tq=null===(K=o0.scopeSpecs)||void 0===K?void 0:K.length)&&void 0!==tq?tq:0)>0||(null!==(t$=null===(H=o0.scopeIncludes)||void 0===H?void 0:H.length)&&void 0!==t$?t$:0)>0||(null!==(tY=null===(J=o0.scopeExcludes)||void 0===J?void 0:J.length)&&void 0!==tY?tY:0)>0),sX={options:sH,scope:sY,photos:sQ,terms:!1,markup:!1,urgency:!1},s0=e$.Qq?{options:sV.isExpanded("options",sH),scope:sV.isExpanded("scope",sY),photos:sV.isExpanded("photos",sQ),terms:sV.isExpanded("terms"),markup:sV.isExpanded("markup"),urgency:sV.isExpanded("urgency")}:{options:!0,scope:!0,photos:!0,terms:!0,markup:!0,urgency:!0},s1=tx.map(e=>({key:e.key,label:e.label,expanded:s0[e.key],hasContent:sX[e.key]})),s5=null!==(t1=null!==(t0=null!==(tX=null===(Q=o0.customer)||void 0===Q?void 0:Q.id)&&void 0!==tX?tX:rQ)&&void 0!==t0?t0:oP)&&void 0!==t1?t1:void 0,s2=o0.lineGroups.some(e=>e.items.some(e=>!t7(e)&&e.unitPrice>0)),s3=e$.Qq?[...oq?[]:[{label:r4?"Save draft":"draft"===rP?"Save":"Save Changes",icon:u.Z,onClick:sk,disabled:r7}],...sU?[{label:"Convert to Invoice",icon:m.Z,onClick:sU,disabled:!sK,description:sK?void 0:"Approve or sign the estimate first"}]:[],...sz?[{label:"Generate Work Order",icon:p.Z,onClick:sz,disabled:!sK,description:sK?void 0:"Approve or sign the estimate first"}]:[],...oq&&rV?[{label:"Create Revision",icon:x.Z,onClick:()=>ng(!0)}]:[],...oq?[]:[{label:"Undo",icon:b.Z,onClick:o3,disabled:!nc}],{label:"Add Task",icon:h.Z,onClick:()=>a.A.info("Tasks linked to estimates â coming soon."),disabled:!0,description:"Coming soon"},{label:"Message",icon:f.Z,onClick:()=>a.A.info("Customer messaging from the estimate page â coming soon."),disabled:!0,description:"Coming soon"},{label:"Files",icon:g.Z,onClick:()=>a.A.info("Estimate file attachments â coming soon."),disabled:!0,description:"Coming soon"},{label:"More",icon:v.Z,onClick:()=>a.A.info("More actions menu â coming soon."),disabled:!0,description:"Coming soon"}]:[];return(0,n.jsxs)("div",{className:"min-h-screen bg-background text-foreground",style:{fontFamily:"'Montserrat', system-ui, sans-serif"},children:[(0,n.jsx)(V,{customerName:null!==(t5=null!=rJ?rJ:null===(Y=o0.customer)||void 0===Y?void 0:Y.name)&&void 0!==t5?t5:void 0,customerId:null!==(t2=null!=rQ?rQ:null===(ee=o0.customer)||void 0===ee?void 0:ee.id)&&void 0!==t2?t2:void 0,propertyLabel:sW,projectName:null!=rX?rX:r4?"New Estimate (draft)":void 0,projectId:r0,estimateNumber:null!=r5?r5:r4?"DRAFT":void 0,estimateId:na,siblings:oK,currentEstimateId:na,pulseAfterSave:null!=r2?r2:ob,onRenameProject:r0?async e=>{let t=await fetch("/api/crm-projects/".concat(r0),{method:"PATCH",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({name:e})});if(!t.ok){let e=await t.json().catch(()=>({}
1)),r="string"==typeof(null==e?void 0:e.error)?e.error:"";return 409===t.status||r.includes("P2002")||r.toLowerCase().includes("already")?{error:"Name already used. Try a different name."}:{error:r||"Rename failed"}}oh(Date.now()),setTimeout(()=>oh(void 0),1600)}:void 0}),"estimate"===np&&e$.Qq&&(0,n.jsx)(ey,{title:s_,customerName:null!==(ra=null!=rJ?rJ:null===(et=o0.customer)||void 0===et?void 0:et.name)&&void 0!==ra?ra:void 0,addressLabel:null!==(ri=null!=sW?sW:o0.serviceAddress)&&void 0!==ri?ri:void 0,status:rP,estimateNumber:r5,isCreateMode:r4,isSaving:r7,isLocked:oq,autosaveState:sE,onAutosaveRetry:sT,urgency:o0.urgency,onBack:rW,onSend:()=>nH(!0),onPreview:()=>nH(!0),overflowItems:s3,subtotal:sy.rawSubtotal,taxAmount:sy.taxAmount,discountValue:sy.discountValue,total:sy.total,contacts:r8?oF:void 0,customerId:null!=oP?oP:void 0,customerType:oG,property:r8?null!==(rd=oO.find(e=>e.id===ok))&&void 0!==rd?rd:null:void 0,projectManagerContactId:r1,onContactsChanged:oZ,remainingRequiredCount:(s5?0:1)+(s2?0:1)}),"estimate"===np&&!e$.Qq&&(0,n.jsx)(X,{title:s_,status:rP,estimateNumber:r5,estimateId:na,totalRevenue:sy.rawSubtotal,currentVersion:rG,lastRevisionReason:rL,isSaving:r7,isLocked:oq,isCreateMode:r4,autosaveState:sE,onAutosaveRetry:sT,onSend:()=>nH(!0),onPreview:()=>nH(!0),onConvertToInvoice:na&&!r4?async()=>{if(!r7){ne(!0);try{var e;let t=await fetch("/api/crm-estimates/".concat(na,"/convert"),{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({skipBillPrep:!0})});if(400===t.status){let e=await t.json().catch(()=>({})),r="string"==typeof(null==e?void 0:e.error)?e.error:"Estimate must be approved or signed before converting.";a.A.error(r);return}if(!t.ok){let e=await t.json().catch(()=>({}));a.A.error("string"==typeof(null==e?void 0:e.error)?e.error:"Convert failed (".concat(t.status,")"));return}let r=await t.json(),n=null==r?void 0:null===(e=r.invoice)||void 0===e?void 0:e.id;a.A.success("Invoice created!"),n?window.location.href="/invoices/".concat(n):window.location.href="/invoices"}catch(e){a.A.error(e instanceof Error?e.message:"Convert to invoice failed")}finally{ne(!1)}}}:void 0,onGenerateWO:na&&!r4?async()=>{if(!r7){ne(!0);try{var e;let t=await fetch("/api/work-orders/from-estimate/".concat(na),{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({})});if(!t.ok){let e=await t.json().catch(()=>({}));a.A.error("string"==typeof(null==e?void 0:e.error)?e.error:"Generate work order failed (".concat(t.status,")"));return}let r=await t.json(),n=null==r?void 0:null===(e=r.workOrder)||void 0===e?void 0:e.id;a.A.success("Work order created!"),n?window.location.href="/work-orders/".concat(n):window.location.href="/work-orders"}catch(e){a.A.error(e instanceof Error?e.message:"Generate work order failed")}finally{ne(!1)}}}:void 0,onAddTask:()=>a.A.info("Tasks linked to estimates â coming soon."),addTaskDisabled:!0,onMessage:()=>{a.A.info("Customer messaging from the estimate page â coming soon.")},messageDisabled:!0,onFiles:()=>a.A.info("Estimate file attachments â coming soon."),filesDisabled:!0,onMore:()=>a.A.info("More actions menu â coming soon."),moreDisabled:!0,onSave:oq?void 0:sk,onCancel:rW,onCreateRevision:oq&&rV?()=>ng(!0):void 0,onUndo:oq?void 0:o3,canUndo:nc}),"estimate"===np&&oq&&(0,n.jsx)("div",{className:"bg-violet-50 dark:bg-violet-950/40 border-b border-violet-200 dark:border-violet-700",children:(0,n.jsxs)("div",{className:"px-4 sm:px-6 py-2.5 flex items-start sm:items-center gap-3",children:[(0,n.jsx)("div",{className:"w-7 h-7 rounded-full bg-violet-600 dark:bg-violet-500 text-white flex items-center justify-center flex-shrink-0",children:(0,n.jsx)(y.Z,{className:"w-3.5 h-3.5"})}),(0,n.jsxs)("div",{className:"text-xs text-violet-800 dark:text-violet-300 leading-relaxed flex-1",children:[(0,n.jsx)("span",{className:"font-bold",children:"Locked"})," ","â","signed"===rP&&" customer signed this estimate. ","approved"===rP&&" customer approved this estimate. ","rejected"===rP&&" customer declined this estimate. ","converted"===rP&&" this estimate has been converted to an invoice. ","Click ",(0,n.jsx)("span",{className:"font-bold",children:"Create Revision"})," to start a new editable version."]})]})}),"estimate"===np&&oW&&!oq&&(0,n.jsx)("div",{className:"bg-amber-50 dark:bg-amber-950/40 border-b border-amber-200 dark:border-amber-700",children:(0,n.jsxs)("div",{className:"px-4 sm:px-6 py-2 flex items-start sm:items-center gap-3",children:[(0,n.jsx)(j.Z,{className:"w-4 h-4 text-amber-700 dark:text-amber-300 flex-shrink-0"}),(0,n.jsxs)("div",{className:"text-xs text-amber-800 dark:text-amber-300 leading-relaxed flex-1",children:["Customer viewed this estimate on"," ",(0,n.jsx)("span",{className:"font-bold",children:new Date(rM).toLocaleDateString(void 0,{dateStyle:"medium"})}),". Consider sending a revision if scope or price changed materially."]}),rV&&(0,n.jsxs)("button",{type:"button",onClick:()=>ng(!0),className:"inline-flex items-center gap-1 px-2.5 py-1 rounded-lg bg-card border border-amber-200 dark:border-amber-700 text-amber-800 dark:text-amber-300 text-[11px] font-semibold hover:bg-amber-50 dark:hover:bg-amber-950/40 transition-colors flex-shrink-0",children:[(0,n.jsx)(x.Z,{className:"w-3 h-3"}),"Revise instead"]})]})}),(0,n.jsx)(eA,{projectId:r0,activeTab:np,onTabSelect:nx}),"estimate"!==np&&r0&&(0,n.jsxs)("div",{className:"px-6 pt-4 pb-8 min-h-[400px]",children:["schedule"===np&&(0,n.jsx)(t_.gz,{projectId:r0,customerId:null!==(rc=null!=rQ?rQ:null===(er=o0.customer)||void 0===er?void 0:er.id)&&void 0!==rc?rc:"",customerName:null!==(ru=null===(en=o0.customer)||void 0===en?void 0:en.name)&&void 0!==ru?ru:void 0,hasApprovedEstimate:"approved"===rP||"signed"===rP,propertyAddress:null!==(rm=null!=r$?r$:null==of?void 0:null===(es=of.properties)||void 0===es?void 0:null===(eo=es.find(e=>e.id===ok))||void 0===eo?void 0:eo.address)&&void 0!==rm?rm:void 0,projectName:null!=rX?rX:void 0,currentUserId:null!==(rp=null==r9?void 0:r9.id)&&void 0!==rp?rp:void 0}),"messages"===np&&(0,n.jsx)(tU.I,{projectId:r0,customerId:null!==(rx=null!=rQ?rQ:null===(ea=o0.customer)||void 0===ea?void 0:ea.id)&&void 0!==rx?rx:""}),"files"===np&&(0,n.jsx)(tz.b,{projectId:r0,customerId:null!==(rb=null!=rQ?rQ:null===(el=o0.customer)||void 0===el?void 0:el.id)&&void 0!==rb?rb:""}),"photos"===np&&(0,n.jsx)(tK.B,{projectId:r0,projectName:null!=rX?rX:void 0}),"history"===np&&(0,n.jsx)(tV.v,{projectId:r0,customerId:null!==(rh=null!=rQ?rQ:null===(ei=o0.customer)||void 0===ei?void 0:ei.id)&&void 0!==rh?rh:"",estimateId:na})]}),(0,n.jsxs)("div",{className:"estimate"===np?"px-6 pt-2.5 pb-5":"hidden",children:[oq&&na&&(0,n.jsx)("div",{className:"mb-3",children:(0,n.jsx)(_,{estimateId:na,status:rP})}),(0,n.jsxs)("div",{className:"grid gap-3 lg:grid-cols-[minmax(0,1fr)_340px]",children:[(0,n.jsxs)("div",{className:"space-y-3 min-w-0",children:[r4&&(0,n.jsx)("div",{className:"rounded-lg border border-border bg-card",children:(0,n.jsx)("div",{className:"px-4 py-3",children:(0,n.jsxs)("div",{className:"space-y-3",children:[(0,n.jsxs)("div",{children:[(0,n.jsxs)("label",{className:"block text-[10px] font-semibold uppercase tracking-wider text-muted-foreground mb-1.5",children:["Customer ",(0,n.jsx)("span",{className:"text-destructive",children:"*"})]}),(0,n.jsx)(tT.o,{value:o0.customer?{id:o0.customer.id,name:o0.customer.name,company:o0.customer.company,phone:o0.customer.phone,email:o0.customer.email,address:o0.customer.address,lastServiceAddress:o0.customer.lastServiceAddress}:null,onChange:oJ,required:!0})]}),o0.customer&&ov&&(0,n.jsxs)("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[(0,n.jsx)(N.Z,{className:"w-3.5 h-3.5 animate-spin"}),"Loading contacts & propertiesâ¦"]}),o0.customer&&!ov&&(0,n.jsxs)("div",{className:"space-y-2",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("label",{className:"block text-[10px] font-semibold uppercase tracking-wider text-muted-foreground mb-1",children:"Job-site property"}),(0,n.jsx)(tm.D,{customerId:o0.customer.id,value:ok,onChange:oA})]}),(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)("label",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted-foreground",children:"On-site contact"}),(0,n.jsx)(tp.w,{contacts:oF.length>0?oF:null!==(rf=null==of?void 0:of.contacts)&&void 0!==rf?rf:[],value:oC,onChange:oI,primaryContactName:(()=>{var e;let t=(null!==(e=null==of?void 0:of.contacts)&&void 0!==e?e:[])[0];
1return t?[t.firstName,t.lastName].filter(Boolean).join(" "):null})(),customerId:null!==(rg=null!=rQ?rQ:null===(ed=o0.customer)||void 0===ed?void 0:ed.id)&&void 0!==rg?rg:null,estimateId:null!=na?na:null})]}),r8&&oF.length>1&&(0,n.jsx)("div",{className:"mt-1 pt-2 border-t border-border",children:(0,n.jsxs)("div",{className:"flex-1",children:[(0,n.jsx)("label",{className:"block text-[10px] font-semibold uppercase tracking-wider text-muted-foreground mb-1",children:"Bill To"}),(0,n.jsxs)("select",{value:null!=oE?oE:"",onChange:e=>oT(e.target.value||null),className:"w-full rounded-xl border border-border bg-background px-3 py-2 text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-primary/40 focus:border-primary",children:[(0,n.jsx)("option",{value:"",children:"â Select billing contact â"}),oF.map(e=>(0,n.jsxs)("option",{value:e.id,children:[(0,tP.Pc)(e),e.isBilling?" â
Billing":e.isPrimary?" \xb7 Primary":""]},e.id))]}),(0,n.jsx)("p",{className:"text-[10px] text-muted-foreground mt-1",children:"Who receives this document for payment"})]})})]})]})})}),!r4&&sG&&(0,n.jsx)(eP,{customer:sG,onChangeCustomer:void 0}),!r4&&!r8&&(null!=rQ?rQ:null===(ec=o0.customer)||void 0===ec?void 0:ec.id)&&(0,n.jsx)("div",{className:"rounded-lg border border-border bg-card",children:(0,n.jsxs)("div",{className:"px-4 py-3",children:[(0,n.jsx)("label",{className:"block text-[10px] font-semibold uppercase tracking-wider text-muted-foreground mb-1",children:"Job-site property"}),(0,n.jsx)(tm.D,{customerId:null!==(rv=null!=rQ?rQ:null===(eu=o0.customer)||void 0===eu?void 0:eu.id)&&void 0!==rv?rv:null,value:ok,onChange:oA})]})}),!r4&&r8&&(null!=rQ?rQ:null===(em=o0.customer)||void 0===em?void 0:em.id)&&
1(0,n.jsx)("div",{className:"rounded-lg border border-border bg-card",children:(0,n.jsx)("div",{className:"px-4 py-3 space-y-2",children:oM?(0,n.jsxs)("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[(0,n.jsx)(N.Z,{className:"w-3.5 h-3.5 animate-spin"}),"Loading contacts & propertiesâ¦"]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("label",{className:"block text-[10px] font-semibold uppercase tracking-wider text-muted-foreground mb-1",children:"Job-site property"}),(0,n.jsx)(tm.D,{customerId:null!==(ry=null!=rQ?rQ:null===(ep=o0.customer)||void 0===ep?void 0:ep.id)&&void 0!==ry?ry:null,value:ok,onChange:oA})]}),(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)("label",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted-foreground",children:"On-site contact"}),(0,n.jsx)(tp.w,{contacts:oF.length>0?oF:null!==(rj=null==of?void 0:of.contacts)&&void 0!==rj?rj:[],value:oC,onChange:oI,primaryContactName:(()=>{var e;let t=(null!==(e=null==of?void 0:of.contacts)&&void 0!==e?e:[])[0];return t?[t.firstName,t.lastName].filter(Boolean).join(" "):null})()})]}),r8&&oF.length>1&&(0,n.jsx)("div",{className:"pt-2 border-t border-border",children:(0,n.jsxs)("div",{className:"flex-1",children:[(0,n.jsx)("label",{className:"block text-[10px] font-semibold uppercase tracking-wider text-muted-foreground mb-1",children:"Bill To"}),(0,n.jsxs)("select",{value:null!=oE?oE:"",onChange:e=>oT(e.target.value||null),className:"w-full rounded-xl border border-border bg-background px-3 py-2 text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-primary/40 focus:border-primary",children:[(0,n.jsx)("option",{value:"",children:"â Select billing contact â"}),oF.map(e=>(0,n.jsxs)("option",{value:e.id,children:[(0,tP.Pc)(e),e.isBilling?" â
Billing":e.isPrimary?" \xb7 Primary":""]},e.id))]}),(0,n.jsx)("p",{className:"text-[10px] text-muted-foreground mt-1",children:"Who receives this document for payment"})]})})]})})}),!r4&&o0.customer&&!r8&&(0,n.jsx)("div",{className:"rounded-lg border border-border bg-card",children:(0,n.jsx)("div",{className:"px-4 py-3 space-y-2",children:(0,n.jsxs)("div",{className:"flex items-center gap-2",children:[(0,n.jsx)("label",{className:"text-[10px] font-semibold uppercase tracking-wider text-muted-foreground",children:"On-site contact"}),(0,n.jsx)(tp.w,{contacts:oF.length>0?oF:null!==(rN=null==of?void 0:of.contacts)&&void 0!==rN?rN:[],value:oC,onChange:oI,primaryContactName:(()=>{var e;let t=(null!==(e=null==of?void 0:of.contacts)&&void 0!==e?e:[])[0];return t?[t.firstName,t.lastName].filter(Boolean).join(" "):null})(),customerId:null!==(rk=null!=rQ?rQ:null===(ex=o0.customer)||void 0===ex?void 0:ex.id)&&void 0!==rk?rk:null,estimateId:null!=na?na:null})]})})}),s0.urgency&&(0,n.jsx)(eO,{urgency:o0.urgency,validDays:o0.validDays,onUrgencyChange:e=>o1(t=>({...t,urgency:e})),disabled:oq}),s0.markup&&(0,n.jsx)(eZ.d,{markupDefaults:oR,onMarkupChange:(e,t)=>
1oB(r=>({...r,[e]:t})),disabled:oq,readableSummary:e$.Qq}),e$.Qq&&!sV.fullLayout&&(0,n.jsx)(ty,{sections:s1,onToggle:sV.toggleSection,onExpandAll:sV.expandAll}),(()=>{var e,t,r,o,s,a;let l=(0,n.jsxs)("div",{id:"scope-of-work-editor",children:[!oq&&(0,n.jsxs)("div",{className:"flex items-center justify-end gap-2 mb-1.5",children:[(0,n.jsxs)("button",{type:"button",onClick:()=>{si()},disabled:nE||!na,className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-[11px] font-semibold text-muted-foreground bg-muted hover:bg-muted hover:text-primary transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:[nE?(0,n.jsx)(N.Z,{size:12,className:"animate-spin"}):(0,n.jsx)(k.Z,{size:12}),"Generate from line items"]}),(0,n.jsxs)("button",{type:"button",onClick:()=>nA(!0),disabled:!na,title:na?void 0:"Save the estimate first",className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-[11px] font-semibold text-muted-foreground bg-muted hover:bg-muted hover:text-primary transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:[(0,n.jsx)(w.Z,{size:12}),"Apply template"]}),(o0.scopeOfWork||(null!==(o=null===(e=o0.scopeSpecs)||void 0===e?void 0:e.length)&&void 0!==o?o:0)>0||(null!==(s=null===(t=o0.scopeIncludes)||void 0===t?void 0:t.length)&&void 0!==s?s:0)>0||(null!==(a=null===(r=o0.scopeExcludes)||void 0===r?void 0:r.length)&&void 0!==a?a:0)>0)&&(0,n.jsxs)("button",{type:"button",onClick:()=>nS(!0),className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-[11px] font-semibold text-muted-foreground bg-muted hover:bg-muted hover:text-primary transition-colors",children:[(0,n.jsx)(c.Z,{size:12}),"Save as template"]}),(0,n.jsxs)("button",{type:"button",onClick:()=>{sd()},disabled:nP||!na,className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-lg text-[11px] font-semibold text-muted-foreground bg-muted hover:bg-muted hover:text-primary transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:[nP?(0,n.jsx)(N.Z,{size:12,className:"animate-spin"}):(0,n.jsx)(C.Z,{size:12}),"Review proposal"]})]}),(0,n.jsx)(eG.U,{value:o0.scopeOfWork,onChange:e=>o1(t=>({...t,scopeOfWork:e||null})),specs:o0.scopeSpecs,onSpecsChange:e=>o1(t=>({...t,scopeSpecs:e})),includes:o0.scopeIncludes,onIncludesChange:e=>o1(t=>({...t,scopeIncludes:e})),excludes:o0.scopeExcludes,onExcludesChange:e=>o1(t=>({...t,scopeExcludes:e})),disabled:oq})]}),i=e$.Qq?(0,n.jsx)(tl,{organizationId:rE,estimateId:null!=na?na:null,hideWhenEmpty:!0,forceExpanded:s0.photos,onCountChange:e=>s$(e>0)}):(0,n.jsx)(ta,{organizationId:rE,estimateId:null!=na?na:null}),d=e$.Qq?(0,n.jsx)(tu,{estimateId:na,hideWhenEmpty:!0,forceExpanded:s0.options,onHasContentChange:sJ}):null,u=e$.Zp&&e$.Iv,m=o0.lineGroups.length>0,p=(0,n.jsxs)("div",{className:"mt-3 space-y-3 min-w-0",children:[!oq&&u&&(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-between gap-3 px-4 py-3 bg-muted rounded-xl border border-border",children:[(0,n.jsx)("p",{className:"text-xs text-muted-foreground",children:"Pull priced materials from your catalog â quantities \xd7 your markup"}),m?(0,n.jsxs)("button",{type:"button",onClick:()=>n8(!0),title:"Priced materials from your Material Catalog",className:"flex items-center gap-2 px-4 py-2.5 rounded-xl bg-primary hover:bg-primary/90 text-primary-foreground text-sm font-semibold shadow-sm transition-all min-h-[44px]",children:[(0,n.jsx)(S.Z,{size:15,strokeWidth:2.5}),"Price from Catalog"]}):(0,n.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,n.jsx)("span",{className:"text-xs text-muted-foreground",children:"Add a section first â line items live inside sections"}),(0,n.jsxs)("button",{type:"button",onClick:o7,className:"flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs font-semibold text-primary hover:bg-primary/10 transition-colors",children:[(0,n.jsx)(I.Z,{size:12}),"Add section"]})]})]}),(0,n.jsx)(eL.O,{lineGroups:o0.lineGroups,pinnedColumns:o_,onSavePinnedColumns:oz,phaseLabel:"approved"===rP||"signed"===rP?"Approved":"Estimating",isLocked:oq,markupDefaults:oR,showQuantity:o0.showQuantity,showUnit:o0.showUnit,showPrice:o0.showPrice,showAmount:o0.showAmount,showOrderStatus:o0.showOrderStatus,onToggleColumns:e=>o1(t=>({...t,...e}
1)),detailLevel:o0.detailLevel,onApplyDocumentOptions:e=>sn(e),onUpdateItem:(e,t,r)=>o6(e,t,r),onDeleteItem:o8,onDuplicateItem:sc,onAddItem:o9,onAddGroup:o7,onAddSubGroup:se,onUpdateGroup:(e,t)=>o4(e,t),onDeleteGroup:sr,onMoveGroupToParent:st,onOpenCatalogPicker:(e,t)=>nh({groupId:e,itemId:t}),onReorderItem:so,onMoveItemBetweenGroups:ss,onReorderGroups:sa,onApplyToScope:sl,onEditGroupParameters:e$.xf&&n$?sh:void 0,assemblySourcedGroupIds:e$.xf&&n$&&od?new Set(Object.keys(od)):void 0,groupHeaderExtras:oq?void 0:sf,descriptionRowExtras:e$.TC?sq:void 0}),nb&&"toolbar"!==nb.itemId&&nb.itemId!=="footer-".concat(nb.groupId)&&(0,n.jsx)("div",{className:"relative",children:(0,n.jsx)("div",{className:"absolute top-0 left-0 z-50",children:(0,n.jsx)(e0,{orgId:rE,onSelect:e=>sg(nb.groupId,nb.itemId,e),onClose:()=>nh(null)})})}),(null==nb?void 0:nb.itemId)==="toolbar"&&(0,n.jsx)("div",{className:"relative",children:(0,n.jsx)("div",{className:"absolute top-0 left-0 z-50",children:(0,n.jsx)(e0,{orgId:rE,onSelect:e=>sv(nb.groupId,e),onClose:()=>nh(null)})})}),!oq&&(0,n.jsxs)("div",{className:"flex flex-wrap items-center gap-3 px-4 py-3 bg-muted rounded-xl border border-border",children:[(0,n.jsxs)("button",{type:"button","data-brion-action":"add-line-item",onClick:()=>{var e;return o9((null===(e=o0.lineGroups[0])||void 0===e?void 0:e.id)||"")},disabled:0===o0.lineGroups.length,className:"flex items-center gap-2 px-4 py-2.5 rounded-xl border-2 border-primary text-primary text-sm font-semibold hover:bg-amber-50 dark:hover:bg-amber-950/40 transition-all min-h-[44px] disabled:opacity-50",children:[(0,n.jsx)(A.Z,{size:15,strokeWidth:2.5}),"Add Item"]}),(0,n.jsxs)("button",{type:"button",onClick:()=>{var e;return nh({groupId:(null===(e=o0.lineGroups[0])||void 0===e?void 0:e.id)||"",itemId:"toolbar"})},disabled:0===o0.lineGroups.length,title:"Legacy catalog items (unpriced)",className:"flex items-center gap-2 px-4 py-2.5 rounded-xl border border-border bg-card text-muted-foreground text-sm font-medium hover:border-primary/50 hover:text-primary transition-all min-h-[44px] disabled:opacity-50",children:[(0,n.jsx)(E.Z,{size:14}),"Add from Catalog"]}),e$.xf&&n$&&(0,n.jsxs)("button",{type:"button",onClick:()=>n3(!0),title:"Assembly pricebook (labs)",className:"flex items-center gap-2 px-4 py-2.5 rounded-xl border border-border bg-card text-muted-foreground text-sm font-medium hover:border-primary/50 hover:text-primary transition-all min-h-[44px]",children:[(0,n.jsx)(T.Z,{size:14}),"Add assembly"]}),e$.xf&&n$&&(0,n.jsxs)("button",{type:"button",onClick:()=>n6(!0),title:"Assembly pricebook (labs)",className:"flex items-center gap-2 px-4 py-2.5 rounded-xl border border-border bg-card text-muted-foreground text-sm font-medium hover:border-primary/50 hover:text-primary transition-all min-h-[44px]",children:[(0,n.jsx)(P.Z,{size:14}),"Insert Assembly Pricebook"]}),(0,n.jsxs)("button",{type:"button",onClick:o7,className:"flex items-center gap-2 px-4 py-2.5 rounded-xl border border-border bg-card text-muted-foreground text-sm font-medium hover:border-primary/50 hover:text-primary transition-all min-h-[44px]",children:[(0,n.jsx)(I.Z,{size:14}),"Add Section"]}),rH&&(0,n.jsxs)("button",{type:"button",onClick:()=>nw(!0),className:"flex items-center gap-2 px-4 py-2.5 rounded-xl border border-border bg-card text-muted-foreground text-sm font-medium hover:border-violet-500/50 hover:text-violet-600 dark:text-violet-400 transition-all min-h-[44px]",children:[(0,n.jsx)(D.Z,{size:14}),"Copy from another estimate"]}),na&&(0,n.jsxs)("button",{type:"button",onClick:()=>nK(!0),className:"flex items-center gap-2 px-4 py-2.5 rounded-xl border border-border bg-card text-muted-foreground text-sm font-medium hover:border-primary/50 hover:text-primary transition-all min-h-[44px]",children:[(0,n.jsx)(F.Z,{size:14}),"Insert saved group"]})]})]}),x=(0,n.jsxs)("div",{className:"bg-card rounded-2xl border border-border shadow-sm overflow-hidden",children:[(0,n.jsx)("div",{className:"px-5 py-3.5 bg-muted border-b border-border",children:(0,n.jsx)("h2",{className:"text-sm font-bold text-foreground",children:"Terms & Notes"})}),(0,n.jsx)("div",{className:"p-5",children:(0,n.jsxs)("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4 mb-5",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)(ro,{htmlFor:"payment-terms",children:"Payment Terms"}),(0,n.jsx)(rs,{id:"payment-terms",value:o0.paymentTerms,onChange:e=>o1(t=>({...t,paymentTerms:e.target.value})),options:Object.entries(re).map(e=>{let[t,r]=e;return{value:t,label:r}})})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)(ro,{htmlFor:"contract-type",children:"Contract Type"}
1),(0,n.jsx)(rs,{id:"contract-type",value:o0.contractType,onChange:e=>o1(t=>({...t,contractType:e.target.value})),options:Object.entries(rt).map(e=>{let[t,r]=e;return{value:t,label:r}})})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)(ro,{htmlFor:"valid-days",children:"Valid For"}),(0,n.jsxs)("div",{className:"relative",children:[(0,n.jsx)("input",{id:"valid-days","data-brion-field":"valid_days",type:"number",value:o0.validDays,onChange:e=>o1(t=>({...t,validDays:parseInt(e.target.value)||0})),min:1,className:"w-full rounded-xl border border-border bg-background px-3.5 py-2.5 text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-primary/40 focus:border-primary pr-14 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),(0,n.jsx)("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-xs text-muted-foreground font-medium",children:"days"})]})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)(ro,{htmlFor:"tax-rate",children:"Tax Rate"}),(0,n.jsxs)("div",{className:"relative",children:[(0,n.jsx)("input",{id:"tax-rate","data-brion-field":"tax_rate",type:"number",value:o0.taxRate,onChange:e=>o1(t=>({...t,taxRate:parseFloat(e.target.value)||0})),min:0,step:"0.01",className:"w-full rounded-xl border border-border bg-background px-3.5 py-2.5 text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-primary/40 focus:border-primary pr-8 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),(0,n.jsx)("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-xs text-muted-foreground font-medium",children:"%"})]})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)(ro,{children:"Discount"}),(0,n.jsxs)("div",{className:"flex gap-2",children:[(0,n.jsxs)("div",{className:"relative flex-1",children:["fixed"===o0.discountType&&(0,n.jsx)("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-xs text-muted-foreground",children:"$"}),(0,n.jsx)("input",{"data-brion-field":"discount_amount",type:"number",value:o0.discountAmount||"",onChange:e=>o1(t=>({...t,discountAmount:parseFloat(e.target.value)||0})),min:0,step:"0.01",placeholder:"0",className:t6("w-full rounded-xl border border-border bg-background py-2.5 text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-primary/40 focus:border-primary [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none","fixed"===o0.discountType?"pl-7 pr-3":"px-3.5")})]}),(0,n.jsxs)("div",{className:"flex rounded-xl border border-border overflow-hidden flex-shrink-0",children:[(0,n.jsx)("button",{type:"button",onClick:()=>o1(e=>({...e,discountType:"fixed"})),className:t6("px-3 py-2.5 text-xs font-semibold transition-colors","fixed"===o0.discountType?"bg-primary text-primary-foreground":"bg-background text-muted-foreground hover:bg-muted"),children:(0,n.jsx)(O.Z,{className:"w-3.5 h-3.5"})}),(0,n.jsx)("button",{type:"button",onClick:()=>o1(e=>({...e,discountType:"percent"})),className:t6("px-3 py-2.5 text-xs font-semibold transition-colors border-l border-border","percent"===o0.discountType?"bg-primary text-primary-foreground":"bg-background text-muted-foreground hover:bg-muted"),children:(0,n.jsx)(M.Z,{className:"w-3.5 h-3.5"})})]})]})]}),(0,n.jsx)("div",{children:(0,n.jsx)(tW,{totalAmountCents:Math.round(100*sy.total),customerState:(()=>{var e,t,r,n;let o=null!==(n=null!==(r=null===(e=o0.customer)||void 0===e?void 0:e.address)&&void 0!==r?r:null===(t=o0.newCustomerForm)||void 0===t?void 0:t.address)&&void 0!==n?n:"",s=/\b([A-Z]{2})\b/.exec(o);return s?s[1]:null})(),trade:o0.jobType||null,milestones:ou,onChange:om,collapsed:op,onCollapseChange:ox})})]})})]});return e$.Qq?(0,n.jsxs)(n.Fragment,{children:[p,d,s0.scope&&l,i,s0.terms&&x]}):(0,n.jsxs)(n.Fragment,{children:[l,i,p,x]})})()]}),(0,n.jsx)("div",{className:"space-y-4 lg:sticky lg:top-[60px] lg:self-start",children:(0,n.jsx)(ez,{totals:sF,paymentSchedule:sO,customerNotes:o0.customerNotes,internalNotes:o0.internalNotes,warrantyText:o0.warrantyText,onCustomerNotesChange:e=>o1(t=>({...t,customerNotes:e})),onInternalNotesChange:e=>o1(t=>({...t,internalNotes:e})),onWarrantyTextChange:e=>o1(t=>({...t,warrantyText:e})),onEditPaymentSchedule:()=>
1ox(!1),isLocked:oq,onApplyTargetMargin:(e,t)=>{o1(r=>({...r,lineGroups:r.lineGroups.map(r=>({...r,items:r.items.map(r=>{if(!r.cost||r.cost<=0)return r;let n=r.lineItemType||"labor";if(!("all"===t||t===n||"subcontract"===t&&"subcontractor"===n))return r;let o=Math.min(Math.max(e/100,0),.99),s=o>=1?r.cost:Math.round(r.cost/(1-o)*100)/100;return{...r,unitPrice:s}})}))}))}})})]})]}),nf&&(0,n.jsx)("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4",onClick:()=>!nj&&ng(!1),children:(0,n.jsxs)("div",{className:"w-full max-w-md bg-card rounded-2xl shadow-xl border border-border overflow-hidden",onClick:e=>e.stopPropagation(),children:[(0,n.jsxs)("div",{className:"px-5 py-4 border-b border-border flex items-center gap-2",children:[(0,n.jsx)("div",{className:"w-8 h-8 rounded-full bg-violet-50 dark:bg-violet-950/40 text-violet-600 dark:text-violet-400 flex items-center justify-center",children:(0,n.jsx)(x.Z,{className:"w-4 h-4"})}),(0,n.jsxs)("div",{children:[(0,n.jsx)("h3",{className:"text-sm font-bold text-foreground",children:"Create Revision"}),(0,n.jsx)("p",{className:"text-[11px] text-amber-800 dark:text-amber-300",children:"The current signed version will be preserved in history."})]})]}),(0,n.jsxs)("div",{className:"p-5 space-y-3",children:[(0,n.jsxs)("label",{className:"block",children:[(0,n.jsx)("span",{className:"text-[11px] uppercase tracking-wide font-bold text-amber-800 dark:text-amber-300",children:"What's changing in this revision?"}),(0,n.jsx)("textarea",{value:nv,onChange:e=>ny(e.target.value),placeholder:"e.g. Customer asked to add gutters. Added new section, adjusted labor.",rows:3,className:"mt-1.5 w-full rounded-lg border border-border px-3 py-2 text-sm text-foreground placeholder:text-muted-foreground/60 resize-none focus:outline-none focus:border-violet-500 dark:focus:border-violet-400 focus:ring-2 focus:ring-violet-500/20 dark:focus:ring-violet-400/20",autoFocus:!0})]}),(0,n.jsxs)("div",{className:"rounded-lg bg-amber-50 dark:bg-amber-950/40 border border-amber-200 dark:border-amber-700 p-3 text-[11px] text-amber-800 dark:text-amber-300 leading-relaxed",children:[(0,n.jsx)("div",{className:"font-bold mb-1",children:"What happens when you click Create:"}),(0,n.jsxs)("ul",{className:"space-y-0.5 list-disc pl-4",children:[(0,n.jsx)("li",{children:"A snapshot of the current version is saved to revision history"}),(0,n.jsx)("li",{children:"The previous customer approval link stops working"}),(0,n.jsx)("li",{children:"You'll be editing a fresh draft â send it to the customer when ready"})]})]})]}),(0,n.jsxs)("div",{className:"px-5 py-3 bg-muted border-t border-border flex justify-end gap-2",children:[(0,n.jsx)("button",{type:"button",onClick:()=>ng(!1),disabled:nj,className:"px-4 py-2 rounded-lg text-sm font-semibold text-muted-foreground hover:bg-muted transition-colors disabled:opacity-50",children:"Cancel"}),(0,n.jsx)("button",{type:"button",onClick:oH,disabled:nj||!nv.trim(),className:"inline-flex items-center gap-1.5 px-4 py-2 rounded-lg bg-violet-600 dark:bg-violet-500 hover:bg-violet-700 dark:hover:bg-violet-600 text-white text-sm font-semibold shadow-sm transition-all disabled:opacity-50",children:nj?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(N.Z,{className:"w-3.5 h-3.5 animate-spin"}),"Creating..."]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(x.Z,{className:"w-3.5 h-3.5"}),"Create Revision"]})})]})]})}),(0,n.jsx)(e2.Vq,{open:nV,onOpenChange:nH,children:(0,n.jsxs)(e2.cZ,{className:"max-w-4xl w-full max-h-[90vh] overflow-y-auto",children:[(0,n.jsx)(e2.fK,{children:(0,n.jsx)(e2.$N,{className:"text-base font-bold text-foreground",children:"Estimate Preview â customer view"})}),(0,n.jsx)(tF.Z,{billTo:(()=>{var e,t,r,n,o;if(!r8||oF.length<=1||!oE)return null;let s=oF.find(e=>e.id===oE);if(!s)return null;let a=oj?oF.find(e=>e.id===oj):null;return{billToName:(0,tP.Pc)(s),billToPhone:null!==(e=s.phone)&&void 0!==e?e:null,billToEmail:null!==(t=s.email)&&void 0!==t?t:null,attnName:a?(0,tP.Pc)(a):null,attnRole:null!==(r=null==a?void 0:a.role)&&void 0!==r?r:null,attnPhone:null!==(n=null==a?void 0:a.phone)&&void 0!==n?n:null,attnEmail:null!==(o=null==a?void 0:a.email)&&void 0!==o?o:null}})(),data:{customer:o0.customer?{name:o0.customer.name,company:o0.customer.company,phone:o0.customer.phone,email:o0.customer.email,address:o0.customer.address}:null,isNewCustomer:o0.isNewCustomer,newCustomerForm:o0.newCustomerForm,jobType:o0.jobType,serviceAddress:o0.serviceAddress||(null!==(rC=null!==(rw=null===(eb=o0.customer)||void 0===eb?void 0:eb.lastServiceAddress)&&void 0!==rw?rw:null===(eh=o0.
1customer)||void 0===eh?void 0:eh.address)&&void 0!==rC?rC:""),jobDescription:o0.jobDescription,urgency:o0.urgency,scopeSpecs:o0.scopeSpecs,scopeOfWork:o0.scopeOfWork,scopeIncludes:o0.scopeIncludes,scopeExcludes:o0.scopeExcludes,lineGroups:o0.lineGroups.map(e=>{var t;return{id:e.id,name:e.name,displayMode:e.displayMode,parentGroupId:null!==(t=e.parentGroupId)&&void 0!==t?t:null,items:e.items.map(e=>({id:e.id,description:e.description,qty:e.qty,unit:e.unit,unitPrice:e.unitPrice}))}}),paymentTerms:o0.paymentTerms,validDays:o0.validDays,taxRate:o0.taxRate,discountAmount:o0.discountAmount,discountType:o0.discountType,depositRequired:o0.depositRequired,depositAmount:o0.depositAmount,customerNotes:o0.customerNotes,showQuantity:o0.showQuantity,showUnit:o0.showUnit,showPrice:o0.showPrice,showAmount:o0.showAmount,showOrderStatus:o0.showOrderStatus,detailLevel:o0.detailLevel,paymentMilestones:ou.map(e=>({id:e.id,label:e.label,amountKind:e.amountKind,percent:e.percent,fixedAmountCents:e.fixedAmountCents,triggerKind:e.triggerKind}))},branding:rF,onSave:()=>{sk()},onSend:()=>{sD()},onToggleColumns:e=>sn(e)})]})}),nk&&rH&&(0,n.jsx)(rl,{orgId:rE,currentEstimateId:null!=rT?rT:"",onClose:()=>nw(!1),onCopy:async e=>{await rH(e),nw(!1)}}),(0,n.jsx)(tH,{open:nC,onOpenChange:nS,title:"Save scope as template",description:"Give this scope a name so you can quickly apply it to future estimates.",defaultName:o0.jobType?"".concat(o0.jobType," scope"):"",trades:null!=nJ?nJ:[],onSave:async(e,t)=>{try{let n=await fetch("/api/crm-estimates/scope-templates",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({estimateId:null!=na?na:null,label:e,trade:t||null})});if(!n.ok){var r;let e=await n.json().catch(()=>({}));a.A.error(null!==(r=e.error)&&void 0!==r?r:"Failed to save scope template.");return}a.A.success("Scope template saved.")}catch(e){a.A.error("Could not save scope template â network error.")}}}),nI&&(0,n.jsx)(tJ,{open:nI,onOpenChange:nA,estimateId:null!=na?na:"",hasExistingScope:!!(o0.scopeOfWork||(null!==(rS=null===(ef=o0.scopeSpecs)||void 0===ef?void 0:ef.length)&&void 0!==rS?rS:0)>0||(null!==(rI=null===(eg=o0.scopeIncludes)||void 0===eg?void 0:eg.length)&&void 0!==rI?rI:0)>0||(null!==(rA=null===(ev=o0.scopeExcludes)||void 0===ev?void 0:ev.length)&&void 0!==rA?rA:0)>0),onApplied:e=>{o1(t=>({...t,scopeOfWork:e.scopeOfWork,scopeSpecs:e.scopeSpecs,scopeIncludes:e.scopeIncludes,scopeExcludes:e.scopeExcludes}))}}),(0,n.jsx)(tH,{open:nR,onOpenChange:nB,title:"Save group as reusable",description:"Save this line group so you can quickly insert it into any estimate.",defaultName:n_,trades:null!=nJ?nJ:[],onSave:async(e,t)=>{if(!nq)return;let r=o0.lineGroups.find(e=>e.id===nq);try{var n,o;let s=await fetch("/api/crm-estimates/saved-line-groups",{method:"POST",credentials:"include",headers:{"Content-Type":"application/json"},body:JSON.stringify({groupId:nq,name:e,trade:t||null,inlineGroup:r?{groupName:r.name,isCollapsed:r.collapsed,items:(null!==(n=r.items)&&void 0!==n?n:[]).map((e,t)=>{var r,n,o,s,a,l,i;return{description:null!==(r=e.description)&&void 0!==r?r:"",quantity:Number(null!==(n=e.qty)&&void 0!==n?n:1),unit:null!==(o=e.unit)&&void 0!==o?o:null,unitPrice:null!=e.unitPrice?Number(e.unitPrice):null,total:null!=e.cost?Number(e.cost):null,sortOrder:t,lineItemType:null!==(s=e.lineItemType)&&void 0!==s?s:"fixed",isOptional:null!==(a=e.isOptional)&&void 0!==a&&a,taxable:null!==(l=e.taxable)&&void 0!==l&&l,notes:null!==(i=e.notes)&&void 0!==i?i:null}})}:void 0})});if(!s.ok){let e=await s.json().catch(()=>({}));a.A.error(null!==(o=e.error)&&void 0!==o?o:"Failed to save group.");return}a.A.success('"'.concat(e,'" saved as a reusable group.'))}catch(e){a.A.error("Could not save group â network error.")}}}),nz&&na&&(0,n.jsx)(tQ,{open:nz,onOpenChange:nK,estimateId:na,onInserted:()=>{fetch("/api/crm-estimates/".concat(na),{credentials:"include"}).then(e=>e.ok?e.json():null).then(e=>{var t;if(!(null==e?void 0:null===(t=e.estimate)||void 0===t?void 0:t.lineGroups))return;let r=e.estimate.lineGroups.map(e=>{var t;return{id:e.id||t4(),name:e.name||"General",collapsed:!1,displayMode:e.dis
1playMode||"inherit",parentGroupId:null!==(t=e.parentGroupId)&&void 0!==t?t:null,items:(e.lineItems||[]).map(e=>{var t,r,n,o,s,a,l,i,d,c;return{id:e.id||t4(),description:e.description||"",qty:Number(e.quantity)||1,unit:e.unit||"each",unitPrice:Number(e.unitPrice)||0,cost:Number(e.unitCost)||0,isOptional:e.isOptional||!1,notes:e.notes||"",taxable:!1!==e.taxable,aiGenerated:!1,lineItemType:e.lineItemType||"labor",materialItemId:e.materialItemId||void 0,productionRateId:e.productionRateId||void 0,isSpecialOrder:null!==(t=e.isSpecialOrder)&&void 0!==t&&t,orderStatus:null!==(r=e.orderStatus)&&void 0!==r?r:null,supplierName:null!==(n=e.supplierName)&&void 0!==n?n:null,supplierEta:null!==(o=e.supplierEta)&&void 0!==o?o:null,customerPromiseDate:null!==(s=e.customerPromiseDate)&&void 0!==s?s:null,orderReference:null!==(a=e.orderReference)&&void 0!==a?a:null,isAllowance:null!==(l=e.isAllowance)&&void 0!==l&&l,allowanceCap:null!=e.allowanceCap?Number(e.allowanceCap):null,lineTotalCents:null!==(i=e.lineTotalCents)&&void 0!==i?i:null,sourcePath:null!==(d=e.sourcePath)&&void 0!==d?d:null,lineKey:null!==(c=e.lineKey)&&void 0!==c?c:null}})}});o1(e=>({...e,lineGroups:r}))}).catch(()=>{})}}),e$.xf&&n$&&nX&&n1&&(0,n.jsx)(e1.k,{open:nX,onClose:()=>{n0(!1),n5(null),nh(null)},onSelect:e=>{n0(!1),n5(null),sp(e.id)},onSelectExpanded:su,preSelectedAssemblyId:n1}),e$.xf&&n$&&n2&&(0,n.jsx)(e1.k,{open:n2,onClose:()=>n3(!1),onSelect:sx,onSelectParameterized:sm,onSelectExpanded:(e,t,r)=>{su(e,t,r),n3(!1)}}),e$.xf&&n$&&n4&&(0,n.jsx)(e7,{open:n4,onClose:()=>n6(!1),onInsert:sb}),e$.Zp&&e$.Iv&&n9&&(0,n.jsx)(te.h,{open:n9,onClose:()=>n8(!1),estimateTrade:o0.jobType||null,onSelect:e=>{var t;sv((null===(t=o0.lineGroups[0])||void 0===t?void 0:t.id)||"",e),n8(!1)}}),(0,n.jsx)(t3,{open:nF,onOpenChange:nO,findings:nM,summary:nG}),e$.xf&&n$&&n7&&ot&&(0,n.jsx)(tt.e,{open:n7,onClose:()=>{oe(!1),or(null),oo(""),oa(null),oi(null)},assemblyId:ot,assemblyName:on,estimateId:null!=na?na:null,onAdded:()=>{r6.refresh()},initialInputs:ol,replaceGroupId:os})]})});function rl(e){let{orgId:t,currentEstimateId:r,onClose:a,onCopy:l}=e,[i,d]=(0,o.useState)(""),[c,u]=(0,o.useState)([]),[m,p]=(0,o.useState)(null),[x,b]=(0,o.useState)(!1),[h,f]=(0,o.useState)(!1);(0,o.useEffect)(()=>{let e=new AbortController,t=setTimeout(()=>{b(!0);let t=new URLSearchParams;i.trim()&&t.set("q",i.trim()),t.set("limit","20"),fetch("/api/crm-estimates?".concat(t),{credentials:"include",signal:e.signal}).then(e=>e.ok?e.json():{estimates:[]}).then(e=>{u((e.estimates||[]).filter(e=>e.id!==r).map(e=>{var t,r,n;return{id:e.id,estimateNumber:e.estimateNumber,title:e.title,total:Number(e.total),status:e.status,createdAt:e.createdAt,customerName:(null===(t=e.customer)||void 0===t?void 0:t.companyName)||(null===(r=e.customer)||void 0===r?void 0:r.name),lineGroupCount:null===(n=e.lineGroups)||void 0===n?void 0:n.length}}))}).catch(()=>{}).finally(()=>b(!1))},250);return()=>{clearTimeout(t),e.abort()}},[i,r,t]);let g=async()=>{if(m){f(!0);try{await l(m)}finally{f(!1)}}};return(0,n.jsx)("div",{className:"fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4",onClick:()=>!h&&a(),children:(0,n.jsxs)("div",{className:"w-full max-w-2xl max-h-[80vh] flex flex-col bg-card rounded-2xl shadow-xl border border-border overflow-hidden",onClick:e=>e.stopPropagation(),children:[(0,n.jsxs)("div",{className:"px-5 py-4 border-b border-border flex items-center gap-2",children:[(0,n.jsx)("div",{className:"w-8 h-8 rounded-full bg-amber-50 dark:bg-amber-950/40 text-primary flex items-center justify-center",children:(0,n.jsx)(D.Z,{className:"w-4 h-4"})}),(0,n.jsxs)("div",{className:"flex-1",children:[(0,n.jsx)("h3",{className:"text-sm font-bold text-foreground",children:"Copy from another estimate"}),(0,n.jsx)("p",{className:"text-[11px] text-amber-800 dark:text-amber-300",children:"Line groups and items will be appended. Customer, totals, and approval state stay untouched."})]}),(0,n.jsx)("button",{type:"button",onClick:a,disabled:h,className:"p-1.5 rounded-lg text-muted-foreground hover:text-foreground hover:bg-muted transition-colors",children:(0,n.jsx)(Z.Z,{className:"w-4 h-4"})})]}),(0,n.jsx)("div",{className:"p-4 border-b border-border",children:(0,n.jsxs)("div",{className:"relative",children:[(0,n.jsx)(G.Z,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),(0,n.jsx)("input",{type:"text",value:i,onChange:e=>d(e.target.value),placeholder:"Search by estimate number, title, or customer...",autoFocus:!0,className:"w-full pl-9 pr-3 py-2 rounded-lg border border-border text-sm text-foreground placeholder:text-muted-foreground
1/60 focus:outline-none focus:border-primary focus:ring-2 focus:ring-primary/20"})]})}),(0,n.jsxs)("div",{className:"flex-1 overflow-y-auto",children:[x&&(0,n.jsx)("div",{className:"p-8 flex items-center justify-center text-muted-foreground",children:(0,n.jsx)(N.Z,{className:"w-5 h-5 animate-spin"})}),!x&&0===c.length&&(0,n.jsx)("div",{className:"p-8 text-center text-sm text-muted-foreground",children:i?"No estimates match your search.":"No other estimates to copy from yet."}),!x&&c.length>0&&(0,n.jsx)("ul",{className:"divide-y divide-border",children:c.map(e=>{var t;let r=m===e.id;return(0,n.jsx)("li",{children:(0,n.jsxs)("button",{type:"button",onClick:()=>p(e.id),className:t6("w-full text-left px-5 py-3 flex items-start gap-3 transition-colors",r?"bg-amber-50 dark:bg-amber-950/40":"hover:bg-muted"),children:[(0,n.jsx)("div",{className:t6("w-4 h-4 mt-0.5 rounded-full border-2 flex-shrink-0 flex items-center justify-center",r?"border-primary bg-primary":"border-border"),children:r&&(0,n.jsx)("div",{className:"w-1.5 h-1.5 rounded-full bg-primary-foreground"})}),(0,n.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,n.jsxs)("div",{className:"flex items-center gap-2 flex-wrap",children:[(0,n.jsx)("span",{className:"text-[11px] font-bold text-amber-700 dark:text-amber-300",children:e.estimateNumber}),(0,n.jsx)("span",{className:"inline-flex items-center px-1.5 py-0.5 rounded bg-muted text-muted-foreground text-[9px] uppercase font-bold tracking-wide",children:e.status})]}),(0,n.jsx)("div",{className:"mt-0.5 text-sm font-semibold text-foreground truncate",children:e.title}),(0,n.jsxs)("div",{className:"mt-0.5 flex items-center gap-2 text-[11px] text-amber-800 dark:text-amber-300",children:[e.customerName&&(0,n.jsx)("span",{className:"truncate",children:e.customerName}),e.customerName&&(0,n.jsx)("span",{children:"\xb7"}),(0,n.jsx)("span",{children:new Date(e.createdAt).toLocaleDateString(void 0,{dateStyle:"medium"})})]})]}),(0,n.jsx)("div",{className:"text-sm font-bold text-foreground flex-shrink-0",children:(t=e.total,(0,s.xG)(t))})]})},e.id)})})]}),(0,n.jsxs)("div",{className:"px-5 py-3 bg-muted border-t border-border flex justify-end gap-2",children:[(0,n.jsx)("button",{type:"button",onClick:a,disabled:h,className:"px-4 py-2 rounded-lg text-sm font-semibold text-muted-foreground hover:bg-muted transition-colors disabled:opacity-50",children:"Cancel"}),(0,n.jsx)("button",{type:"button",onClick:g,disabled:!m||h,className:"inline-flex items-center gap-1.5 px-4 py-2 rounded-lg bg-primary hover:bg-primary/90 text-white text-sm font-semibold shadow-sm transition-all disabled:opacity-50",children:h?(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(N.Z,{className:"w-3.5 h-3.5 animate-spin"}),"Copying..."]}):(0,n.jsxs)(n.Fragment,{children:[(0,n.jsx)(D.Z,{className:"w-3.5 h-3.5"}),"Copy selected"]})})]})]})})}},11039:function(e,t,r){r.d(t,{Z:function(){return p}});var n=r(27573),o=r(7653),s=r(84683),a=r(88235),l=r(10075);function i(e){return(0,s.xG)(e)}let d={standard:{label:"Standard",surchargeRate:0,badgeColor:"hsl(var(--muted-foreground))",badgeBg:"hsl(var(--muted))"},priority:{label:"Priority",surchargeRate:.15,badgeColor:"#8A5C10",badgeBg:"#FEF3C7"},emergency:{label:"Emergency",surchargeRate:.25,badgeColor:"#9B1C1C",badgeBg:"#FEE2E2"}};function c(e){let{label:t,color:r,bg:o,small:s}=e;return(0,n.jsx)("span",{className:"inline-flex items-center rounded-full font-semibold tracking-wide ".concat(s?"text-[10px] px-2 py-0.5":"text-xs px-3 py-1"),style:{color:r,backgroundColor:o},children:t})}let u=e=>(0,a.LK)(e,"en");function m(e){return u(e)}function p(e){let{data:t,branding:r,billTo:a,onSave:u,onSend:p,onToggleColumns:x}=e,b=(0,o.useMemo)(()=>{var e,t,n,o;return{companyName:null!==(e=null==r?void 0:r.companyName)&&void 0!==e?e:"Your Company",logoUrl:null==r?void 0:r.logoUrl,accentColor:null!==(t=null==r?void 0:r.accentColor)&&void 0!==t?t:"hsl(var(--primary))",primaryColor:null!==(n=null==r?void 0:r.primaryColor)&&void 0!==n?n:null,brandTokens:null!==(o=null==r?void 0:r.brandTokens)&&void 0!==o?o:null,address:null==r?void 0:r.address,city:null==r?void 0:r.city,state:null==r?void 0:r.state,zip:null==r?void 0:r.zip,phone:null==r?void 0:r.phone,email:null==r?void 0:r.email,website:null==r?void 0:r.website,licenseNumber:null==r?void 0:r.licenseNumber,insuranceInfo:null==r?void 0:r.insuranceInfo,footerText:null==r?void 0:r.footerText,signatureImageUrl:null==r?void 0:r.signatureImageUrl}},[r]),h=(0,o.useMemo)(()=>{var e,r;return t.isNewCustomer?{name:null!==(e=t.newCustomerForm.name)&&void 0!==e?e:"â",company:t.newCustomerForm.company,phone:t.newCustomerForm.phone,email:t.newCustomerForm.email,address:t.newCustomerForm.address}:null!==(r=t.customer)&&void 0!==r?r:{name:"â"}},[t]),f=(0,o.useMemo)(()=>(function(){let e=new Date,t=String(e.getFullYear()).slice(-2),r=String(e.getMonth()+1).padStart(2,"0"),n=String(e.getDate()).padStart(2,"0");return"EST-".concat(t).concat(r).concat(n,"-").concat(Math.floor(1e3+9e3*Math.random()))})(),[]),g=(0,o.useMemo)(()=>new Date,[]),v=(0,o.useMemo)(()=>{let e=new Date(g);return e.setDate(e.getDate()+t.validDays),e},[g,t.validDays]),y=d[t.urgency],j=[b.city,b.state,b.zip].filter(
1Boolean).join(", "),N=[b.address,j].filter(Boolean).join(" \xb7 "),k=b.accentColor,w=(0,o.useMemo)(()=>g.toISOString(),[g]),C=(0,o.useMemo)(()=>v.toISOString(),[v]),S=(0,o.useMemo)(()=>({companyName:b.companyName,logoUrl:b.logoUrl,accentColor:b.accentColor,primaryColor:b.primaryColor,brandTokens:b.brandTokens,companyFullAddress:N,phone:b.phone,email:b.email,website:b.website,licenseNumber:b.licenseNumber,insuranceInfo:b.insuranceInfo,footerText:b.footerText,signatureImageUrl:b.signatureImageUrl,customerName:h.name,customerPhone:h.phone,customerEmail:h.email}),[b,N,h]),I=(0,o.useMemo)(()=>(function(e,t,r,n,o,a){var l,i,d,c,u,m,p,x,b,h,f,g,v,y;let j=e=>e.qty*e.unitPrice,N=e=>{var t,r;return{id:e.id,description:e.description,qty:e.qty,unit:e.unit,unitPrice:e.unitPrice,total:j(e),isOptional:null!==(t=e.isOptional)&&void 0!==t&&t,customerDescription:null!==(r=e.customerDescription)&&void 0!==r?r:null}},k=(e,t)=>e.items.reduce((e,t)=>e+j(t),0)+t.reduce((e,t)=>e+t.items.reduce((e,t)=>e+j(t),0),0),w=e.lineGroups.filter(e=>{var t;return(null!==(t=e.displayMode)&&void 0!==t?t:"expanded")!=="hidden"||!0}),C=new Map(w.map(e=>[e.id,e])),S=new Map,I=[];for(let e of w){let t=e.parentGroupId;if(t&&C.has(t)){let r=null!==(l=S.get(t))&&void 0!==l?l:[];r.push(e),S.set(t,r)}else I.push(e)}let A=I.map(e=>{var t,r,n,o;let s=null!==(t=S.get(e.id))&&void 0!==t?t:[];return{id:e.id,name:e.name,displayMode:null!==(r=e.displayMode)&&void 0!==r?r:"expanded",isOptional:null!==(n=e.isOptional)&&void 0!==n&&n,description:null!==(o=e.description)&&void 0!==o?o:null,subtotal:k(e,s),items:e.items.map(N),subgroups:s.map(e=>{var t,r,n;return{id:e.id,name:e.name,displayMode:null!==(t=e.displayMode)&&void 0!==t?t:"expanded",isOptional:null!==(r=e.isOptional)&&void 0!==r&&r,description:null!==(n=e.description)&&void 0!==n?n:null,subtotal:e.items.reduce((e,t)=>e+j(t),0),items:e.items.map(N),subgroups:[]}})}}),E=e.lineGroups.reduce((e,t)=>e+t.items.reduce((e,t)=>e+t.qty*t.unitPrice,0),0),T=E*("priority"===e.urgency?.15:"emergency"===e.urgency?.25:0),P=!e.discountAmount||e.discountAmount<=0?0:"percent"===e.discountType?e.discountAmount/100*(E+T):e.discountAmount,D=E+T-P,F=(null!==(i=e.taxRate)&&void 0!==i?i:0)/100,O=D*F,M=D+O,Z=e.scopeSpecs&&e.scopeSpecs.length>0?e.scopeSpecs.filter(e=>{var t,r;return(null===(t=e.label)||void 0===t?void 0:t.trim())&&(null===(r=e.value)||void 0===r?void 0:r.trim())}).map(e=>({label:e.label,value:e.value})):e.jobType?[{label:"Job Type",value:e.jobType}]:[],G=[];if(t.companyName){let e=[];t.licenseNumber&&e.push("Lic. #".concat(t.licenseNumber)),t.insuranceInfo&&e.push(t.insuranceInfo),G.push({id:"contractor",name:t.companyName,role:null,phone:t.phone||null,email:t.email||null,variant:"preparedBy",extraLines:e.length>0?e:void 0})}return t.customerName&&"â"!==t.customerName&&G.push({id:"customer",name:t.customerName,role:null,phone:t.customerPhone||null,email:t.customerEmail||null,variant:"preparedFor"}),{branding:{companyName:t.companyName,logoUrl:t.logoUrl,primaryColor:null!==(d=t.primaryColor)&&void 0!==d?d:t.accentColor,accentColor:t.accentColor,brandTokens:null!==(c=t.brandTokens)&&void 0!==c?c:null,address:t.companyFullAddress,phone:t.phone,email:t.email,website:t.website,licenseNumber:t.licenseNumber,insuranceInfo:t.insuranceInfo},doc:{number:r,issuedDate:n,validUntil:o,title:e.jobType||"Estimate",description:e.jobDescription||null},contacts:G,property:e.serviceAddress?{address:e.serviceAddress,sameAsBilling:!1}:null,scope:{narrative:null!==(u=e.scopeOfWork)&&void 0!==u?u:null,specs:Z,includes:(null!==(m=e.scopeIncludes)&&void 0!==m?m:[]).filter(e=>e&&e.trim()),excludes:(null!==(p=e.scopeExcludes)&&void 0!==p?p:[]).filter(e=>e&&e.trim())},groups:A,columns:{showQuantity:null===(x=e.showQuantity)||void 0===x||x,showUnit:null===(b=e.showUnit)||void 0===b||b,showPrice:null===(h=e.showPrice)||void 0===h||h,showAmount:null===(f=e.showAmount)||void 0===f||f,showOrderStatus:null!==(g=e.showOrderStatus)&&void 0!==g&&g,detailLevel:null!==(v=e.detailLevel)&&void 0!==v?v:null},photos:[],totals:{subtotal:E,taxRate:F,taxAmount:O,discountAmount:P,total:M,depositDue:e.depositRequired&&e.depositAmount>0?e.depositAmount:null},schedule:{milestones:(null!==(y=e.paymentMilestones)&&void 0!==y?y:[]).map(e=>{var t;return{id:e.id,label:e.label,trigger:"ON_ESTIMATE_SIGN"===e.triggerKind?"on signing":"when invoiced",auto:"ON_ESTIMATE_SIGN"===e.triggerKind,amount:"PERCENT"===e.amountKind&&null!=e.percent?M*(0,s.Qw)(e.percent):(null!==(t=e.fixedAmountCents)&&void 0!==t?t:0)/100,percent:"PERCENT"===e.amountKind&&null!=e.percent?e.percent:null}})},billTo:null!=a?a:null}})(t,S,f,w,C,a),[t,S,f,w,C,a]);return(0,n.jsxs)("div",{className:"min-h-screen bg-background flex flex-col items-center py-8 px-4",children:[(0,n.jsxs)("article",{className:"w-full max-w-4xl bg-white shadow-xl shadow-foreground
1/[0.08] rounded-xl overflow-hidden","aria-label":"Estimate document",children:[(0,n.jsx)("div",{className:"h-2 w-full",style:{backgroundColor:k}}),(0,n.jsxs)("div",{className:"flex flex-wrap items-center justify-end gap-3 px-8 pt-6",children:[(0,n.jsx)(c,{label:"Draft",color:"hsl(var(--muted-foreground))",bg:"hsl(var(--muted))"}),(0,n.jsx)(c,{label:"".concat(y.label," urgency"),color:y.badgeColor,bg:y.badgeBg,small:!0}),(0,n.jsxs)("span",{className:"text-[11px] text-muted-foreground",children:["Valid for ",t.validDays," ",1===t.validDays?"day":"days"]})]}),x&&(0,n.jsxs)("div",{className:"mx-8 mt-4 mb-0 px-4 py-3 rounded-xl border bg-muted border-border",children:[(0,n.jsx)("p",{className:"text-[10px] font-bold uppercase tracking-[0.1em] text-muted-foreground mb-3",children:"Customer document options"}),(0,n.jsxs)("div",{className:"mb-3",children:[(0,n.jsx)("p",{className:"text-[10px] font-semibold text-muted-foreground uppercase tracking-[0.07em] mb-1.5",children:"Detail level"}),(0,n.jsx)("div",{className:"flex flex-wrap gap-1.5",children:[{value:"itemized",label:"Itemized",hint:"Every line â qty, price, subtotals"},{value:"grouped_subtotals",label:"Grouped subtotals",hint:"Descriptions by section, subtotals, no per-line price"},{value:"subtotals_only",label:"Subtotals only",hint:"Section totals only â no lines, no amounts"},{value:"summary",label:"Summary",hint:"One total per section, sub-sections rolled up"},{value:"lump_sum",label:"Lump sum",hint:"Single grand total only"}].map(e=>{var r;let{value:o,label:s,hint:a}=e,l=(null!==(r=t.detailLevel)&&void 0!==r?r:null)===o;return(0,n.jsx)("button",{type:"button",title:a,onClick:()=>x({detailLevel:o}),className:"px-2.5 py-1 rounded-lg text-[11px] font-semibold transition-colors border",style:l?{background:k,color:"#fff",borderColor:k}:{background:"#fff",color:"hsl(var(--foreground))",borderColor:"hsl(var(--border))"},children:s},String(o))})}),(0,n.jsxs)("p",{className:"text-[10px] text-muted-foreground mt-1.5 leading-snug",children:["itemized"===t.detailLevel&&"Every line with qty + price; group and sub-group subtotals; grand total.",("grouped_subtotals"===t.detailLevel||null==t.detailLevel)&&"Line descriptions by section; subtotal per section and sub-section; no per-line pricing.","subtotals_only"===t.detailLevel&&"Section headings and subtotals only â no line descriptions, no quantities, no per-line prices.","summary"===t.detailLevel&&"One subtotal per top-level section; sub-sections rolled up; grand total.","lump_sum"===t.detailLevel&&"A single grand total â no sections, no lines shown to the customer."]})]}),(0,n.jsx)("p",{className:"text-[10px] text-muted-foreground mt-2 leading-snug",children:"Detail level sets the document-wide default. Toggle individual columns on the live preview below, or set per-section overrides inline on each section header in the builder (use the eye icon on each group)."})]}),(0,n.jsx)(l.Z,{vm:I,t:m,fmt:i,fmtDate:e=>{var t;return e?(t=new Date(e),(0,s.p6)(t,{year:"numeric",month:"long",day:"numeric"})):"â"},onToggleColumns:x}),(0,n.jsxs)("footer",{className:"px-8 pt-6 pb-8 border-t border-border space-y-5",style:{backgroundColor:"hsl(var(--card))"},children:[t.customerNotes&&(0,n.jsxs)("div",{children:[(0,n.jsx)("h4",{className:"text-xs font-bold uppercase tracking-widest mb-1.5",style:{color:k,fontFamily:"var(--font-serif)"},children:"Notes"}),(0,n.jsx)("p",{className:"text-sm text-foreground leading-relaxed whitespace-pre-line",children:t.customerNotes})]}),t.paymentTerms&&(0,n.jsxs)("div",{children:[(0,n.jsx)("h4",{className:"text-xs font-bold uppercase tracking-widest mb-1",style:{color:k,fontFamily:"var(--font-serif)"},children:"Payment Terms"}),(0,n.jsx)("p",{className:"text-sm text-foreground",children:t.paymentTerms})]}),(b.licenseNumber||b.insuranceInfo)&&(0,n.jsxs)("div",{className:"flex flex-wrap gap-x-6 gap-y-1",children:[b.licenseNumber&&(0,n.jsxs)("span",{className:"text-[11px] text-muted-foreground",children:[(0,n.jsx)("strong",{children:"Lic #:"})," ",b.licenseNumber]}),b.insuranceInfo&&(0,n.jsxs)("span",{className:"text-[11px] text-muted-foreground",children:[(0,n.jsx)("strong",{children:"Insurance:"})," ",b.insuranceInfo]})]}),b.footerText&&(0,n.jsx)("p",{className:"text-[11px] text-muted-foreground italic leading-relaxed",children:b.footerText}),(0,n.jsxs)("div",{className:"pt-4 flex flex-col sm:flex-row gap-10 items-start",children:[(0,n.jsxs)("div",{className:"flex flex-col gap-1 min-w-[200px]",children:[(0,n.jsx)("div",{className:"h-12 flex items-end pb-1",children:b.signatureImageUrl?(0,n.jsx)("img",{src:b.signatureImageUrl,alt:"Authorized signature",className:"max-h-12 max-w-[180px] object-contain",crossOrigin:"anonymous"}):(0,n.jsx)("div",{className:"w-48 border-b-2",style:{borderColor:k+"80"},"aria-hidden":"true"})}),(0,n.jsx)("span",{className:"text-[11px] text-muted-foreground font-medium uppercase tracking-wider",children:"Authorized Signature"}),(0,n.jsx)("span",{className:"text-xs text-foreground font-semibold",children:b.companyName})]}),(0,n.jsxs)("div",{className:"flex flex-col gap-1 min-w-[200px]",children:[(0,n.jsx)("div",{className:"h-12 w-48 border-b-2 flex items-end pb-1",style:{borderColor:"hsl(var(--border))"},"aria-hidden":"true"}),(0,n.jsx)("span",{className:"text-[11px] text-muted-foreground font-medium uppercase tracking-wider",children:"Customer Acceptance"}),(0,n.jsx)("span",{className:"text-xs text-foreground",children:h.name})]})]})]})]}),(0,n.jsxs)("div",{className:"flex flex-col sm:flex-row items-center justify-center gap-3 mt-8 w-full max-w-4xl",children:[(0,n.jsx)("button",{type:"button",onClick:u,className:"w-full sm:w-auto min-w-[180px] px-7 py-3 rounded-lg border-2 font-semibold text-sm transition-all duration-150 hover:bg-muted active:scale-[0.97] focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2",style:{borderColor:k,color:k,fontFamily:"var(--font-serif)"},onFocus:e=>e.currentTarget.style.boxShadow="0 0 0 3px ".concat(k,"40"),onBlur:e=>e.currentTarget.style.boxShadow="","aria-label":"Save estimate as draft",children:"Save as Draft"}),(0,n.jsx)("button",{type:"button",onClick:p,className:"w-full sm:w-auto min-w-[180px] px-7 py-3 rounded-lg font-semibold text-sm text-white transition-all duration-150 active:scale-[0.97] focus:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 shadow-md",style:{backgroundColor:k,fontFamily:"var(--font-serif)",boxShadow:"0 4px 14px ".concat(k,"50")},onMouseEnter:e=>e.currentTarget.style.backgroundColor="#A36E08",onMouseLeave:e=>e.currentTarget.style.backgroundColor=k,onFocus:e=>e.currentTarget.style.boxShadow="0 0 0 3px ".concat(k,"40"),onBlur:e=>e.currentTarget.style.boxShadow="0 4px 14px ".concat(k,"50"),"aria-label":"Send estimate to client",children:"Send to Client"})]}),(0,n.jsx)("p",{className:"mt-4 text-[11px] text-muted-foreground",children:"Step 5 of 5 â Review & Send"})]})}},4043:function(e,t,r){r.d(t,{$6:function(){return a},AW:function(){return d},Dk:function(){return s},G:function(){return l}});var n=r(41493);let o=["approved","signed","countersigned","converted","executed","rejected","expired"];function s(e){let{lockedAt:t,status:r}=e;return!!t||!!r&&o.includes(r.toLowerCase())}function a(e){let{signedAt:t,status:r}=e;if(t)return!0;
1if(!r)return!1;let n=r.toLowerCase();return"signed"===n||"countersigned"===n}function l(e){return"/change-orders/new?estimateId=".concat(encodeURIComponent(e))}let i=new Set(["ESTIMATE_LOCKED","SIGNED_ESTIMATE_REQUIRES_CHANGE_ORDER"]);function d(e){var t;if(!(e instanceof n.MS)||!e.code||!i.has(e.code))return null;let r=null===(t=e.details)||void 0===t?void 0:t.nextAction;return{message:e.message,label:null==r?void 0:r.label,href:null==r?void 0:r.href}}},6257:function(e,t,r){r.d(t,{A:function(){return s},I:function(){return l}});var n=r(27573);r(7653);var o=r(29147);function s(e){return null==e?"unknown":e>=80?"high":e>=55?"medium":"low"}let a={high:{label:"Confidence",flagLabel:"High",barClass:"bg-emerald-400",textClass:"text-emerald-700 dark:text-emerald-300",flagClass:"bg-emerald-50 text-emerald-700 border-emerald-200 dark:bg-emerald-950/30 dark:text-emerald-300 dark:border-emerald-800"},medium:{label:"Confidence",flagLabel:"Medium",barClass:"bg-amber-400",textClass:"text-amber-700 dark:text-amber-300",flagClass:"bg-amber-50 text-amber-700 border-amber-200 dark:bg-amber-950/30 dark:text-amber-300 dark:border-amber-800"},low:{label:"Confidence",flagLabel:"Low â edit before sending",barClass:"bg-red-400",textClass:"text-red-700 dark:text-red-300",flagClass:"bg-red-50 text-red-700 border-red-200 dark:bg-red-950/30 dark:text-red-300 dark:border-red-800"},unknown:{label:"Confidence",flagLabel:"Checkingâ¦",barClass:"bg-muted-foreground/30",textClass:"text-muted-foreground",flagClass:"bg-muted text-muted-foreground border-border"}};function l(e){let{score:t,tooltip:r,className:l}=e,i=a[s(t)],d=null!=t?Math.min(100,Math.max(0,t)):0;return(0,n.jsxs)("div",{className:(0,o.cn)("flex items-center gap-2",l),title:r,children:[(0,n.jsx)("span",{className:(0,o.cn)("shrink-0 text-[10.5px] font-bold uppercase tracking-[.04em]",i.textClass),children:i.label}),(0,n.jsx)("div",{className:"h-1 flex-1 overflow-hidden rounded-full bg-muted",role:"progressbar","aria-valuenow":null!=t?t:0,"aria-valuemin":0,"aria-valuemax":100,"aria-label":null!=t?"".concat(t,"%"):"Unknown",children:(0,n.jsx)("div",{className:(0,o.cn)("h-full rounded-full transition-all",i.barClass),style:{width:"".concat(d,"%")}})}),null!=t&&(0,n.jsxs)("span",{className:(0,o.cn)("shrink-0 text-[11.5px] font-bold tabular-nums",i.textClass),children:[t,"%"]}),(0,n.jsx)("span",{className:(0,o.cn)("shrink-0 rounded-full border px-1.5 py-0.5 text-[10.5px] font-bold whitespace-nowrap",i.flagClass),children:i.flagLabel})]})}},24726:function(e,t,r){r.d(t,{w:function(){return x}});var n=r(27573),o=r(7653),s=r(75330),a=r(38983),l=r(10269),i=r(87354),d=r(31503),c=r(39511),u=r(75721),m=r(64099),p=r(17787);function x(e){var t;let{contacts:r,value:x,onChange:b,primaryContactName:h,customerId:f,estimateId:g,onPromoted:v}=e,[y,j]=(0,o.useState)(!1),[N,k]=(0,o.useState)(null),[w,C]=(0,o.useState)(""),[S,I]=(0,o.useState)(""),[A,E]=(0,o.useState)(!1),[T,P]=(0,o.useState)(!1),D=(0,o.useRef)(null),F=(0,o.useRef)(null),O=!!f&&!!g&&!x.contactId&&!!(null===(t=x.serviceContactName)||void 0===t?void 0:t.trim())&&!T,M=(0,o.useCallback)(async()=>{if(f&&g&&!A){E(!0);try{let e=await fetch("/api/customers/".concat(f,"/contacts/promote"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({estimateId:g})});if(201===e.status||200===e.status){let t=await e.json();p.A.success(t.deduped?"Already in contacts":"Saved to contacts"),P(!0),G(),t.contact&&(null==v||v(t.contact))}else if(422===e.status)p.A.error("No on-site contact name to save.");else{let t=await e.json().catch(()=>null);p.A.error((null==t?void 0:t.error)||"Could not save contact.")}}catch(e){p.A.error("Could not save contact.")}finally{E(!1)}}},[f,g,A,v]),Z=function(e,t,r){if(e.contactId){let r=t.find(t=>t.id===e.contactId);if(r)return"".concat(r.firstName," ").concat(r.lastName).trim()}return e.serviceContactName?e.serviceContactName:null!=r?r:"Primary contact"}(x,r,h);function G(){j(!1),k(null)}(0,o.useEffect)(()=>{if("manual"===N){var e,t;C(null!==(e=x.serviceContactName)&&void 0!==e?e:""),I(null!==(t=x.serviceContactPhone)&&void 0!==t?t:""),setTimeout(()=>{var e;return null===(e=F.current)||void 0===e?void 0:e.focus()},50)}},[N,x.serviceContactName,x.serviceContactPhone]),(0,o.useEffect)(()=>
1{if(y)return document.addEventListener("mousedown",e),()=>document.removeEventListener("mousedown",e);function e(e){D.current&&!D.current.contains(e.target)&&(j(!1),k(null))}},[y]);let L=(0,o.useCallback)(e=>{b({contactId:e,serviceContactName:null,serviceContactPhone:null}),G()},[b]),R=x.contactId||x.serviceContactName?"border-primary/60 bg-muted text-foreground":"border-border bg-muted text-muted-foreground",B="w-full rounded-lg border border-border bg-card px-2.5 py-1.5 text-sm text-foreground placeholder:text-muted-foreground/60 focus:border-primary focus:outline-none";return(0,n.jsxs)("div",{className:"relative inline-block",ref:D,children:[(0,n.jsxs)("button",{type:"button",onClick:function(){k("list"),j(!0)},className:"flex items-center gap-1.5 rounded-full border px-3 py-1 text-xs font-medium transition-colors cursor-pointer select-none "+R,"aria-haspopup":"true","aria-expanded":y,"aria-label":"On-site contact",children:[(0,n.jsx)(s.Z,{className:"h-3 w-3 shrink-0"}),(0,n.jsx)("span",{className:"max-w-[160px] truncate",children:Z}),(0,n.jsx)(a.Z,{className:"h-3 w-3 shrink-0 opacity-60"})]}),y&&(0,n.jsxs)("div",{className:"absolute left-0 top-full z-50 mt-1.5 w-64 rounded-xl border border-border bg-card shadow-lg",role:"menu",children:["list"===N&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"flex items-center justify-between border-b border-border px-3 py-2.5",children:[(0,n.jsx)("span",{className:"text-xs font-semibold text-foreground",children:"On-site contact"}),(0,n.jsx)("button",{type:"button",onClick:G,className:"rounded p-0.5 text-muted-foreground hover:text-foreground","aria-label":"Close",children:(0,n.jsx)(l.Z,{className:"h-3.5 w-3.5"})})]}),(0,n.jsx)("div",{className:"max-h-48 overflow-y-auto py-1",children:0===r.length?(0,n.jsx)("p",{className:"px-3 py-2 text-xs text-muted-foreground",children:"No contacts for this customer"}):r.map(e=>{let t="".concat(e.firstName," ").concat(e.lastName).trim(),r=x.contactId===e.id;return(0,n.jsxs)("button",{type:"button",role:"menuitem",onClick:()=>L(e.id),className:"flex w-full items-center gap-2 px-3 py-2 text-sm hover:bg-muted transition-colors "+(r?"font-medium text-primary":"text-foreground"),children:[(0,n.jsx)(s.Z,{className:"h-3.5 w-3.5 shrink-0 opacity-50"}),(0,n.jsx)("span",{className:"flex-1 text-left truncate",children:t}),e.isPrimary&&(0,n.jsx)("span",{className:"shrink-0 rounded-full bg-muted px-1.5 py-0.5 text-[9px] font-semibold uppercase tracking-wide text-muted-foreground",children:"Primary"}),r&&(0,n.jsx)(i.Z,{className:"h-3.5 w-3.5 shrink-0"})]},e.id)})}),(0,n.jsxs)("div",{className:"border-t border-border px-2 py-1.5",children:[(0,n.jsxs)("button",{type:"button",role:"menuitem",onClick:()=>k("manual"),className:"flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-xs text-muted-foreground hover:bg-muted",children:[(0,n.jsx)(d.Z,{className:"h-3.5 w-3.5"}),"Enter manually"]}),(0,n.jsxs)("button",{type:"button",role:"menuitem",onClick:function(){b({contactId:null,serviceContactName:null,serviceContactPhone:null}),G()},className:"flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-xs text-muted-foreground hover:bg-muted",children:[(0,n.jsx)(c.Z,{className:"h-3.5 w-3.5"}),"Same as customer"]}),O&&(0,n.jsxs)("button",{type:"button",role:"menuitem",disabled:A,onClick:M,className:"flex w-full items-center gap-2 rounded-lg px-2 py-1.5 text-xs font-medium text-muted-foreground hover:bg-muted disabled:opacity-50",children:[A?(0,n.jsx)(u.Z,{className:"h-3.5 w-3.5 animate-spin"}):(0,n.jsx)(m.Z,{className:"h-3.5 w-3.5"}),A?"Savingâ¦":"Save as contact"]})]})]}),"manual"===N&&(0,n.jsxs)(n.Fragment,{children:[(0,n.jsxs)("div",{className:"flex items-center justify-between border-b border-border px-3 py-2.5",children:[(0,n.jsx)("span",{className:"text-xs font-semibold text-foreground",children:"Enter contact"}),(0,n.jsx)("button",{type:"button",onClick:()=>k("list"),className:"rounded p-0.5 text-muted-foreground hover:text-foreground","aria-label":"Back",children:(0,n.jsx)(l.Z,{className:"h-3.5 w-3.5"})})]}),(0,n.jsxs)("div",{className:"p-3 space-y-2",children:[(0,n.jsxs)("div",{children:[(0,n.jsx)("label",{htmlFor:"onsite-manual-name",className:"mb-1 block text-xs font-medium text-muted-foreground",children:"Name *"}),(0,n.jsx)("input",{id:"onsite-manual-name",ref:F,type:"text",value:w,onChange:e=>C(e.target.value),placeholder:"Contact name",className:B})]}),(0,n.jsxs)("div",{children:[(0,n.jsx)("label",{htmlFor:"onsite-manual-phone",className:"mb-1 block text-xs font-medium text-muted-foreground",children:"Phone"}),(0,n.jsx)("input",{id:"onsite-manual-phone",type:"tel",value:S,onChange:e=>I(e.target.value),placeholder:"(617) 555-0123",className:B})]}),(0,n.jsxs)("div",{className:"flex items-center justify-end gap-2 pt-1",children:[(0,n.jsx)("button",{type:"button",onClick:()=>k("list"),className:"rounded-lg px-2.5 py-1.5 text-xs font-medium text-muted-foreground hover:bg-muted",children:"Back"}),(0,n.jsx)("button",{type:"button",disabled:!w.trim(),onClick:function(){let e=w.trim(),t=S.trim();e&&(b({contactId:null,serviceContactName:e,serviceContactPhone:t||null}),G())},className:"rounded-lg bg-primary px-2.5 py-1.5 text-xs font-medium text-primary-foreground hover:bg-primary/80 disabled:opacity-50 transition-colors",children:"Save"})]})]})]})]})]})}},51062:function(e,t,r){r.d(t,{Pc:function(){return a},SP:function(){return s},lU:function(){return i},nH:function(){return l},tL:function(){return o}});var n=r(7653);
1function o(e){let[t,r]=(0,n.useState)([]),[o,s]=(0,n.useState)([]),[a,l]=(0,n.useState)(!1),[i,d]=(0,n.useState)(null),[c,u]=(0,n.useState)(0);return(0,n.useEffect)(()=>{if(!e){r([]),s([]);return}let t=!1;return l(!0),d(null),Promise.all([fetch("/api/customers/".concat(e,"/contacts"),{credentials:"include"}).then(e=>e.ok?e.json():null).then(e=>{var t;return null!==(t=null==e?void 0:e.contacts)&&void 0!==t?t:[]}),fetch("/api/customers/".concat(e,"/properties"),{credentials:"include"}).then(e=>e.ok?e.json():null).then(e=>{var t;return null!==(t=null==e?void 0:e.properties)&&void 0!==t?t:[]})]).then(e=>{let[n,o]=e;t||(r(n),s(o))}).catch(e=>{t||d(e instanceof Error?e.message:"Failed to load contacts")}).finally(()=>{t||l(!1)}),()=>{t=!0}},[e,c]),{contacts:t,properties:o,loading:a,error:i,refetch:(0,n.useCallback)(()=>u(e=>e+1),[])}}function s(e,t){let[r,o]=(0,n.useState)([]),[s,a]=(0,n.useState)(!1),l=(0,n.useCallback)(()=>{if(!e||!t){o([]);return}a(!0),fetch("/api/customers/".concat(e,"/estimates/").concat(t,"/recipients"),{credentials:"include"}).then(e=>e.ok?e.json():null).then(e=>{var t;o(null!==(t=null==e?void 0:e.recipients)&&void 0!==t?t:[])}).catch(()=>o([])).finally(()=>a(!1))},[e,t]);return(0,n.useEffect)(()=>
1{l()},[l]),{recipients:r,loading:s,addRecipient:(0,n.useCallback)(async(r,n)=>{e&&t&&(await fetch("/api/customers/".concat(e,"/estimates/").concat(t,"/recipients"),{method:"POST",headers:{"Content-Type":"application/json"},credentials:"include",body:JSON.stringify({contactId:r,role:n})}),l())},[e,t,l]),removeRecipient:(0,n.useCallback)(async r=>{e&&t&&(await fetch("/api/customers/".concat(e,"/estimates/").concat(t,"/recipients/").concat(r),{method:"DELETE",credentials:"include"}),l())},[e,t,l])}}function a(e){let t=[e.firstName,e.lastName].filter(Boolean).join(" "),r=e.role?" (".concat(e.role,")"):e.phone?" \xb7 ".concat(e.phone):"";return"".concat(t).concat(r)}function l(e){var t,r,n;if(0===e.length)return null;let o=e.find(e=>e.isBilling);if(o)return o.id;let s=e.find(e=>e.isPrimary);return null!==(n=null!==(r=null==s?void 0:s.id)&&void 0!==r?r:null===(t=e[0])||void 0===t?void 0:t.id)&&void 0!==n?n:null}function i(e,t,r){if(!t)return null;let n=r.find(e=>e.id===t);if(null==n?void 0:n.primaryContactId)return n.primaryContactId;let o=e.filter(e=>e.linkedPropertyIds.includes(t));return o.length>0?o[0].id:null}},73552:function(e,t,r){r.d(t,{Cp:function(){return i},rz:function(){return d}});var n=r(39155),o=r(41493),s=r(50221),a=r(15671);function l(e){let t=new URLSearchParams;return e.taskName&&t.set("taskName",e.taskName),e.productionRateId&&t.set("productionRateId",e.productionRateId),e.unit&&t.set("unit",e.unit),e.byCrewMember&&t.set("byCrewMember","true"),t.toString()}function i(e,t){let{currentOrgId:r}=(0,s.a)(),i=(0,n.h)({queries:t.map(t=>({queryKey:["production-rate-analytics-catalog-row",r,e,t.taskName,t.unit],queryFn:()=>(0,o.x1)("/api/production-rate-analytics/".concat(encodeURIComponent(e),"?").concat(l({taskName:t.taskName,unit:t.unit,byCrewMember:!0}))),enabled:a.TC&&!!r&&!!e,staleTime:6e4}))});return{rows:t.map((e,t)=>{var r,n,o,s,a;return{rate:e,analytics:null!==(s=null===(n=i[t])||void 0===n?void 0:null===(r=n.data)||void 0===r?void 0:r.analytics)&&void 0!==s?s:null,isLoading:null!==(a=null===(o=i[t])||void 0===o?void 0:o.isLoading)&&void 0!==a&&a}}),isLoading:i.some(e=>e.isLoading)}}function d(e){let{currentOrgId:t}=(0,s.a)(),r=Array.from(new Set(e.filter(Boolean))),i=(0,n.h)({queries:r.map(e=>({queryKey:["learned-rate-hint",t,e],queryFn:async()=>{try{let t=(await (0,o.x1)("/api/production-rates/".concat(e))).rate,r=await (0,o.x1)("/api/production-rate-analytics/".concat(encodeURIComponent(t.trade),"?").concat(l({productionRateId:e,unit:t.unit})));return{rate:t,analytics:r.analytics}}catch(e){return null}},enabled:a.TC&&!!t&&!!e,staleTime:3e5}))}),d=new Map;return r.forEach((e,t)=>{var r,n;let o=null===(r=i[t])||void 0===r?void 0:r.data;if(!o)return;let{rate:s,analytics:a}=o;!(null==a.learned||null==a.catalog||null==a.variancePct||15>Math.abs(a.variancePct))&&(a.sampleSize<5||d.set(e,{productionRateId:e,rate:s,catalog:a.catalog,learned:a.learned,variancePct:a.variancePct,sampleSize:a.sampleSize,confidence:null!==(n=a.confidence)&&void 0!==n?n:0}))}),{hints:d,isLoading:i.some(e=>e.isLoading)}}},37145:function(e,t,r){r.d(t,{BG:function(){return n},Zy:function(){return o}});let n=3;function o(e,t,r){if(null==t)return{ok:!0,newDepth:0};let o=function(e){let t=new Map;for(let n of e){var r;t.set(n.id,null!==(r=n.parentGroupId)&&void 0!==r?r:null)}return t}(r),s=t,a=new Set;for(;null!=s;){if(s===e)return{ok:!1,reason:"cyclic nesting detected"};if(a.has(s))break;a.add(s),s=o.get(s)}let l=function(e,t){let r=0,o=t.get(e),s=n+2,a=0;for(;null!=o&&a<s;)r++,o=t.get(o),a++;return r}(t,o)+1;return l>n?{ok:!1,reason:"max nesting depth is ".concat(n+1," levels; requested depth is ").concat(l+1)}:{ok:!0,newDepth:l}}},32710:function(e,t,r){r.d(t,{Y:function(){return o}});var n=r(41493);async function o(e,t){return"system"===e.source?(await (0,n.x1)("/api/production-rates",{method:"POST",body:JSON.stringify({trade:e.trade,category:e.category,taskName:e.taskName,unit:e.unit,minutesPerUnit:t,defaultCrewSize:e.crewSize,notes:e.notes,systemRateId:e.id})})).rate:(await (0,n.x1)("/api/production-rates/".concat(e.id),{method:"PUT",body:JSON.stringify({minutesPerUnit:t})})).rate}}}]);
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.