import{r as d,j as e,B as Ae,i as ae,z as f,R as ye,C as Ie,o as ke,c as Pe,b as Fe,D as Ce,E as Te,p as we,y as qe,t as Me,x as Re,L as Le,f as $e,q as ze,s as Ue,v as _e,G as Ge}from"./index-9FS9bw8D.js";import{F as Ee,a as We}from"./PlayIcon-CoXqSH0y.js";function Be({title:m,titleId:T,...S},w){return d.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:w,"aria-labelledby":T},S),m?d.createElement("title",{id:T},m):null,d.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15.75 15.75V18m-7.5-6.75h.008v.008H8.25v-.008Zm0 2.25h.008v.008H8.25V13.5Zm0 2.25h.008v.008H8.25v-.008Zm0 2.25h.008v.008H8.25V18Zm2.498-6.75h.007v.008h-.007v-.008Zm0 2.25h.007v.008h-.007V13.5Zm0 2.25h.007v.008h-.007v-.008Zm0 2.25h.007v.008h-.007V18Zm2.504-6.75h.008v.008h-.008v-.008Zm0 2.25h.008v.008h-.008V13.5Zm0 2.25h.008v.008h-.008v-.008Zm0 2.25h.008v.008h-.008V18Zm2.498-6.75h.008v.008h-.008v-.008Zm0 2.25h.008v.008h-.008V13.5ZM8.25 6h7.5v2.25h-7.5V6ZM12 2.25c-1.892 0-3.758.11-5.593.322C5.307 2.7 4.5 3.65 4.5 4.757V19.5a2.25 2.25 0 0 0 2.25 2.25h10.5a2.25 2.25 0 0 0 2.25-2.25V4.757c0-1.108-.806-2.057-1.907-2.185A48.507 48.507 0 0 0 12 2.25Z"}))}const Oe=d.forwardRef(Be);function Ve({title:m,titleId:T,...S},w){return d.createElement("svg",Object.assign({xmlns:"http://www.w3.org/2000/svg",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor","aria-hidden":"true","data-slot":"icon",ref:w,"aria-labelledby":T},S),m?d.createElement("title",{id:T},m):null,d.createElement("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 3c2.755 0 5.455.232 8.083.678.533.09.917.556.917 1.096v1.044a2.25 2.25 0 0 1-.659 1.591l-5.432 5.432a2.25 2.25 0 0 0-.659 1.591v2.927a2.25 2.25 0 0 1-1.244 2.013L9.75 21v-6.568a2.25 2.25 0 0 0-.659-1.591L3.659 7.409A2.25 2.25 0 0 1 3 5.818V4.774c0-.54.384-1.006.917-1.096A48.32 48.32 0 0 1 12 3Z"}))}const Ze=d.forwardRef(Ve),He=({application:m,propertyDetails:T,onClose:S,onComplete:w})=>{const[I,g]=d.useState(!1),[H,j]=d.useState(!1),[J,ee]=d.useState([]),[pe,L]=d.useState(null),[$,M]=d.useState(0),[z,Y]=d.useState(null),[q,F]=d.useState(null),[R,h]=d.useState(null),[Q,G]=d.useState(null),[O,re]=d.useState(0),[ne,oe]=d.useState(0),K=d.useRef(0),W=d.useRef(null),[U,le]=d.useState([]),[V,he]=d.useState(null),[x,Z]=d.useState(null),[B,_]=d.useState("overseed"),b=d.useMemo(()=>{var u,s;return(u=x==null?void 0:x.products)!=null&&u.length?x.products.map(a=>({key:a.id||`${a.productId||"shared"}-${a.userProductId||"user"}`,name:a.productName,brand:a.productBrand,type:a.productType,rateAmount:a.rateAmount,rateUnit:a.rateUnit,productAmount:a.calculatedProductAmount,waterAmount:a.calculatedWaterAmount,targetSpeedMph:a.targetSpeedMph})):(s=m==null?void 0:m.productDetails)!=null&&s.length?m.productDetails.map((a,n)=>({key:`${a.name}-${n}`,name:a.name,brand:a.brand,type:a.type,rateAmount:a.rateAmount,rateUnit:a.rateUnit,productAmount:a.calculatedAmount,waterAmount:a.waterAmount||m.totalWaterAmount,targetSpeedMph:m.avgSpeedMph})):[]},[x,m]);d.useEffect(()=>{console.log("ApplicationExecutionModal - Application data:",m),console.log("ApplicationExecutionModal - Property details:",T),console.log("ApplicationExecutionModal - Application sections:",m.sections),console.log("ApplicationExecutionModal - Application areas:",m.areas),console.log("ApplicationExecutionModal - Sections state:",U),console.log("ApplicationExecutionModal - Map center:",V)},[m,T,U,V]),d.useEffect(()=>{(async()=>{var s;if(m!=null&&m.id)try{const n=(await ae.getPlan(m.id)).data.data.plan;if(console.log("Fetched plan details:",n),console.log("Plan details sections:",n.sections),Z(n),n.sections&&n.sections.length>0){le(n.sections);let o=0,t=0,r=0;if(n.sections.forEach(l=>{var i;let c=l.polygonData;if(typeof c=="string")try{c=JSON.parse(c)}catch(v){console.error("Failed to parse polygon data:",v);return}(i=c==null?void 0:c.coordinates)!=null&&i[0]&&c.coordinates[0].forEach(([v,A])=>{o+=v,t+=A,r++})}),r>0){const l=o/r,c=t/r;he([l,c])}}if((!n.sections||n.sections.length===0)&&(T!=null&&T.sections)){const o=((s=m.sections)==null?void 0:s.map(r=>r.id))||[],t=T.sections.filter(r=>o.includes(r.id));le(t)}}catch(a){console.error("Failed to fetch section data:",a)}})()},[m,T]);const k=d.useMemo(()=>{var s;const u=(x==null?void 0:x.products)||[];if(u.length>0){const a=u.find(n=>n.applicationType==="liquid"||n.productType==="liquid");return a?a.targetSpeedMph||3:null}return((s=m==null?void 0:m.productDetails)==null?void 0:s.length)>0&&m.productDetails.find(n=>n.applicationType==="liquid"||n.type==="liquid")?m.avgSpeedMph||3:null},[m,x]),te=d.useMemo(()=>((x==null?void 0:x.products)||[]).some(u=>(u.productType||"").toLowerCase()==="seed"),[x==null?void 0:x.products]),E=d.useMemo(()=>{if(!k||!$)return"normal";const u=.1,s=k*(1-u),a=k*(1+u);return $a?"fast":"normal"},[$,k]),se=async()=>{try{"wakeLock"in navigator&&(W.current=await navigator.wakeLock.request("screen"))}catch{}},de=async()=>{var u;try{await((u=W.current)==null?void 0:u.release())}catch{}W.current=null},ce=()=>{if(!navigator.geolocation){f.error("GPS not available on this device");return}g(!0),j(!1),z||Y(new Date),se(),h(null),G(null);const u=navigator.geolocation.watchPosition(s=>{const{latitude:a,longitude:n,accuracy:o,speed:t}=s.coords,r=new Date(s.timestamp),l={lat:a,lng:n,accuracy:o,timestamp:r.toISOString(),speed:t||0};if(L(l),R&&Q){const c=fe(R.lat,R.lng,a,n),i=(r-Q)/1e3;if(i>0){const v=c/i*2.237;M(v);const A=K.current+c;K.current=A,re(A);const y=(r-z)/1e3;y>0&&oe(A/y*2.237)}}h({lat:a,lng:n}),G(r),ee(c=>[...c,l])},s=>{console.error("GPS error:",s),f.error(`GPS error: ${s.message}`)},{enableHighAccuracy:!0,timeout:5e3,maximumAge:1e3});F(u)},ie=()=>{q&&(navigator.geolocation.clearWatch(q),F(null)),g(!1),j(!0),de()},P=(u=ne||k||3)=>x!=null&&x.products&&x.products.length>0?x.products.map(s=>{const a={rateAmount:s.rateAmount,rateUnit:s.rateUnit,actualProductAmount:s.actualProductAmount||s.calculatedProductAmount||1,actualWaterAmount:Math.max(s.actualWaterAmount||s.calculatedWaterAmount||1,.1),actualSpeedMph:Math.max(u,.1)};return s.productId&&!isNaN(parseInt(s.productId))&&(a.productId=parseInt(s.productId)),s.userProductId&&!isNaN(parseInt(s.userProductId))&&(a.userProductId=parseInt(s.userProductId)),a}).filter(s=>s.productId||s.userProductId):[],ge=async({gpsTrackData:u,completionNotes:s,fallbackSpeed:a,requireGps:n})=>{var i,v,A,y;const o=U.map(C=>C.id).filter(Boolean),t=o[0]||null,r=(i=x==null?void 0:x.equipment)==null?void 0:i.id,l=P(a);if(!t){f.error("No valid section found for this application"),console.error("Invalid section ID:",t,"Available sections:",U);return}if(!r){f.error("No equipment information found for this application"),console.error("Invalid equipment ID:",r,"Plan details:",x);return}if(l.length===0){f.error("No products found for this application"),console.error("No valid products. Original products:",x==null?void 0:x.products,"Filtered products:",l);return}if(n&&J.length===0){console.warn("No GPS tracking data collected"),f.error("No GPS tracking data was collected. Please ensure location services are enabled.");return}const c={planId:m.id,lawnSectionId:t,lawnSectionIds:o,equipmentId:r,gpsTrack:u,averageSpeed:Math.max(a,.1),areaCovered:Math.max(m.totalSectionArea||m.sectionArea||0,.1),notes:s,products:l};te&&(c.seedingType=B),console.log("Sending log data:",JSON.stringify(c,null,2)),console.log("Total distance being stored:",O),console.log("GPS track data being stored:",u);try{console.log("About to call createLog with data:",JSON.stringify(c,null,2));const C=await ae.createLog(c);console.log("CreateLog response:",C),f.success("Application completed successfully"),ee([]),re(0),K.current=0,oe(0),j(!1),w()}catch(C){console.error("Failed to save application log:",C),console.error("Error details:",(v=C.response)==null?void 0:v.data),console.error("Full error object:",JSON.stringify(C.response||C,null,2)),f.error(`Failed to save application log: ${((y=(A=C.response)==null?void 0:A.data)==null?void 0:y.message)||C.message}`)}},ue=async()=>{ie();const s=z?(new Date-z)/1e3:0,a=Math.round(ne*100)/100,n={points:J.map(o=>({lat:o.lat,lng:o.lng,timestamp:o.timestamp,accuracy:o.accuracy||0,speed:o.speed||0})),totalDistance:Math.round(O*100)/100,duration:Math.round(s),averageSpeed:a};await ge({gpsTrackData:n,completionNotes:`Application completed via mobile tracking. Duration: ${Math.round(s/60)} minutes, Distance: ${(O*3.28084).toFixed(0)} ft, Points: ${J.length}`,fallbackSpeed:a,requireGps:!0})},xe=async()=>{ie(),await ge({gpsTrackData:{points:[],totalDistance:0,duration:0,averageSpeed:Math.round((k||3)*100)/100,assumedCompleteCoverage:!0},completionNotes:`Application manually completed without GPS tracking. Assumed full planned coverage for ${Math.round(m.totalSectionArea||m.sectionArea||0).toLocaleString()} sq ft.`,fallbackSpeed:k||3,requireGps:!1})},fe=(u,s,a,n)=>{const t=u*Math.PI/180,r=a*Math.PI/180,l=(a-u)*Math.PI/180,c=(n-s)*Math.PI/180,i=Math.sin(l/2)*Math.sin(l/2)+Math.cos(t)*Math.cos(r)*Math.sin(c/2)*Math.sin(c/2);return 6371e3*(2*Math.atan2(Math.sqrt(i),Math.sqrt(1-i)))};return d.useEffect(()=>()=>{q&&navigator.geolocation.clearWatch(q),de()},[q]),e.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:e.jsxs("div",{className:"bg-white rounded-lg p-6 w-full max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsxs("div",{className:"flex justify-between items-center mb-6",children:[e.jsx("h3",{className:"text-xl font-semibold",children:"Execute Application"}),e.jsx("button",{onClick:S,className:"text-gray-500 hover:text-gray-700",children:"✕"})]}),e.jsxs("div",{className:"bg-gray-50 p-4 rounded-lg mb-6",children:[e.jsx("h4",{className:"font-medium mb-2",children:"Application Details"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Property:"})," ",m.propertyName]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Areas:"})," ",m.sectionNames]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Equipment:"})," ",m.equipmentName]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Area:"})," ",Math.round(m.totalSectionArea||m.sectionArea||0).toLocaleString()," sq ft"]})]}),e.jsxs("div",{className:"mt-4",children:[e.jsx("h5",{className:"font-medium mb-2",children:"Products to Apply:"}),e.jsx("div",{className:"space-y-2",children:b.length>0?b.map(u=>e.jsxs("div",{className:"bg-white p-2 rounded border text-sm",children:[e.jsx("div",{className:"font-medium",children:u.name}),e.jsxs("div",{className:"text-gray-600",children:["Rate: ",u.rateAmount," ",u.rateUnit,u.productAmount!=null&&` • Product needed: ${Number(u.productAmount).toFixed(2)}`,u.waterAmount!=null&&Number(u.waterAmount)>0&&` • Water needed: ${Number(u.waterAmount).toFixed(2)}`,u.targetSpeedMph!=null&&Number(u.targetSpeedMph)>0&&` • Target speed: ${Number(u.targetSpeedMph).toFixed(2)} mph`]}),u.brand&&e.jsxs("div",{className:"text-gray-500",children:[u.brand,u.type?` • ${u.type}`:""]})]},u.key)):e.jsx("div",{className:"bg-white p-2 rounded border text-sm text-gray-500",children:"No products loaded for this plan yet."})})]})]}),k&&e.jsx("div",{className:`p-4 rounded-lg mb-6 ${E==="normal"?"bg-green-50 border border-green-200":E==="slow"?"bg-yellow-50 border border-yellow-200":"bg-red-50 border border-red-200"}`,children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium",children:"Speed Guidance"}),e.jsxs("p",{className:"text-sm text-gray-600",children:["Target: ",k.toFixed(1)," mph • Current: ",$.toFixed(1)," mph"]})]}),e.jsx("div",{className:`text-lg font-bold ${E==="normal"?"text-green-600":E==="slow"?"text-yellow-600":"text-red-600"}`,children:E==="normal"?"✓ Good Speed":E==="slow"?"↑ Go Faster":"↓ Slow Down"})]})}),e.jsxs("div",{className:"mb-6",children:[e.jsx("h4",{className:"font-medium mb-2",children:"Application Area & GPS Track"}),e.jsx("div",{className:"h-96 border rounded-lg overflow-hidden",children:U.length>0?e.jsx(Ae,{property:T,sections:U,selectedSections:U.map(u=>u.id)||[],mode:"execution",gpsTrack:J,currentLocation:pe,center:V,zoom:V?16:15}):e.jsx("div",{className:"h-full w-full flex items-center justify-center bg-gray-100",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-gray-500 mb-2",children:"Loading map..."}),e.jsxs("div",{className:"text-sm text-gray-400",children:["Sections: ",U.length,", Center: ",V?"Set":"Not set"]})]})})})]}),te&&e.jsxs("div",{className:"bg-green-50 p-4 rounded-lg mb-6",children:[e.jsx("h4",{className:"font-medium mb-2",children:"Seeding Details"}),e.jsxs("div",{className:"flex items-center gap-6 text-sm",children:[e.jsxs("label",{className:"inline-flex items-center gap-2",children:[e.jsx("input",{type:"radio",name:"seedingType",value:"overseed",checked:B==="overseed",onChange:()=>_("overseed")}),"Overseed"]}),e.jsxs("label",{className:"inline-flex items-center gap-2",children:[e.jsx("input",{type:"radio",name:"seedingType",value:"new_seed",checked:B==="new_seed",onChange:()=>_("new_seed")}),"New Seed"]})]})]}),I&&e.jsxs("div",{className:"bg-blue-50 p-4 rounded-lg mb-6",children:[e.jsx("h4",{className:"font-medium mb-2",children:"Tracking Statistics"}),e.jsxs("div",{className:"grid grid-cols-4 gap-4 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Duration:"}),e.jsx("br",{}),z?Math.round((new Date-z)/6e4):0," min"]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Distance:"}),e.jsx("br",{}),(O*3.28084).toFixed(0)," ft"]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Avg Speed:"}),e.jsx("br",{}),ne.toFixed(1)," mph"]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Track Points:"}),e.jsx("br",{}),J.length]})]})]}),e.jsxs("div",{className:"flex gap-3",children:[I?e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:ie,className:"btn-secondary flex-1",children:"Pause Tracking"}),e.jsx("button",{onClick:ue,className:"btn-primary flex-1",children:"Complete Application"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:ce,className:"btn-primary flex-1",children:[H?"Resume":"Start"," Application"]}),e.jsx("button",{onClick:xe,className:"btn-secondary flex-1",children:"Complete Without GPS"})]}),e.jsx("button",{onClick:S,className:"btn-secondary",children:"Cancel"})]})]})})},Je=({onClose:m,properties:T,products:S,equipment:w,nozzles:I,selectedPropertyDetails:g,onPropertySelect:H,editingPlan:j,onSubmit:J})=>{var u;const[ee,pe]=d.useState(""),[L,$]=d.useState([]),[M,z]=d.useState(""),[Y,q]=d.useState(""),[F,R]=d.useState([]),[h,Q]=d.useState(""),[G,O]=d.useState("overseed"),[re,ne]=d.useState(new Date().toISOString().split("T")[0]),[oe,K]=d.useState(""),[W,U]=d.useState(!1),[le,V]=d.useState({}),[he,x]=d.useState(!1),[Z,B]=d.useState(null),[_,b]=d.useState({setting:"",rateDescription:"",notes:""}),k=ye.useMemo(()=>{var s;if(g!=null&&g.latitude&&(g!=null&&g.longitude))return[g.latitude,g.longitude];if(((s=g==null?void 0:g.sections)==null?void 0:s.length)>0){let a=0,n=0,o=0;if(g.sections.forEach(t=>{var l;let r=t.polygonData;if(typeof r=="string")try{r=JSON.parse(r)}catch{return}(l=r==null?void 0:r.coordinates)!=null&&l[0]&&r.coordinates[0].forEach(([c,i])=>{a+=c,n+=i,o++})}),o>0)return[a/o,n/o]}return[39.8283,-98.5795]},[g]);d.useEffect(()=>{var l,c,i,v,A;if(!j)return;const s=((l=j.property)==null?void 0:l.id)||j.propertyId;s&&(pe(String(s)),H&&H(s));const a=(j.sections||j.selectedAreas||[]).map(y=>typeof y=="object"?y.id:y);$(a),((c=j.equipment)!=null&&c.id||j.equipmentId)&&z(String(((i=j.equipment)==null?void 0:i.id)||j.equipmentId)),((v=j.nozzle)!=null&&v.id||j.nozzleId)&&q(String(((A=j.nozzle)==null?void 0:A.id)||j.nozzleId)),ne(j.plannedDate||new Date().toISOString().split("T")[0]),K(j.notes||"");const n=(j.products||[]).map(y=>(y.productType||"").toLowerCase()),o=n.includes("liquid")?"liquid":n.includes("seed")?"seed":"granular",t=(j.applicationType||o).toLowerCase();Q(t),t==="seed"&&O(j.seedingMode||"overseed");const r=(j.products||[]).map(y=>({uniqueId:y.userProductId?`user_${y.userProductId}`:`shared_${y.productId}`,productId:y.productId||null,userProductId:y.userProductId||null,productName:y.productName,productBrand:y.productBrand,productType:y.productType,rateAmount:y.rateAmount,rateUnit:y.rateUnit,isUserProduct:!!y.userProductId}));R(r)},[j,H]);const te=async s=>{pe(s),$([]),s&&H&&await H(s)};ye.useEffect(()=>{console.log("=== ApplicationPlanModal Debug ==="),console.log("selectedPropertyDetails:",g),console.log("mapCenter:",k),console.log("sections:",g==null?void 0:g.sections),console.log(` === EQUIPMENT DEBUG ===`),console.log("equipment array length:",w==null?void 0:w.length),console.log("equipment full array:",w),w&&w.length>0&&(console.log("first equipment item:",w[0]),console.log("equipment field analysis:"),w.forEach((s,a)=>{console.log(`Equipment ${a}:`,{id:s.id,name:s.name,equipment_name:s.equipment_name,custom_name:s.custom_name,category_name:s.category_name,type_name:s.type_name,category:s.category,type:s.type,allFields:Object.keys(s)})})),console.log(` === PRODUCTS DEBUG ===`),console.log("products array length:",S==null?void 0:S.length),console.log("products full array:",S),S&&S.length>0&&(console.log("first product item:",S[0]),console.log("product field analysis:"),S.forEach((s,a)=>{a<3&&console.log(`Product ${a}:`,{id:s.id,name:s.name,product_name:s.product_name,productName:s.productName,brand:s.brand,product_brand:s.product_brand,productBrand:s.productBrand,productType:s.productType,product_type:s.product_type,type:s.type,isShared:s.isShared,uniqueId:s.uniqueId,allFields:Object.keys(s)})})),console.log(` === NOZZLES DEBUG ===`),console.log("nozzles array length:",I==null?void 0:I.length),console.log("nozzles full array:",I),I&&I.length>0&&(console.log("first nozzle item:",I[0]),console.log("nozzle field analysis:"),I.forEach((s,a)=>{console.log(`Nozzle ${a}:`,{id:s.id,name:s.name,custom_name:s.custom_name,manufacturer:s.manufacturer,flow_rate_gpm:s.flow_rate_gpm,orifice_size:s.orifice_size,allFields:Object.keys(s)})})),console.log(`=== End Debug === `)},[g,k,w,S,I]);const E=(s,a)=>{if(!Array.isArray(s)||s.length===0)return null;const n=s.map(l=>({...l,_t:`${l.applicationType||""} ${l.notes||""}`.toLowerCase()})),o=a==="new_seed";let t=n.find(l=>o?l._t.includes("new"):l._t.includes("over"));if(t)return t;const r=s.filter(l=>!isNaN(parseFloat(l.rateAmount)));return r.length?r.reduce((l,c)=>{const i=parseFloat(l.rateAmount),v=parseFloat(c.rateAmount);return o?v>i?c:l:v{$(a=>a.includes(s.id)?a.filter(n=>n!==s.id):[...a,s.id])},de=()=>{R(s=>[...s,{uniqueId:"",productId:null,userProductId:null,productName:"",productBrand:"",productType:h,rateAmount:"",rateUnit:h==="granular"||h==="seed"?"lb/1000sqft":"oz/1000sqft",isUserProduct:!1}])},ce=s=>{Q(s),s==="seed"&&O("overseed"),R([]),setTimeout(()=>{R([{uniqueId:"",productId:null,userProductId:null,productName:"",productBrand:"",productType:s,rateAmount:"",rateUnit:s==="granular"||s==="seed"?"lb/1000sqft":"oz/1000sqft",isUserProduct:!1}])},0)};d.useEffect(()=>{h==="seed"&&R(s=>s.map(a=>{if(a.productType!=="seed"||a.rateAmount)return a;const n=S.find(o=>(o.uniqueId||o.id)===a.uniqueId);if(n&&n.rates&&n.rates.length){const o=E(n.rates,G)||n.rates[0];return{...a,rateAmount:o.rateAmount||o.amount,rateUnit:o.rateUnit||o.unit||"lb/1000sqft"}}return a}))},[G,h,S]);const ie=s=>{R(a=>a.filter((n,o)=>o!==s))},P=(s,a,n)=>{R(o=>o.map((t,r)=>r===s?{...t,[a]:n}:t))},ge=async(s,a)=>{var n;try{const o=(s.isShared,s.id),t=s.isShared?`/api/product-spreader-settings/product/${o}`:`/api/product-spreader-settings/user-product/${o}`;console.log("Checking spreader settings:",{product:s,equipmentId:a,endpoint:t});const r=await fetch(t,{headers:{Authorization:`Bearer ${localStorage.getItem("authToken")}`}});if(r.ok){const l=await r.json();console.log("Spreader settings response:",l);const i=(((n=l.data)==null?void 0:n.settings)||[]).find(v=>(console.log("Comparing setting:",v,"with equipmentId:",a),v.equipmentId===parseInt(a)));console.log("Found equipment setting:",i),i?(console.log("Setting found, storing for calculations"),V(v=>({...v,[`${s.id}_${a}`]:i}))):(console.log("No setting found, showing form"),B(s),x(!0))}else console.log("Response not ok:",r.status)}catch(o){console.error("Failed to check spreader settings:",o)}},ue=async()=>{var s;try{if(!_.setting){f.error("Please enter a setting value");return}const a={equipmentId:parseInt(M),settingValue:_.setting.toString(),rateDescription:_.rateDescription||null,notes:_.notes||null};Z.isShared?a.productId=Z.id:a.userProductId=Z.id;const n=await fetch("/api/product-spreader-settings",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${localStorage.getItem("authToken")}`},body:JSON.stringify(a)});if(n.ok){const o=await n.json();console.log("Spreader setting saved successfully:",o),f.success("Spreader setting added successfully"),(s=o.data)!=null&&s.setting&&V(t=>({...t,[`${Z.id}_${M}`]:o.data.setting})),x(!1),B(null),b({setting:"",rateDescription:"",notes:""})}else{const o=await n.json();throw console.error("Failed to save spreader settings:",o),new Error(o.message||"Failed to save spreader settings")}}catch(a){console.error("Failed to save spreader settings:",a),f.error("Failed to save spreader settings")}},xe=()=>{if(!(g!=null&&g.sections)||L.length===0)return null;const s=L.reduce((t,r)=>{const l=g.sections.find(c=>c.id===r);return t+((l==null?void 0:l.area)||0)},0),a=s*.092903;let n=0;if(h==="liquid"&&Y&&M){const t=I.find(l=>l.id===parseInt(Y)),r=w.find(l=>l.id===parseInt(M));if(t&&r&&t.flowRateGpm&&r.sprayWidthFeet){const l=t.flowRateGpm*3.78541,c=r.sprayWidthFeet*.3048;n=l/(c*107.29)*a*.264172}}const o=F.map(t=>{var l,c;const r=parseFloat(t.rateAmount)||0;if(t.productType==="granular"||t.productType==="seed"){const i=r*s/1e3;return{productName:t.productName,totalProductNeeded:i.toFixed(2),unit:((l=t.rateUnit)==null?void 0:l.replace("/1000sqft","").replace("/1000 sq ft",""))||"lbs",waterNeeded:0}}else{const i=r*s/1e3;return{productName:t.productName,totalProductNeeded:i.toFixed(2),unit:((c=t.rateUnit)==null?void 0:c.replace("/1000sqft","").replace("/1000 sq ft",""))||"oz",waterNeeded:0}}});return{totalArea:s.toLocaleString(),calculations:o,waterNeeded:n>0?n.toFixed(1):0}},fe=async s=>{if(s.preventDefault(),!ee){f.error("Please select a property");return}if(L.length===0){f.error("Please select at least one area");return}if(!M){f.error("Please select equipment");return}if(F.length===0){f.error("Please add at least one product");return}if(!re){f.error("Please select a planned date");return}if(h==="liquid"&&!Y){f.error("Please select a nozzle for liquid applications");return}for(const a of F){if(!a.productId&&!a.userProductId){f.error("Please select a product for all entries");return}if(!a.rateAmount){f.error("Please enter rate amount for all products");return}}U(!0);try{const a={propertyId:parseInt(ee),selectedAreas:L,equipmentId:M,nozzleId:Y||null,applicationType:h,seedingMode:h==="seed"?G:null,plannedDate:re,notes:h==="seed"?`${oe||""} [Seeding: ${G.replace("_"," ")}]`.trim():oe};if(h==="liquid")a.selectedProducts=F.map(n=>({product:S.find(o=>(o.uniqueId||o.id)===n.uniqueId),rateAmount:n.rateAmount,rateUnit:n.rateUnit}));else{const n=F[0],o=S.find(t=>(t.uniqueId||t.id)===n.uniqueId);a.selectedProduct={...o,customRateAmount:n.rateAmount,customRateUnit:n.rateUnit,rateAmount:n.rateAmount,rateUnit:n.rateUnit}}await J(a),m()}catch(a){console.error("Failed to submit plan:",a),f.error("Failed to save application plan")}finally{U(!1)}};return e.jsxs("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:[e.jsxs("div",{className:"bg-white rounded-lg p-6 w-full max-w-6xl mx-4 max-h-[90vh] overflow-y-auto",children:[e.jsxs("div",{className:"flex justify-between items-center mb-6",children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-900",children:j?"Edit Application Plan":"Plan New Application"}),e.jsx("button",{onClick:m,className:"text-gray-400 hover:text-gray-600",children:e.jsx(Ie,{className:"h-6 w-6"})})]}),e.jsxs("form",{onSubmit:fe,children:[e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:[e.jsx(ke,{className:"h-4 w-4 inline mr-1"}),"Property"]}),e.jsxs("select",{value:ee,onChange:s=>te(s.target.value),className:"w-full border border-gray-300 rounded px-3 py-2",required:!0,children:[e.jsx("option",{value:"",children:"Select a property"}),T.map(s=>e.jsxs("option",{value:s.id,children:[s.name," - ",s.address]},s.id))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Planned Date"}),e.jsx("input",{type:"date",value:re,onChange:s=>ne(s.target.value),className:"w-full border border-gray-300 rounded px-3 py-2",required:!0})]}),e.jsx("div",{className:"border rounded-lg p-4 bg-gray-50",children:e.jsxs("div",{className:"grid grid-cols-1 gap-4",children:[e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:[e.jsx(Pe,{className:"h-4 w-4 inline mr-1"}),"Application Type"]}),e.jsxs("div",{className:"flex gap-4",children:[e.jsxs("label",{className:"flex items-center",children:[e.jsx("input",{type:"radio",name:"applicationType",value:"granular",checked:h==="granular",onChange:s=>ce(s.target.value),className:"mr-2"}),"Granular (Spreader)"]}),e.jsxs("label",{className:"flex items-center",children:[e.jsx("input",{type:"radio",name:"applicationType",value:"seed",checked:h==="seed",onChange:s=>ce(s.target.value),className:"mr-2"}),"Seed (Spreader)"]}),e.jsxs("label",{className:"flex items-center",children:[e.jsx("input",{type:"radio",name:"applicationType",value:"liquid",checked:h==="liquid",onChange:s=>ce(s.target.value),className:"mr-2"}),"Liquid (Sprayer)"]})]})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:[e.jsx(Fe,{className:"h-4 w-4 inline mr-1"}),"Equipment *"]}),e.jsxs("select",{value:M,onChange:s=>z(s.target.value),className:"w-full border border-gray-300 rounded px-3 py-2",required:!0,children:[e.jsx("option",{value:"",children:"Select equipment"}),w.filter(s=>h?h==="granular"||h==="seed"?s.categoryName==="Spreader":h==="liquid"?s.categoryName==="Sprayer":!0:!0).map(s=>e.jsxs("option",{value:s.id,children:[s.customName," - ",s.typeName]},s.id))]})]}),h==="liquid"&&M&&e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:["Nozzle Selection *",e.jsx("span",{className:"text-xs text-gray-500 ml-1",children:"(Required for spray calculations)"})]}),e.jsxs("select",{value:Y,onChange:s=>q(s.target.value),className:"w-full border border-gray-300 rounded px-3 py-2",required:h==="liquid",children:[e.jsx("option",{value:"",children:"Select nozzle"}),I.map(s=>e.jsxs("option",{value:s.id,children:[s.customName," - ",s.manufacturer,s.flowRateGpm&&` (${s.flowRateGpm} GPM)`,s.orificeSize&&` - ${s.orificeSize}`]},s.id))]})]})]})}),h==="seed"&&e.jsxs("div",{className:"mb-2",children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Seeding Scenario"}),e.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[e.jsxs("label",{className:"inline-flex items-center gap-2",children:[e.jsx("input",{type:"radio",name:"seed-mode",value:"overseed",checked:G==="overseed",onChange:()=>O("overseed")}),"Overseed"]}),e.jsxs("label",{className:"inline-flex items-center gap-2",children:[e.jsx("input",{type:"radio",name:"seed-mode",value:"new_seed",checked:G==="new_seed",onChange:()=>O("new_seed")}),"New lawn"]})]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex justify-between items-center mb-2",children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700",children:"Products to Apply"}),h==="liquid"&&e.jsx("button",{type:"button",onClick:de,className:"text-blue-600 hover:text-blue-800 text-sm",children:"+ Add Product (Tank Mix)"})]}),F.map((s,a)=>e.jsx("div",{className:"border rounded p-3 mb-3",children:e.jsxs("div",{className:"grid grid-cols-1 gap-3",children:[e.jsxs("select",{value:s.uniqueId||"",onChange:n=>{const o=S.find(t=>(t.uniqueId||t.id)===n.target.value);if(o){P(a,"uniqueId",n.target.value),P(a,"productId",o.isShared?o.id:null),P(a,"userProductId",o.isShared?null:o.id),P(a,"isUserProduct",!o.isShared);const t=o.isShared?o.name:o.customName||o.baseProductName||o.name,r=o.isShared?o.brand:o.customBrand||o.brand||"Unknown Brand";P(a,"productName",t),P(a,"productBrand",r),P(a,"productType",o.productType),console.log("Selected product for rate population:",o);let l=!1;if(o.rates&&o.rates.length>0){let c=o.rates[0];if(h==="seed"){const i=E(o.rates,G);i&&(c=i)}P(a,"rateAmount",c.rateAmount||c.amount),P(a,"rateUnit",c.rateUnit||c.unit||(h==="seed"||h==="granular"?"lb/1000sqft":"oz/1000sqft")),l=!0}else!o.isShared&&o.customRateAmount&&(P(a,"rateAmount",o.customRateAmount),P(a,"rateUnit",o.customRateUnit||(o.productType==="granular"?"lb/1000sqft":"oz/1000sqft")),l=!0);l||(o.productType==="granular"||o.productType==="seed"?P(a,"rateUnit","lb/1000sqft"):o.productType==="liquid"&&P(a,"rateUnit","oz/1000sqft")),(o.productType==="granular"||o.productType==="seed")&&M&&ge(o,M)}},className:"border border-gray-300 rounded px-3 py-2",required:!0,children:[e.jsx("option",{value:"",children:"Select product"}),S.filter(n=>!h||n.productType===h).map(n=>e.jsxs("option",{value:n.uniqueId||n.id,children:[n.isShared?`${n.name} - ${n.brand}`:`${n.customName||n.baseProductName||n.name} - ${n.customBrand||n.brand||"Unknown Brand"}`,n.isShared===!1&&" (Custom)"]},n.uniqueId||n.id))]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-gray-600 mb-1",children:"Application Rate"}),e.jsx("input",{type:"number",step:"0.01",placeholder:"Rate",value:s.rateAmount||"",onChange:n=>P(a,"rateAmount",n.target.value),className:"w-full border border-gray-300 rounded px-3 py-2",required:!0})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-xs text-gray-600 mb-1",children:"Rate Unit"}),e.jsx("select",{value:s.rateUnit||(h==="granular"||h==="seed"?"lb/1000sqft":"oz/1000sqft"),onChange:n=>P(a,"rateUnit",n.target.value),className:"w-full border border-gray-300 rounded px-3 py-2",children:h==="granular"||h==="seed"?e.jsxs(e.Fragment,{children:[e.jsx("option",{value:"lb/1000sqft",children:"lb/1000sqft"}),e.jsx("option",{value:"oz/1000sqft",children:"oz/1000sqft"})]}):e.jsxs(e.Fragment,{children:[e.jsx("option",{value:"oz/1000sqft",children:"oz/1000sqft"}),e.jsx("option",{value:"fl oz/1000sqft",children:"fl oz/1000sqft"}),e.jsx("option",{value:"lb/1000sqft",children:"lb/1000sqft"})]})})]})]}),h==="liquid"&&F.length>1&&e.jsx("div",{className:"flex justify-end",children:e.jsx("button",{type:"button",onClick:()=>ie(a),className:"text-red-600 hover:text-red-800 text-sm",children:"Remove Product"})})]})},a)),F.length===0&&e.jsx("div",{className:"text-center py-4 border-2 border-dashed border-gray-300 rounded",children:e.jsx("p",{className:"text-gray-500 text-sm",children:h?`Select a ${h} product to continue`:"Select application type first"})})]}),F.length>0&&L.length>0&&(()=>{const s=xe();return s?e.jsxs("div",{className:"border rounded-lg p-4 bg-blue-50",children:[e.jsx("h3",{className:"font-medium text-blue-900 mb-2",children:"Application Calculations"}),e.jsxs("div",{className:"text-sm text-blue-800",children:[e.jsxs("p",{className:"mb-2",children:["Total Area: ",s.totalArea," sq ft"]}),s.calculations.map((a,n)=>e.jsxs("div",{className:"mb-2",children:[e.jsxs("p",{className:"font-medium",children:[a.productName,":"]}),e.jsxs("p",{className:"ml-2",children:["Product needed: ",a.totalProductNeeded," ",a.unit]})]},n)),h==="liquid"&&s.waterNeeded>0&&e.jsx("div",{className:"mt-2 pt-2 border-t border-blue-200",children:e.jsxs("p",{className:"font-medium",children:["Water needed: ",s.waterNeeded," gallons"]})})]})]}):null})(),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Notes (Optional)"}),e.jsx("textarea",{value:oe,onChange:s=>K(s.target.value),rows:3,className:"w-full border border-gray-300 rounded px-3 py-2",placeholder:"Add any notes or special instructions..."})]})]}),e.jsxs("div",{children:[((u=g==null?void 0:g.sections)==null?void 0:u.length)>0&&e.jsxs("div",{className:"mb-4",children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Select Areas to Treat"}),e.jsx("div",{className:"max-h-32 overflow-y-auto border rounded p-2 bg-gray-50",children:g.sections.map(s=>e.jsxs("label",{className:"flex items-center py-1 cursor-pointer hover:bg-gray-100 rounded px-2",children:[e.jsx("input",{type:"checkbox",checked:L.includes(s.id),onChange:()=>se(s),className:"mr-2"}),e.jsxs("span",{className:"text-sm",children:[s.name," (",Math.round(s.area||0).toLocaleString()," sq ft)"]})]},s.id))}),L.length>0&&e.jsx("div",{className:"mt-2 p-2 bg-blue-50 rounded",children:e.jsxs("p",{className:"text-sm font-medium text-blue-800",children:["Total Selected: ",L.reduce((s,a)=>{var o;const n=(o=g.sections)==null?void 0:o.find(t=>t.id===a);return s+((n==null?void 0:n.area)||0)},0).toLocaleString()," sq ft"]})})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-2",children:"Property Map"}),e.jsx("div",{className:"h-64 border rounded-lg overflow-hidden",children:g?e.jsx(Ae,{center:k,zoom:16,property:g,sections:g.sections||[],selectedSections:L,mode:"view",editable:!1,className:"h-full w-full"}):e.jsx("div",{className:"h-full w-full flex items-center justify-center bg-gray-100",children:e.jsx("p",{className:"text-gray-500",children:"Select a property to view areas"})})})]})]})]}),e.jsxs("div",{className:"flex justify-end gap-3 mt-6 pt-6 border-t",children:[e.jsx("button",{type:"button",onClick:m,className:"px-4 py-2 text-gray-600 hover:text-gray-800",disabled:W,children:"Cancel"}),e.jsx("button",{type:"submit",className:"px-6 py-2 bg-blue-600 text-white rounded hover:bg-blue-700 disabled:opacity-50",disabled:W,children:W?"Saving...":j?"Update Plan":"Create Plan"})]})]})]}),he&&Z&&e.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-75 flex items-center justify-center",style:{zIndex:9999},children:e.jsxs("div",{className:"bg-white rounded-lg p-6 w-full max-w-md mx-4",children:[e.jsx("h3",{className:"text-lg font-semibold mb-4",children:"Add New Setting"}),e.jsx("div",{className:"mb-4",children:e.jsx("select",{disabled:!0,value:M,className:"w-full border border-gray-300 rounded px-3 py-2 bg-gray-100",children:w.filter(s=>s.id===parseInt(M)).map(s=>{var a;return e.jsxs("option",{value:s.id,children:[s.customName," (",(a=s.categoryName)==null?void 0:a.toLowerCase(),")"]},s.id)})})}),e.jsx("div",{className:"mb-4",children:e.jsx("input",{type:"text",value:_.setting,onChange:s=>b(a=>({...a,setting:s.target.value})),className:"w-full border border-green-400 rounded px-3 py-2 focus:outline-none focus:border-green-500",placeholder:"Setting (e.g., #14, 2.5)"})}),e.jsx("div",{className:"mb-4",children:e.jsx("input",{type:"text",value:_.rateDescription,onChange:s=>b(a=>({...a,rateDescription:s.target.value})),className:"w-full border border-gray-300 rounded px-3 py-2",placeholder:"Rate description (optional)"})}),e.jsx("div",{className:"mb-6",children:e.jsx("textarea",{rows:3,value:_.notes,onChange:s=>b(a=>({...a,notes:s.target.value})),className:"w-full border border-gray-300 rounded px-3 py-2",placeholder:"Notes (optional)"})}),e.jsxs("div",{className:"flex justify-end gap-3",children:[e.jsx("button",{type:"button",onClick:()=>{x(!1),B(null),b({setting:"",rateDescription:"",notes:""})},className:"px-4 py-2 text-gray-600 hover:text-gray-800",children:"Cancel"}),e.jsx("button",{type:"button",onClick:ue,className:"px-4 py-2 bg-blue-500 text-white rounded hover:bg-blue-600",children:"Add Setting"})]})]})})]})},Ke=()=>{const m=Ce(),T=Te(),[S,w]=d.useState(!1),[I,g]=d.useState([]),[H,j]=d.useState(!0),[J,ee]=d.useState([]),[pe,L]=d.useState([]),[$,M]=d.useState([]),[z,Y]=d.useState([]),[q,F]=d.useState(null),[R,h]=d.useState(null),[Q,G]=d.useState({}),[O,re]=d.useState(null),[ne,oe]=d.useState(!1),[K,W]=d.useState(null),[U,le]=d.useState(!1),[V,he]=d.useState(!1),[x,Z]=d.useState(null),[B,_]=d.useState(!1),[b,k]=d.useState({status:"all",dateRange:"all",product:"all",minArea:"",maxArea:"",property:"all"}),[te,E]=d.useState("date"),[se,de]=d.useState("desc"),[ce,ie]=d.useState(!1);d.useEffect(()=>{P(),ge()},[]),d.useEffect(()=>{new URLSearchParams(m.search).get("new")==="plan"&&!S&&(w(!0),T("/applications",{replace:!0}))},[m.search]),d.useEffect(()=>{new URLSearchParams(m.search).get("action")==="log"&&(_(!0),k(r=>({...r,status:"planned"})),ie(!0),T("/applications",{replace:!0}))},[m.search]);const P=async()=>{try{const t=await ae.getPlans();g(t.data.data.plans||[])}catch(t){console.error("Failed to fetch applications:",t),f.error("Failed to load applications")}},ge=async()=>{var t;try{j(!0);const[r,l,c,i]=await Promise.all([we.getAll(),qe.getAll(),Me.getAll(),Re.getAll()]);ee(r.data.data.properties||[]);const v=(l.data.data.sharedProducts||[]).map(C=>({...C,uniqueId:`shared_${C.id}`,isShared:!0})),A=(l.data.data.userProducts||[]).map(C=>({...C,uniqueId:`user_${C.id}`,isShared:!1})),y=[...v,...A];L(y),M(c.data.data.equipment||[]),Y(((t=i.data.data)==null?void 0:t.nozzles)||i.data||[])}catch(r){console.error("Failed to fetch planning data:",r),f.error("Failed to load planning data")}finally{j(!1)}},ue=async t=>{if(!t||isNaN(parseInt(t)))return console.error("Invalid property ID:",t),f.error("Invalid property ID"),F(null),null;if(Q[t])return F(Q[t]),Q[t];try{const l=(await we.getById(parseInt(t))).data.data.property;return G(c=>({...c,[t]:l})),F(l),l}catch(r){return console.error("Failed to fetch property details:",r),f.error("Failed to load property details"),F(null),null}},xe=async(t,r)=>{if(window.confirm(`Are you sure you want to delete the plan for "${r}"?`))try{await ae.deletePlan(t),f.success("Application plan deleted successfully"),P()}catch(l){console.error("Failed to delete plan:",l),f.error("Failed to delete application plan")}},fe=async t=>{try{const l=(await ae.getPlan(t)).data.data.plan;h(l),w(!0)}catch(r){console.error("Failed to fetch plan details:",r),f.error("Failed to load plan details")}},u=async t=>{try{W(t);const r=t.propertyId;r&&(!q||q.id!==r)?await ue(r):r||(console.warn("No property ID found for application:",t),F(null)),le(!0)}catch(r){console.error("Failed to start application execution:",r),f.error("Failed to start application execution")}},s=async t=>{try{Z(t);const r=t.propertyId;r&&(!q||q.id!==r)?await ue(r):r||(console.warn("No property ID found for application:",t),F(null)),he(!0)}catch(r){console.error("Failed to load application details:",r),f.error("Failed to load application details")}},a=async t=>{if(window.confirm("Are you sure you want to archive this application? It will be hidden from the main list but preserved in your records."))try{await ae.updatePlanStatus(t,"archived"),f.success("Application archived successfully"),P()}catch(r){console.error("Failed to archive application:",r),f.error("Failed to archive application")}},n=ye.useMemo(()=>I.filter(r=>{var c,i;if(r.status==="archived"&&b.status!=="archived"||b.status!=="all"&&r.status!==b.status)return!1;if(b.dateRange!=="all"){const v=new Date(r.plannedDate),A=new Date;switch(b.dateRange){case"today":if(v.toDateString()!==A.toDateString())return!1;break;case"week":const y=new Date(A.getTime()-7*24*60*60*1e3);if(vparseInt(b.maxArea)||b.property!=="all"&&r.propertyName!==b.property||b.product!=="all"&&!(((c=r.productDetails)==null?void 0:c.some(A=>A.name.toLowerCase().includes(b.product.toLowerCase())))||((i=r.products)==null?void 0:i.some(A=>{var y;return(y=A.productName)==null?void 0:y.toLowerCase().includes(b.product.toLowerCase())}))))}).sort((r,l)=>{let c,i;switch(te){case"date":c=new Date(r.plannedDate),i=new Date(l.plannedDate);break;case"area":c=r.totalSectionArea||r.sectionArea||0,i=l.totalSectionArea||l.sectionArea||0;break;case"property":c=r.propertyName||"",i=l.propertyName||"";break;case"status":c=r.status||"",i=l.status||"";break;default:return 0}return se==="desc"?i>c?1:ii?1:c[...new Set(I.map(r=>r.propertyName).filter(Boolean))].sort(),[I]);return ye.useMemo(()=>{const t=new Set;return I.forEach(r=>{var l,c;(l=r.productDetails)==null||l.forEach(i=>t.add(i.name)),(c=r.products)==null||c.forEach(i=>i.productName&&t.add(i.productName))}),[...t].sort()},[I]),H?e.jsx("div",{className:"p-6",children:e.jsx("div",{className:"flex justify-center items-center h-64",children:e.jsx(Le,{size:"lg"})})}):e.jsxs("div",{className:"p-6",children:[ce&&e.jsx("div",{className:"mb-4 rounded-md border border-blue-200 bg-blue-50 p-3 text-sm text-blue-800",children:"Select a planned application below and click the Play icon to log it."}),e.jsxs("div",{className:"flex justify-between items-center mb-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-900",children:"Applications"}),e.jsx("p",{className:"text-gray-600",children:"Plan, track, and log your lawn applications"})]}),e.jsxs("button",{onClick:()=>{F(null),w(!0)},className:"btn-primary flex items-center gap-2",children:[e.jsx($e,{className:"h-5 w-5"}),"Plan Application"]})]}),I.length>0&&e.jsx("div",{className:"mb-6",children:e.jsxs("div",{className:"bg-white p-4 rounded-lg shadow",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("button",{onClick:()=>_(!B),className:"flex items-center gap-2 text-gray-700 hover:text-gray-900",children:[e.jsx(Ze,{className:"h-5 w-5"}),"Filters & Sort",B&&e.jsx("span",{className:"text-sm text-gray-500",children:"(hide)"})]}),e.jsxs("div",{className:"text-sm text-gray-600",children:[n.length," of ",I.length," applications"]})]}),B&&e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Status"}),e.jsxs("select",{value:b.status,onChange:t=>k(r=>({...r,status:t.target.value})),className:"w-full border border-gray-300 rounded px-3 py-2 text-sm",children:[e.jsx("option",{value:"all",children:"All Status"}),e.jsx("option",{value:"planned",children:"Planned"}),e.jsx("option",{value:"in_progress",children:"In Progress"}),e.jsx("option",{value:"completed",children:"Completed"}),e.jsx("option",{value:"archived",children:"Archived"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Date Range"}),e.jsxs("select",{value:b.dateRange,onChange:t=>k(r=>({...r,dateRange:t.target.value})),className:"w-full border border-gray-300 rounded px-3 py-2 text-sm",children:[e.jsx("option",{value:"all",children:"All Dates"}),e.jsx("option",{value:"today",children:"Today"}),e.jsx("option",{value:"week",children:"Last Week"}),e.jsx("option",{value:"month",children:"Last Month"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Property"}),e.jsxs("select",{value:b.property,onChange:t=>k(r=>({...r,property:t.target.value})),className:"w-full border border-gray-300 rounded px-3 py-2 text-sm",children:[e.jsx("option",{value:"all",children:"All Properties"}),o.map(t=>e.jsx("option",{value:t,children:t},t))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Sort By"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("select",{value:te,onChange:t=>E(t.target.value),className:"flex-1 border border-gray-300 rounded px-3 py-2 text-sm",children:[e.jsx("option",{value:"date",children:"Date"}),e.jsx("option",{value:"property",children:"Property"}),e.jsx("option",{value:"area",children:"Area Size"}),e.jsx("option",{value:"status",children:"Status"})]}),e.jsx("button",{onClick:()=>de(se==="asc"?"desc":"asc"),className:"px-3 py-2 border border-gray-300 rounded text-sm hover:bg-gray-50",children:se==="desc"?"↓":"↑"})]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Area Range (sq ft)"}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"number",value:b.minArea,onChange:t=>k(r=>({...r,minArea:t.target.value})),placeholder:"Min",className:"flex-1 border border-gray-300 rounded px-3 py-2 text-sm"}),e.jsx("span",{className:"text-gray-500",children:"to"}),e.jsx("input",{type:"number",value:b.maxArea,onChange:t=>k(r=>({...r,maxArea:t.target.value})),placeholder:"Max",className:"flex-1 border border-gray-300 rounded px-3 py-2 text-sm"})]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx("label",{className:"block text-sm font-medium text-gray-700 mb-1",children:"Product Contains"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx("input",{type:"text",value:b.product,onChange:t=>k(r=>({...r,product:t.target.value})),placeholder:"Search products...",className:"flex-1 border border-gray-300 rounded px-3 py-2 text-sm"}),b.product!=="all"&&b.product!==""&&e.jsx("button",{onClick:()=>k(t=>({...t,product:"all"})),className:"px-3 py-2 text-gray-400 hover:text-gray-600",children:e.jsx(Ie,{className:"h-4 w-4"})})]})]}),e.jsx("div",{className:"md:col-span-4 pt-2",children:e.jsx("button",{onClick:()=>{k({status:"all",dateRange:"all",product:"all",minArea:"",maxArea:"",property:"all"}),E("date"),de("desc")},className:"text-sm text-blue-600 hover:text-blue-800",children:"Clear all filters"})})]})]})}),I.length===0?e.jsxs("div",{className:"card text-center py-12",children:[e.jsx(Oe,{className:"h-16 w-16 text-gray-300 mx-auto mb-4"}),e.jsx("h3",{className:"text-lg font-medium text-gray-900 mb-2",children:"No Applications Yet"}),e.jsx("p",{className:"text-gray-600 mb-6",children:"Start by planning your first lawn application"}),e.jsx("button",{onClick:()=>{F(null),w(!0)},className:"btn-primary",children:"Plan Your First Application"})]}):e.jsx("div",{className:"space-y-4",children:n.map(t=>e.jsx("div",{className:"card",children:e.jsxs("div",{className:"flex justify-between items-start",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsxs("h3",{className:"font-semibold text-gray-900",children:[t.propertyName," - ",t.sectionName]}),e.jsx("span",{className:`px-2 py-1 text-xs font-medium rounded-full ${t.status==="planned"?"bg-blue-100 text-blue-800":t.status==="completed"?"bg-green-100 text-green-800":t.status==="in_progress"?"bg-yellow-100 text-yellow-800":"bg-gray-100 text-gray-800"}`,children:t.status})]}),e.jsxs("p",{className:"text-sm text-gray-600 mb-1",children:[e.jsx(ke,{className:"h-4 w-4 inline mr-1"}),t.propertyAddress]}),e.jsxs("p",{className:"text-sm text-gray-600 mb-1",children:["Areas: ",t.sectionNames," (",Math.round(t.totalSectionArea||t.sectionArea||0).toLocaleString()," sq ft)"]}),e.jsxs("p",{className:"text-sm text-gray-600 mb-1",children:["Equipment: ",t.equipmentName]}),e.jsxs("p",{className:"text-sm text-gray-600 mb-1",children:["Products: ",t.productCount]}),(t.totalProductAmount>0||t.productDetails&&t.productDetails.length>0)&&e.jsxs("div",{className:"text-sm text-green-600 mt-2 space-y-1",children:[e.jsx("p",{className:"font-medium",children:"Calculated Requirements:"}),t.productDetails&&t.productDetails.length>1?e.jsxs(e.Fragment,{children:[t.productDetails.map((r,l)=>e.jsxs("p",{children:["• ",r.name,r.brand?` (${r.brand})`:"",": ",r.calculatedAmount.toFixed(2)," oz"]},l)),t.totalWaterAmount>0&&e.jsxs("p",{children:["• Water: ",t.totalWaterAmount.toFixed(2)," gallons"]}),t.avgSpeedMph>0&&e.jsxs("p",{children:["• Target Speed: ",t.avgSpeedMph.toFixed(1)," mph"]}),t.spreaderSetting&&e.jsxs("p",{children:["• Spreader Setting: ",t.spreaderSetting]})]}):e.jsxs(e.Fragment,{children:[t.productDetails&&t.productDetails.length===1?e.jsxs("p",{children:["• ",t.productDetails[0].name,t.productDetails[0].brand?` (${t.productDetails[0].brand})`:"",": ",t.productDetails[0].calculatedAmount.toFixed(2)," ",t.totalWaterAmount>0?"oz":"lbs"]}):e.jsxs("p",{children:["• Product: ",t.totalProductAmount.toFixed(2)," ",t.totalWaterAmount>0?"oz":"lbs"]}),t.totalWaterAmount>0&&e.jsxs("p",{children:["• Water: ",t.totalWaterAmount.toFixed(2)," gallons"]}),t.avgSpeedMph>0&&e.jsxs("p",{children:["• Target Speed: ",t.avgSpeedMph.toFixed(1)," mph"]}),t.spreaderSetting&&e.jsxs("p",{children:["• Spreader Setting: ",t.spreaderSetting]})]})]}),t.notes&&e.jsxs("p",{className:"text-sm text-gray-500 mt-2 italic",children:['"',t.notes,'"']})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-sm font-medium text-gray-900",children:t.plannedDate?new Date(t.plannedDate).toLocaleDateString():"No date set"}),e.jsxs("p",{className:"text-xs text-gray-500",children:["Created ",new Date(t.createdAt).toLocaleDateString()]}),e.jsxs("div",{className:"flex gap-2 mt-2",children:[t.status==="planned"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>u(t),className:"p-1 text-green-600 hover:text-green-800 hover:bg-green-50 rounded",title:"Execute application",children:e.jsx(Ee,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>fe(t.id),className:"p-1 text-blue-600 hover:text-blue-800 hover:bg-blue-50 rounded",title:"Edit plan",children:e.jsx(ze,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>xe(t.id,`${t.propertyName} - ${t.sectionName}`),className:"p-1 text-red-600 hover:text-red-800 hover:bg-red-50 rounded",title:"Delete plan",children:e.jsx(Ue,{className:"h-4 w-4"})})]}),t.status==="completed"&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:()=>s(t),className:"p-1 text-indigo-600 hover:text-indigo-800 hover:bg-indigo-50 rounded",title:"View completed application",children:e.jsx(_e,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>a(t.id),className:"p-1 text-gray-600 hover:text-gray-800 hover:bg-gray-50 rounded",title:"Archive application",children:e.jsx(We,{className:"h-4 w-4"})})]})]})]})]})},t.id))}),S&&e.jsx(Je,{onClose:()=>{w(!1),h(null),F(null)},properties:J,products:pe,equipment:$,nozzles:z,selectedPropertyDetails:q,onPropertySelect:ue,editingPlan:R,onSubmit:async t=>{var r,l,c,i,v,A,y,C,Ne,Se;try{if(R){const p=$.find(N=>N.id===parseInt(t.equipmentId)),X=t.nozzleId?z.find(N=>N.id===parseInt(t.nozzleId)):null,be=t.selectedAreas.reduce((N,D)=>{const me=q.sections.find(je=>je.id===D);return N+((me==null?void 0:me.area)||0)},0),ve={lawnSectionIds:t.selectedAreas.map(N=>parseInt(N)),equipmentId:parseInt(t.equipmentId),...t.applicationType==="liquid"&&t.nozzleId&&{nozzleId:parseInt(t.nozzleId)},plannedDate:t.plannedDate||new Date().toISOString().split("T")[0],notes:t.notes||"",applicationType:t.applicationType,seedingMode:t.seedingMode||null,areaSquareFeet:be,equipment:{id:p==null?void 0:p.id,categoryName:p==null?void 0:p.categoryName,tankSizeGallons:p==null?void 0:p.tankSizeGallons,pumpGpm:p==null?void 0:p.pumpGpm,sprayWidthFeet:p==null?void 0:p.sprayWidthFeet,capacityLbs:p==null?void 0:p.capacityLbs,spreadWidth:p==null?void 0:p.spreadWidth},...t.applicationType==="liquid"&&X&&{nozzle:{id:X.id,flowRateGpm:X.flowRateGpm,sprayAngle:X.sprayAngle}},products:t.applicationType==="liquid"?t.selectedProducts.map(N=>{var D;return{...(D=N.product)!=null&&D.isShared?{productId:parseInt(N.product.id)}:{userProductId:parseInt(N.product.id)},rateAmount:parseFloat(N.rateAmount||1),rateUnit:N.rateUnit||"oz/1000 sq ft",applicationType:t.applicationType==="seed"?"granular":t.applicationType}}):[{...(r=t.selectedProduct)!=null&&r.isShared?{productId:parseInt(t.selectedProduct.id)}:{userProductId:parseInt(t.selectedProduct.id)},rateAmount:parseFloat(((l=t.selectedProduct)==null?void 0:l.customRateAmount)||((c=t.selectedProduct)==null?void 0:c.rateAmount)||1),rateUnit:((i=t.selectedProduct)==null?void 0:i.customRateUnit)||((v=t.selectedProduct)==null?void 0:v.rateUnit)||"per 1000sqft",applicationType:t.applicationType==="seed"?"granular":t.applicationType}]};await ae.updatePlan(R.id,ve),f.success(`Application plan updated successfully for ${t.selectedAreas.length} area(s)`)}else{const p=$.find(N=>N.id===parseInt(t.equipmentId)),X=t.nozzleId?z.find(N=>N.id===parseInt(t.nozzleId)):null,be=t.selectedAreas.reduce((N,D)=>{const me=q.sections.find(je=>je.id===D);return N+((me==null?void 0:me.area)||0)},0),ve={lawnSectionIds:t.selectedAreas.map(N=>parseInt(N)),equipmentId:parseInt(t.equipmentId),...t.applicationType==="liquid"&&t.nozzleId&&{nozzleId:parseInt(t.nozzleId)},plannedDate:new Date().toISOString().split("T")[0],notes:t.notes||"",applicationType:t.applicationType,seedingMode:t.seedingMode||null,areaSquareFeet:be,equipment:{id:p==null?void 0:p.id,categoryName:p==null?void 0:p.categoryName,tankSizeGallons:p==null?void 0:p.tankSizeGallons,pumpGpm:p==null?void 0:p.pumpGpm,sprayWidthFeet:p==null?void 0:p.sprayWidthFeet,capacityLbs:p==null?void 0:p.capacityLbs,spreadWidth:p==null?void 0:p.spreadWidth},...t.applicationType==="liquid"&&X&&{nozzle:{id:X.id,flowRateGpm:X.flowRateGpm,sprayAngle:X.sprayAngle}},products:t.applicationType==="liquid"?t.selectedProducts.map(N=>{var D;return{...(D=N.product)!=null&&D.isShared?{productId:parseInt(N.product.id)}:{userProductId:parseInt(N.product.id)},rateAmount:parseFloat(N.rateAmount||1),rateUnit:N.rateUnit||"oz/1000 sq ft",applicationType:t.applicationType==="seed"?"granular":t.applicationType}}):[{...(A=t.selectedProduct)!=null&&A.isShared?{productId:parseInt(t.selectedProduct.id)}:{userProductId:parseInt(t.selectedProduct.id)},rateAmount:parseFloat(((y=t.selectedProduct)==null?void 0:y.customRateAmount)||((C=t.selectedProduct)==null?void 0:C.rateAmount)||1),rateUnit:((Ne=t.selectedProduct)==null?void 0:Ne.customRateUnit)||((Se=t.selectedProduct)==null?void 0:Se.rateUnit)||"per 1000sqft",applicationType:t.applicationType==="seed"?"granular":t.applicationType}]};await ae.createPlan(ve),f.success(`Created application plan for ${t.selectedAreas.length} area(s) successfully`)}w(!1),h(null),P()}catch(p){console.error("Failed to save application plan:",p),f.error("Failed to save application plan")}}}),U&&K&&e.jsx(He,{application:K,propertyDetails:q,onClose:()=>{le(!1),W(null)},onComplete:()=>{P(),le(!1),W(null)}}),V&&x&&e.jsx(Ge,{application:x,propertyDetails:q,onClose:()=>{he(!1),Z(null)}})]})};export{Ke as default};